text stringlengths 54 60.6k |
|---|
<commit_before>62b5b10c-2e4f-11e5-8eee-28cfe91dbc4b<commit_msg>62bc27b5-2e4f-11e5-856d-28cfe91dbc4b<commit_after>62bc27b5-2e4f-11e5-856d-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <readline/readline.h>
#include <readline/history.h>
#include "sexpr.hpp"
#include "ast.hpp"
#include "eval.hpp"
#include "parse.hpp"
#include "type.hpp"
#include "package.hpp"
#include "argparse.hpp"
struct history {
const std::string filename;
history(const std::string& filename="/tmp/slip.history")
: filename(filename) {
read_history(filename.c_str());
}
~history() {
write_history(filename.c_str());
}
};
template<class F>
static void read_loop(const F& f) {
const history lock;
while(const char* line = readline("> ")) {
if(!*line) continue;
add_history(line);
std::stringstream ss(line);
f(ss);
}
};
template<class Func>
static void lines(const std::string& str, Func func) {
std::stringstream ss(str);
std::string line;
while(std::getline(ss, line)) {
func(line);
}
}
static std::string print_error(const std::exception& e, bool verbose=true,
std::size_t level=0) {
std::stringstream ss;
for(std::size_t i = 0; i < level; ++i) {
ss << " |";
}
const std::string prefix = ss.str();
try {
std::rethrow_if_nested(e);
// last one
return e.what();
} catch(std::exception& e) {
// not last one
if(verbose) {
lines(e.what(), [&](const std::string& line) {
std::cerr << prefix << "- " << line << std::endl;
});
}
return print_error(e, verbose, level + 1);
}
}
int main(int argc, const char** argv) {
using namespace argparse;
const auto parser = argparse::parser()
.flag("debug-gc", "debug garbage collector")
.flag("debug-tc", "debug type checking")
.flag("debug-ast", "debug abstract syntax tree")
.flag("time", "time evaluations")
.flag("verbose", "be verbose")
.flag("help", "show help")
.argument<std::string>("filename", "file to run")
;
const auto options = parser.parse(argc, argv);
if(options.flag("help", false)) {
parser.describe(std::cout);
return 0;
}
package main("main");
main.ts->debug = options.flag("debug-tc", false);
const auto collect = [&] {
const bool debug = options.flag("debug-gc", false);
// mark main package
eval::mark(main.es, debug);
// mark imported packages
for(const package* const* it = &package::first; *it; it = &(*it)->next) {
eval::mark((*it)->es, debug);
}
// and sweep
eval::gc::sweep(debug);
};
{
const type::mono a = main.ts->fresh();
main.def("collect", type::unit >>= type::io(a)(type::unit),
eval::closure(0, [&](const eval::value* ) -> eval::value {
collect();
return unit();
}));
}
static const auto handler =
[&](std::istream& in) {
try {
ast::expr::iter(in, [&](ast::expr e) {
if(options.flag("debug-ast", false)) {
std::cout << "ast: " << e << std::endl;
}
main.exec(e, [&](type::poly p, eval::value v) {
// TODO: cleanup variables with depth greater than current in
// substitution
if(auto self = e.get<ast::var>()) {
std::cout << self->name;
}
std::cout << " : " << p << std::flush
<< " = " << v << std::endl;
});
collect();
});
return true;
} catch(sexpr::error& e) {
std::cerr << "parse error: " << e.what() << std::endl;
} catch(ast::error& e) {
std::cerr << "syntax error: " << e.what() << std::endl;
} catch(type::error& e) {
const std::string what = print_error(e, options.flag("verbose", true));
std::cerr << "type error: " << what << std::endl;
} catch(kind::error& e) {
std::cerr << "kind error: " << e.what() << std::endl;
} catch(std::runtime_error& e) {
std::cerr << "runtime error: " << e.what() << std::endl;
}
return false;
};
if(auto filename = options.get<std::string>("filename")) {
if(auto ifs = std::ifstream(filename->c_str())) {
return handler(ifs) ? 0 : 1;
} else {
std::cerr << "io error: " << "cannot open file " << *filename << std::endl;
return 1;
}
} else {
main.exec(main.resolve("repl"));
read_loop(handler);
}
return 0;
}
<commit_msg>dont time just yet<commit_after>#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <readline/readline.h>
#include <readline/history.h>
#include "sexpr.hpp"
#include "ast.hpp"
#include "eval.hpp"
#include "parse.hpp"
#include "type.hpp"
#include "package.hpp"
#include "argparse.hpp"
struct history {
const std::string filename;
history(const std::string& filename="/tmp/slip.history")
: filename(filename) {
read_history(filename.c_str());
}
~history() {
write_history(filename.c_str());
}
};
template<class F>
static void read_loop(const F& f) {
const history lock;
while(const char* line = readline("> ")) {
if(!*line) continue;
add_history(line);
std::stringstream ss(line);
f(ss);
}
};
template<class Func>
static void lines(const std::string& str, Func func) {
std::stringstream ss(str);
std::string line;
while(std::getline(ss, line)) {
func(line);
}
}
static std::string print_error(const std::exception& e, bool verbose=true,
std::size_t level=0) {
std::stringstream ss;
for(std::size_t i = 0; i < level; ++i) {
ss << " |";
}
const std::string prefix = ss.str();
try {
std::rethrow_if_nested(e);
// last one
return e.what();
} catch(std::exception& e) {
// not last one
if(verbose) {
lines(e.what(), [&](const std::string& line) {
std::cerr << prefix << "- " << line << std::endl;
});
}
return print_error(e, verbose, level + 1);
}
}
int main(int argc, const char** argv) {
using namespace argparse;
const auto parser = argparse::parser()
.flag("debug-gc", "debug garbage collector")
.flag("debug-tc", "debug type checking")
.flag("debug-ast", "debug abstract syntax tree")
// .flag("time", "time evaluations")
.flag("verbose", "be verbose")
.flag("help", "show help")
.argument<std::string>("filename", "file to run")
;
const auto options = parser.parse(argc, argv);
if(options.flag("help", false)) {
parser.describe(std::cout);
return 0;
}
package main("main");
main.ts->debug = options.flag("debug-tc", false);
const auto collect = [&] {
const bool debug = options.flag("debug-gc", false);
// mark main package
eval::mark(main.es, debug);
// mark imported packages
for(const package* const* it = &package::first; *it; it = &(*it)->next) {
eval::mark((*it)->es, debug);
}
// and sweep
eval::gc::sweep(debug);
};
{
const type::mono a = main.ts->fresh();
main.def("collect", type::unit >>= type::io(a)(type::unit),
eval::closure(0, [&](const eval::value* ) -> eval::value {
collect();
return unit();
}));
}
static const auto handler =
[&](std::istream& in) {
try {
ast::expr::iter(in, [&](ast::expr e) {
if(options.flag("debug-ast", false)) {
std::cout << "ast: " << e << std::endl;
}
main.exec(e, [&](type::poly p, eval::value v) {
// TODO: cleanup variables with depth greater than current in
// substitution
if(auto self = e.get<ast::var>()) {
std::cout << self->name;
}
std::cout << " : " << p << std::flush
<< " = " << v << std::endl;
});
collect();
});
return true;
} catch(sexpr::error& e) {
std::cerr << "parse error: " << e.what() << std::endl;
} catch(ast::error& e) {
std::cerr << "syntax error: " << e.what() << std::endl;
} catch(type::error& e) {
const std::string what = print_error(e, options.flag("verbose", true));
std::cerr << "type error: " << what << std::endl;
} catch(kind::error& e) {
std::cerr << "kind error: " << e.what() << std::endl;
} catch(std::runtime_error& e) {
std::cerr << "runtime error: " << e.what() << std::endl;
}
return false;
};
if(auto filename = options.get<std::string>("filename")) {
if(auto ifs = std::ifstream(filename->c_str())) {
return handler(ifs) ? 0 : 1;
} else {
std::cerr << "io error: " << "cannot open file " << *filename << std::endl;
return 1;
}
} else {
main.exec(main.resolve("repl"));
read_loop(handler);
}
return 0;
}
<|endoftext|> |
<commit_before>5f89491c-2d16-11e5-af21-0401358ea401<commit_msg>5f89491d-2d16-11e5-af21-0401358ea401<commit_after>5f89491d-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>e1f325cf-2e4e-11e5-af96-28cfe91dbc4b<commit_msg>e1fa12b0-2e4e-11e5-a5fe-28cfe91dbc4b<commit_after>e1fa12b0-2e4e-11e5-a5fe-28cfe91dbc4b<|endoftext|> |
<commit_before>/*
This file is part of Magnum.
Copyright © 2016 Sam Spilsbury <s@polysquare.org>
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2 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 <cstdlib>
#include <array>
#include <iostream>
#include <libvisual/libvisual.h>
#include <libvisual/lv_common.h>
#include <libvisual/lv_input.h>
#include <libvisual/lv_buffer.h>
#include <Magnum/Buffer.h>
#include <Magnum/DefaultFramebuffer.h>
#include <Magnum/Renderer.h>
#include <Magnum/MeshTools/Interleave.h>
#include <Magnum/MeshTools/CompressIndices.h>
#include <Magnum/MeshTools/Transform.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Primitives/Cube.h>
#include <Magnum/Shaders/Phong.h>
#include <Magnum/Trade/MeshData3D.h>
#include <Magnum/SceneGraph/SceneGraph.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/SceneGraph/MatrixTransformation3D.h>
#include <Magnum/SceneGraph/Drawable.hpp>
#include <Magnum/SceneGraph/Camera3D.hpp>
namespace Magnum { namespace Examples {
typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D;
typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D;
static Trade::MeshData3D barPrimitive(Vector3 const &d) {
return Trade::MeshData3D(MeshPrimitive::Triangles, {
0, 1, 2, 0, 2, 3, /* +Z */
4, 5, 6, 4, 6, 7, /* +X */
8, 9, 10, 8, 10, 11, /* +Y */
12, 13, 14, 12, 14, 15, /* -Z */
16, 17, 18, 16, 18, 19, /* -Y */
20, 21, 22, 20, 22, 23 /* -X */
}, {{
{0.0f, 0.0f, 0.0f},
{ d.x(), 0.0f, 0.0f},
{ d.x(), d.y(), 0.0f}, /* +Z */
{0.0f, d.y(), 0.0f},
{ d.x(), 0.0f, 0.0f},
{ d.x(), 0.0f, -d.z()},
{ d.x(), d.y(), -d.z()}, /* +X */
{ d.x(), d.y(), 0.0f},
{0.0f, d.y(), -d.z() + d.z()},
{ d.x(), d.y(), 0.0f},
{ d.x(), d.y(), -d.z()}, /* +Y */
{0.0f, d.y(), -d.z()},
{ d.x(), 0.0f, -d.z()},
{0.0f, 0.0f, -d.z()},
{0.0f, d.y(), -d.z()}, /* -Z */
{ d.x(), d.y(), -d.z()},
{0.0f, 0.0f, -d.z()},
{ d.x(), 0.0f, -d.z()},
{ d.x(), 0.0f, 0.0f}, /* -Y */
{0.0f, 0.0f, 0.0f},
{0.0f, 0.0f, -d.z()},
{0.0f, 0.0f, 0.0f},
{0.0f, d.y(), 0.0f}, /* -X */
{0.0f, d.y(), -d.z()}
}}, {{
{ 0.0f, 0.0f, 1.0f},
{ 0.0f, 0.0f, 1.0f},
{ 0.0f, 0.0f, 1.0f}, /* +Z */
{ 0.0f, 0.0f, 1.0f},
{ 1.0f, 0.0f, 0.0f},
{ 1.0f, 0.0f, 0.0f},
{ 1.0f, 0.0f, 0.0f}, /* +X */
{ 1.0f, 0.0f, 0.0f},
{ 0.0f, 1.0f, 0.0f},
{ 0.0f, 1.0f, 0.0f},
{ 0.0f, 1.0f, 0.0f}, /* +Y */
{ 0.0f, 1.0f, 0.0f},
{ 0.0f, 0.0f, -1.0f},
{ 0.0f, 0.0f, -1.0f},
{ 0.0f, 0.0f, -1.0f}, /* -Z */
{ 0.0f, 0.0f, -1.0f},
{ 0.0f, -1.0f, 0.0f},
{ 0.0f, -1.0f, 0.0f},
{ 0.0f, -1.0f, 0.0f}, /* -Y */
{ 0.0f, -1.0f, 0.0f},
{-1.0f, 0.0f, 0.0f},
{-1.0f, 0.0f, 0.0f},
{-1.0f, 0.0f, 0.0f}, /* -X */
{-1.0f, 0.0f, 0.0f}
}}, {});
}
class Bar:
public Object3D,
public SceneGraph::Drawable3D
{
public:
Mesh &mesh;
Shaders::Phong &shader;
Color3 color;
std::array<float, 100> const &heightMap;
size_t heightMapIndex;
Bar(Object3D &parent,
Mesh &mesh,
Shaders::Phong &shader,
Color3 const &color,
SceneGraph::DrawableGroup3D &group,
std::array<float, 100> const &heightMap,
size_t heightMapIndex);
void draw(Matrix4 const &transformationMatrix,
SceneGraph::Camera3D &camera) override;
};
Bar::Bar(Object3D &parent,
Mesh &mesh,
Shaders::Phong &shader,
Color3 const &color,
SceneGraph::DrawableGroup3D &group,
std::array<float, 100> const &heightMap,
size_t heightMapIndex):
Object3D(&parent),
SceneGraph::Drawable3D(*this, &group),
mesh(mesh),
shader(shader),
color(color),
heightMap(heightMap),
heightMapIndex(heightMapIndex)
{
}
void Bar::draw(Matrix4 const &transformationMatrix,
SceneGraph::Camera3D &camera)
{
Matrix4 transform(Matrix4::translation(Vector3(-0.5f, -0.5f, -1.4f * 2)) *
transformationMatrix *
Matrix4::scaling(Vector3(1.0f, heightMap[heightMapIndex], 1.0f)));
shader.setDiffuseColor(Color4(color, 0.0f))
.setAmbientColor(Color4(Color3::fromHSV(color.hue(), 1.0f, 0.3f), 0.0f))
.setTransformationMatrix(transform)
.setNormalMatrix(transform.rotationScaling());
mesh.draw(shader);
}
class Floor: public Platform::Application {
public:
explicit Floor(const Arguments& arguments);
private:
void drawEvent() override;
Scene3D scene;
SceneGraph::DrawableGroup3D drawables;
Object3D cameraObject;
SceneGraph::Camera3D camera;
Buffer _vertexBuffer, _indexBuffer;
Mesh _mesh;
Shaders::Phong _shader;
std::array<float, 100> heights;
LV::InputPtr visualizerInput;
};
Floor::Floor(const Arguments& arguments):
Platform::Application{arguments, Configuration{}.setTitle("FMV")},
cameraObject(&scene),
camera(cameraObject),
visualizerInput(LV::Input::load("mplayer"))
{
visualizerInput->realize();
Renderer::enable(Renderer::Feature::DepthTest);
Renderer::enable(Renderer::Feature::FaceCulling);
Trade::MeshData3D cube = barPrimitive(Vector3(1.0f, 1.0f, 1.0f));
_vertexBuffer.setData(MeshTools::interleave(cube.positions(0), cube.normals(0)), BufferUsage::StaticDraw);
Containers::Array<char> indexData;
Mesh::IndexType indexType;
UnsignedInt indexStart, indexEnd;
std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cube.indices());
_indexBuffer.setData(indexData, BufferUsage::StaticDraw);
_mesh.setPrimitive(cube.primitive())
.setCount(cube.indices().size())
.addVertexBuffer(_vertexBuffer, 0, Shaders::Phong::Position{}, Shaders::Phong::Normal{})
.setIndexBuffer(_indexBuffer, 0, indexType, indexStart, indexEnd);
auto step = 18;
for (size_t i = 0; i < 10; ++i) {
for (size_t j = 0; j < 10; ++j) {
(new Bar(cameraObject,
_mesh,
_shader,
Color3::fromHSV(Deg(j * step + i * step * 0.1), 1.0f, 1.0f),
drawables,
heights,
i * 10 + j))
->scale(Vector3(0.1, 1.0, 0.1))
.translate(Vector3(0.1 * j, 0.0, -0.1 * i));
heights[j + i * 10] = 0.1;
}
}
camera.setProjectionMatrix(Matrix4::perspectiveProjection(20.0_degf, 1.0f, 0.01f, 100.0f))
.setViewport(defaultFramebuffer.viewport().size());
setSwapInterval(1);
setMinimalLoopPeriod(16);
}
constexpr static int sample(size_t index) {
return static_cast<int>(std::exp((index / 10.0) * log(255.0)));
}
constexpr static const std::array<int, 10> SampleRanges = {
sample(1),
sample(2),
sample(3),
sample(4),
sample(5),
sample(6),
sample(7),
sample(8),
sample(9),
sample(10)
};
void Floor::drawEvent() {
defaultFramebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth);
_shader.setLightColor(Color3{1.0f})
.setProjectionMatrix(camera.projectionMatrix())
.setLightPosition({0.5f, 1.0f, -0.5f});
camera.draw(drawables);
swapBuffers();
redraw();
visualizerInput->run();
auto const &audio = visualizerInput->get_audio();
auto pcm_buffer = LV::Buffer::create(512 * sizeof(float));
auto freq_buffer = LV::Buffer::create(256 * sizeof(float));
const_cast<LV::Audio *>(&audio)->get_sample_mixed_simple(pcm_buffer,
2,
VISUAL_AUDIO_CHANNEL_LEFT,
VISUAL_AUDIO_CHANNEL_RIGHT,
nullptr);
LV::Audio::get_spectrum_for_sample(freq_buffer, pcm_buffer, true);
float *frequenciesData = static_cast<float *>(freq_buffer->get_data());
/* Prepare height-map - first row is all random, the next rows follow on
* from the previous height */
for (size_t i = 0; i < 10; ++i) {
/* Go through the sample ranges until we reach the frequency with the
* highest amplitude in the current sample range */
float highestAmplitudeInRange = 0.0f;
const int sampleRangeStart = SampleRanges[i];
const int sampleRangeEnd = SampleRanges[i + 1];
for (int currentSampleFrequency = sampleRangeStart;
currentSampleFrequency <= sampleRangeEnd;
currentSampleFrequency++) {
if (frequenciesData[currentSampleFrequency] > highestAmplitudeInRange) {
highestAmplitudeInRange = frequenciesData[currentSampleFrequency];
}
}
heights[i] = heights[i] * 0.5f + (highestAmplitudeInRange * 0.5f) + 0.05f;
}
for (size_t i = 0; i < 10; ++i) {
for (size_t j = 1; j < 10; ++j) {
heights[j * 10 + i] = (heights[j * 10 + i] / 2.0f) + (heights[(j - 1) * 10 + i] / 2.0f);
}
}
}
}}
int main(int argc, char **argv)
{
LV::System::init(argc, argv);
Magnum::Examples::Floor app(Magnum::Examples::Floor::Arguments(argc, argv));
int code = app.exec();
LV::System::destroy();
return code;
}
<commit_msg>Clarify that this is not a part of magnum (though it uses it)<commit_after>/*
Copyright © 2016 Sam Spilsbury <s@polysquare.org>
Copyright © 2010, 2011, 2012, 2013, 2014, 2015
Vladimír Vondruš <mosra@centrum.cz>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2 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 <cstdlib>
#include <array>
#include <iostream>
#include <libvisual/libvisual.h>
#include <libvisual/lv_common.h>
#include <libvisual/lv_input.h>
#include <libvisual/lv_buffer.h>
#include <Magnum/Buffer.h>
#include <Magnum/DefaultFramebuffer.h>
#include <Magnum/Renderer.h>
#include <Magnum/MeshTools/Interleave.h>
#include <Magnum/MeshTools/CompressIndices.h>
#include <Magnum/MeshTools/Transform.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Primitives/Cube.h>
#include <Magnum/Shaders/Phong.h>
#include <Magnum/Trade/MeshData3D.h>
#include <Magnum/SceneGraph/SceneGraph.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/SceneGraph/MatrixTransformation3D.h>
#include <Magnum/SceneGraph/Drawable.hpp>
#include <Magnum/SceneGraph/Camera3D.hpp>
namespace Magnum { namespace Examples {
typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D;
typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D;
static Trade::MeshData3D barPrimitive(Vector3 const &d) {
return Trade::MeshData3D(MeshPrimitive::Triangles, {
0, 1, 2, 0, 2, 3, /* +Z */
4, 5, 6, 4, 6, 7, /* +X */
8, 9, 10, 8, 10, 11, /* +Y */
12, 13, 14, 12, 14, 15, /* -Z */
16, 17, 18, 16, 18, 19, /* -Y */
20, 21, 22, 20, 22, 23 /* -X */
}, {{
{0.0f, 0.0f, 0.0f},
{ d.x(), 0.0f, 0.0f},
{ d.x(), d.y(), 0.0f}, /* +Z */
{0.0f, d.y(), 0.0f},
{ d.x(), 0.0f, 0.0f},
{ d.x(), 0.0f, -d.z()},
{ d.x(), d.y(), -d.z()}, /* +X */
{ d.x(), d.y(), 0.0f},
{0.0f, d.y(), -d.z() + d.z()},
{ d.x(), d.y(), 0.0f},
{ d.x(), d.y(), -d.z()}, /* +Y */
{0.0f, d.y(), -d.z()},
{ d.x(), 0.0f, -d.z()},
{0.0f, 0.0f, -d.z()},
{0.0f, d.y(), -d.z()}, /* -Z */
{ d.x(), d.y(), -d.z()},
{0.0f, 0.0f, -d.z()},
{ d.x(), 0.0f, -d.z()},
{ d.x(), 0.0f, 0.0f}, /* -Y */
{0.0f, 0.0f, 0.0f},
{0.0f, 0.0f, -d.z()},
{0.0f, 0.0f, 0.0f},
{0.0f, d.y(), 0.0f}, /* -X */
{0.0f, d.y(), -d.z()}
}}, {{
{ 0.0f, 0.0f, 1.0f},
{ 0.0f, 0.0f, 1.0f},
{ 0.0f, 0.0f, 1.0f}, /* +Z */
{ 0.0f, 0.0f, 1.0f},
{ 1.0f, 0.0f, 0.0f},
{ 1.0f, 0.0f, 0.0f},
{ 1.0f, 0.0f, 0.0f}, /* +X */
{ 1.0f, 0.0f, 0.0f},
{ 0.0f, 1.0f, 0.0f},
{ 0.0f, 1.0f, 0.0f},
{ 0.0f, 1.0f, 0.0f}, /* +Y */
{ 0.0f, 1.0f, 0.0f},
{ 0.0f, 0.0f, -1.0f},
{ 0.0f, 0.0f, -1.0f},
{ 0.0f, 0.0f, -1.0f}, /* -Z */
{ 0.0f, 0.0f, -1.0f},
{ 0.0f, -1.0f, 0.0f},
{ 0.0f, -1.0f, 0.0f},
{ 0.0f, -1.0f, 0.0f}, /* -Y */
{ 0.0f, -1.0f, 0.0f},
{-1.0f, 0.0f, 0.0f},
{-1.0f, 0.0f, 0.0f},
{-1.0f, 0.0f, 0.0f}, /* -X */
{-1.0f, 0.0f, 0.0f}
}}, {});
}
class Bar:
public Object3D,
public SceneGraph::Drawable3D
{
public:
Mesh &mesh;
Shaders::Phong &shader;
Color3 color;
std::array<float, 100> const &heightMap;
size_t heightMapIndex;
Bar(Object3D &parent,
Mesh &mesh,
Shaders::Phong &shader,
Color3 const &color,
SceneGraph::DrawableGroup3D &group,
std::array<float, 100> const &heightMap,
size_t heightMapIndex);
void draw(Matrix4 const &transformationMatrix,
SceneGraph::Camera3D &camera) override;
};
Bar::Bar(Object3D &parent,
Mesh &mesh,
Shaders::Phong &shader,
Color3 const &color,
SceneGraph::DrawableGroup3D &group,
std::array<float, 100> const &heightMap,
size_t heightMapIndex):
Object3D(&parent),
SceneGraph::Drawable3D(*this, &group),
mesh(mesh),
shader(shader),
color(color),
heightMap(heightMap),
heightMapIndex(heightMapIndex)
{
}
void Bar::draw(Matrix4 const &transformationMatrix,
SceneGraph::Camera3D &camera)
{
Matrix4 transform(Matrix4::translation(Vector3(-0.5f, -0.5f, -1.4f * 2)) *
transformationMatrix *
Matrix4::scaling(Vector3(1.0f, heightMap[heightMapIndex], 1.0f)));
shader.setDiffuseColor(Color4(color, 0.0f))
.setAmbientColor(Color4(Color3::fromHSV(color.hue(), 1.0f, 0.3f), 0.0f))
.setTransformationMatrix(transform)
.setNormalMatrix(transform.rotationScaling());
mesh.draw(shader);
}
class Floor: public Platform::Application {
public:
explicit Floor(const Arguments& arguments);
private:
void drawEvent() override;
Scene3D scene;
SceneGraph::DrawableGroup3D drawables;
Object3D cameraObject;
SceneGraph::Camera3D camera;
Buffer _vertexBuffer, _indexBuffer;
Mesh _mesh;
Shaders::Phong _shader;
std::array<float, 100> heights;
LV::InputPtr visualizerInput;
};
Floor::Floor(const Arguments& arguments):
Platform::Application{arguments, Configuration{}.setTitle("FMV")},
cameraObject(&scene),
camera(cameraObject),
visualizerInput(LV::Input::load("mplayer"))
{
visualizerInput->realize();
Renderer::enable(Renderer::Feature::DepthTest);
Renderer::enable(Renderer::Feature::FaceCulling);
Trade::MeshData3D cube = barPrimitive(Vector3(1.0f, 1.0f, 1.0f));
_vertexBuffer.setData(MeshTools::interleave(cube.positions(0), cube.normals(0)), BufferUsage::StaticDraw);
Containers::Array<char> indexData;
Mesh::IndexType indexType;
UnsignedInt indexStart, indexEnd;
std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cube.indices());
_indexBuffer.setData(indexData, BufferUsage::StaticDraw);
_mesh.setPrimitive(cube.primitive())
.setCount(cube.indices().size())
.addVertexBuffer(_vertexBuffer, 0, Shaders::Phong::Position{}, Shaders::Phong::Normal{})
.setIndexBuffer(_indexBuffer, 0, indexType, indexStart, indexEnd);
auto step = 18;
for (size_t i = 0; i < 10; ++i) {
for (size_t j = 0; j < 10; ++j) {
(new Bar(cameraObject,
_mesh,
_shader,
Color3::fromHSV(Deg(j * step + i * step * 0.1), 1.0f, 1.0f),
drawables,
heights,
i * 10 + j))
->scale(Vector3(0.1, 1.0, 0.1))
.translate(Vector3(0.1 * j, 0.0, -0.1 * i));
heights[j + i * 10] = 0.1;
}
}
camera.setProjectionMatrix(Matrix4::perspectiveProjection(20.0_degf, 1.0f, 0.01f, 100.0f))
.setViewport(defaultFramebuffer.viewport().size());
setSwapInterval(1);
setMinimalLoopPeriod(16);
}
constexpr static int sample(size_t index) {
return static_cast<int>(std::exp((index / 10.0) * log(255.0)));
}
constexpr static const std::array<int, 10> SampleRanges = {
sample(1),
sample(2),
sample(3),
sample(4),
sample(5),
sample(6),
sample(7),
sample(8),
sample(9),
sample(10)
};
void Floor::drawEvent() {
defaultFramebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth);
_shader.setLightColor(Color3{1.0f})
.setProjectionMatrix(camera.projectionMatrix())
.setLightPosition({0.5f, 1.0f, -0.5f});
camera.draw(drawables);
swapBuffers();
redraw();
visualizerInput->run();
auto const &audio = visualizerInput->get_audio();
auto pcm_buffer = LV::Buffer::create(512 * sizeof(float));
auto freq_buffer = LV::Buffer::create(256 * sizeof(float));
const_cast<LV::Audio *>(&audio)->get_sample_mixed_simple(pcm_buffer,
2,
VISUAL_AUDIO_CHANNEL_LEFT,
VISUAL_AUDIO_CHANNEL_RIGHT,
nullptr);
LV::Audio::get_spectrum_for_sample(freq_buffer, pcm_buffer, true);
float *frequenciesData = static_cast<float *>(freq_buffer->get_data());
/* Prepare height-map - first row is all random, the next rows follow on
* from the previous height */
for (size_t i = 0; i < 10; ++i) {
/* Go through the sample ranges until we reach the frequency with the
* highest amplitude in the current sample range */
float highestAmplitudeInRange = 0.0f;
const int sampleRangeStart = SampleRanges[i];
const int sampleRangeEnd = SampleRanges[i + 1];
for (int currentSampleFrequency = sampleRangeStart;
currentSampleFrequency <= sampleRangeEnd;
currentSampleFrequency++) {
if (frequenciesData[currentSampleFrequency] > highestAmplitudeInRange) {
highestAmplitudeInRange = frequenciesData[currentSampleFrequency];
}
}
heights[i] = heights[i] * 0.5f + (highestAmplitudeInRange * 0.5f) + 0.05f;
}
for (size_t i = 0; i < 10; ++i) {
for (size_t j = 1; j < 10; ++j) {
heights[j * 10 + i] = (heights[j * 10 + i] / 2.0f) + (heights[(j - 1) * 10 + i] / 2.0f);
}
}
}
}}
int main(int argc, char **argv)
{
LV::System::init(argc, argv);
Magnum::Examples::Floor app(Magnum::Examples::Floor::Arguments(argc, argv));
int code = app.exec();
LV::System::destroy();
return code;
}
<|endoftext|> |
<commit_before>cd306111-2d3e-11e5-a71a-c82a142b6f9b<commit_msg>cd8f8385-2d3e-11e5-a84f-c82a142b6f9b<commit_after>cd8f8385-2d3e-11e5-a84f-c82a142b6f9b<|endoftext|> |
<commit_before>dc3db94f-2e4e-11e5-a960-28cfe91dbc4b<commit_msg>dc44ba66-2e4e-11e5-9630-28cfe91dbc4b<commit_after>dc44ba66-2e4e-11e5-9630-28cfe91dbc4b<|endoftext|> |
<commit_before>
# include "List.h"
# include "Debug.h"
# include "Zalloc.h"
# include "ClassFile.h"
# include "MemberInfo.h"
# include "ConstantInfo.h"
# include "AttributeInfo.h"
void encodeConstantPool(ClassFile *classFile, ClassBuilder *builder) {
unsigned int length;
buildNextShort(builder, length = classFile->constant_pool.size());
debug_printf(level1, "Constant Pool Count : %d.\n", length);
for(unsigned idx = 1; idx < length; idx++) {
ConstantInfo *info;
debug_printf(level2, "Constant %d :\n", idx);
info = static_cast(ConstantInfo *, classFile->constant_pool[idx]);
encodeConstant(builder, info);
if(isLongConstant(info)) {
debug_printf(level2, "Long Constant; Skipping index.\n");
idx++;
}
}
}
void encodeThisClass(ClassFile *classFile, ClassBuilder *builder) {
if(classFile->this_class != NULL) {
uint16_t index = classFile->this_class->index;
debug_printf(level3, "This Class : %d.\n", index);
buildNextShort(builder, index);
} else {
// No ThisClass Entry
debug_printf(level3, "This Class : <NULL>.\n");
buildNextShort(builder, 0);
}
}
void encodeSuperClass(ClassFile *classFile, ClassBuilder *builder) {
if(classFile->super_class != NULL) {
uint16_t index = classFile->super_class->index;
debug_printf(level3, "Super Class : %d.\n", index);
buildNextShort(builder, index);
} else {
// No SuperClass Entry
debug_printf(level3, "Super Class : <NULL>.\n");
buildNextShort(builder, 0);
}
}
void encodeInterfaces(ClassFile *classFile, ClassBuilder *builder) {
unsigned length;
length = classFile->interfaces.size();
debug_printf(level1, "Interfaces Count : %d.\n", length);
buildNextShort(builder, length);
for(unsigned idx = 0; idx < length; idx++) {
ConstantInfo *info = (ConstantInfo *)classFile->interfaces[idx];
debug_printf(level2, "Interface %d : %d.\n", idx, info->index);
buildNextShort(builder, info->index);
}
}
int encodeClassData(ClassFile *classFile, ClassBuilder *builder) {
unsigned int length;
debug_printf(level0, "Magic : %#X.\n", classFile->magic);
debug_printf(level0, "Major Version : %d.\n", classFile->major_version);
debug_printf(level0, "Minor Version : %d.\n", classFile->minor_version);
buildNextInt(builder, classFile->magic);
buildNextShort(builder, classFile->major_version);
buildNextShort(builder, classFile->minor_version);
encodeConstantPool(classFile, builder);
debug_printf(level3, "Access Flags : %#X.\n", classFile->access_flags);
buildNextShort(builder, classFile->access_flags);
encodeThisClass(classFile, builder);
encodeSuperClass(classFile, builder);
encodeInterfaces(classFile, builder);
// Fields Table
length = classFile->fields.size();
debug_printf(level1, "Fields Count : %d.\n", length);
buildNextShort(builder, length);
for(unsigned idx = 0; idx < length; idx++) {
debug_printf(level2, "Field %d :\n", idx);
encodeField(classFile, builder, static_cast(MemberInfo *,
classFile->fields[idx]));
}
// Methods Table
length = classFile->methods.size();
debug_printf(level1, "Methods Count : %d.\n", length);
buildNextShort(builder, length);
for(unsigned idx = 0; idx < length; idx++) {
debug_printf(level2, "Method %d :\n", idx);
encodeMethod(classFile, builder, static_cast(MemberInfo *,
classFile->methods[idx]));
}
// Attributes Table
length = classFile->attributes.size();
debug_printf(level1, "Attributes Count : %d.\n", length);
buildNextShort(builder, length);
for(unsigned idx = 0; idx < length; idx++) {
debug_printf(level2, "Attribute %d :\n", idx);
encodeAttribute(classFile, builder, static_cast(AttributeInfo *,
classFile->attributes[idx]));
}
return 0;
}
int encodeClassFile(FILE *source, ClassFile *classFile) {
int result;
debug_printf(level0, "Creating Class builder.\n");
ClassBuilder *builder = createBuilder(source);
debug_printf(level0, "Encoding Class file :\n");
result = encodeClassData(classFile, builder);
debug_printf(level0, "Finished Class file.\n");
return result;
}
<commit_msg>Fixed a few more integer width issues.<commit_after>
# include "List.h"
# include "Debug.h"
# include "Zalloc.h"
# include "ClassFile.h"
# include "MemberInfo.h"
# include "ConstantInfo.h"
# include "AttributeInfo.h"
void encodeConstantPool(ClassFile *classFile, ClassBuilder *builder) {
size_t length;
length = classFile->constant_pool.size();
buildNextShort(builder, (uint16_t)length);
debug_printf(level1, "Constant Pool Count : %zu.\n", length);
for(unsigned idx = 1; idx < length; idx++) {
ConstantInfo *info;
debug_printf(level2, "Constant %d :\n", idx);
info = static_cast(ConstantInfo *, classFile->constant_pool[idx]);
encodeConstant(builder, info);
if(isLongConstant(info)) {
debug_printf(level2, "Long Constant; Skipping index.\n");
idx++;
}
}
}
void encodeThisClass(ClassFile *classFile, ClassBuilder *builder) {
if(classFile->this_class != NULL) {
uint16_t index = classFile->this_class->index;
debug_printf(level3, "This Class : %d.\n", index);
buildNextShort(builder, index);
} else {
// No ThisClass Entry
debug_printf(level3, "This Class : <NULL>.\n");
buildNextShort(builder, 0);
}
}
void encodeSuperClass(ClassFile *classFile, ClassBuilder *builder) {
if(classFile->super_class != NULL) {
uint16_t index = classFile->super_class->index;
debug_printf(level3, "Super Class : %d.\n", index);
buildNextShort(builder, index);
} else {
// No SuperClass Entry
debug_printf(level3, "Super Class : <NULL>.\n");
buildNextShort(builder, 0);
}
}
void encodeInterfaces(ClassFile *classFile, ClassBuilder *builder) {
size_t length;
length = classFile->interfaces.size();
debug_printf(level1, "Interfaces Count : %d.\n", length);
buildNextShort(builder, (uint16_t)length);
for(unsigned idx = 0; idx < length; idx++) {
ConstantInfo *info = (ConstantInfo *)classFile->interfaces[idx];
debug_printf(level2, "Interface %d : %d.\n", idx, info->index);
buildNextShort(builder, info->index);
}
}
int encodeClassData(ClassFile *classFile, ClassBuilder *builder) {
size_t length;
debug_printf(level0, "Magic : %#X.\n", classFile->magic);
debug_printf(level0, "Major Version : %d.\n", classFile->major_version);
debug_printf(level0, "Minor Version : %d.\n", classFile->minor_version);
buildNextInt(builder, classFile->magic);
buildNextShort(builder, classFile->major_version);
buildNextShort(builder, classFile->minor_version);
encodeConstantPool(classFile, builder);
debug_printf(level3, "Access Flags : %#X.\n", classFile->access_flags);
buildNextShort(builder, classFile->access_flags);
encodeThisClass(classFile, builder);
encodeSuperClass(classFile, builder);
encodeInterfaces(classFile, builder);
// Fields Table
length = classFile->fields.size();
debug_printf(level1, "Fields Count : %d.\n", length);
buildNextShort(builder, (uint16_t)length);
for(unsigned idx = 0; idx < length; idx++) {
debug_printf(level2, "Field %d :\n", idx);
encodeField(classFile, builder, static_cast(MemberInfo *,
classFile->fields[idx]));
}
// Methods Table
length = classFile->methods.size();
debug_printf(level1, "Methods Count : %d.\n", length);
buildNextShort(builder, (uint16_t)length);
for(unsigned idx = 0; idx < length; idx++) {
debug_printf(level2, "Method %d :\n", idx);
encodeMethod(classFile, builder, static_cast(MemberInfo *,
classFile->methods[idx]));
}
// Attributes Table
length = classFile->attributes.size();
debug_printf(level1, "Attributes Count : %d.\n", length);
buildNextShort(builder, (uint16_t)length);
for(unsigned idx = 0; idx < length; idx++) {
debug_printf(level2, "Attribute %d :\n", idx);
encodeAttribute(classFile, builder, static_cast(AttributeInfo *,
classFile->attributes[idx]));
}
return 0;
}
int encodeClassFile(FILE *source, ClassFile *classFile) {
int result;
debug_printf(level0, "Creating Class builder.\n");
ClassBuilder *builder = createBuilder(source);
debug_printf(level0, "Encoding Class file :\n");
result = encodeClassData(classFile, builder);
debug_printf(level0, "Finished Class file.\n");
return result;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#include <gtest/gtest.h>
#include <stub/return_handler.hpp>
TEST(return_handler, void)
{
// Just checking that it can be instantiated
stub::return_handler<void> r;
r();
}
TEST(return_handler, api)
{
// Return a single value multiple times
{
stub::return_handler<uint32_t> r;
r.set_return(5U);
EXPECT_EQ(r(), 5U);
EXPECT_EQ(r(), 5U);
EXPECT_EQ(r(), 5U);
}
// Use the return value of set_return
{
stub::return_handler<uint32_t> r;
r.set_return({5U, 3U});
EXPECT_EQ(r(), 5U);
EXPECT_EQ(r(), 3U);
EXPECT_EQ(r(), 5U);
EXPECT_EQ(r(), 3U);
EXPECT_EQ(r(), 5U);
}
// Try with no_repeat
{
stub::return_handler<uint32_t> r;
r.set_return(5U).no_repeat();
EXPECT_EQ(r(), 5U);
r.set_return({3U,4U}).no_repeat();
EXPECT_EQ(r(), 3U);
EXPECT_EQ(r(), 4U);
}
// Death tests
{
stub::return_handler<uint32_t> r;
r.set_return({3U,4U}).no_repeat();
EXPECT_EQ(r(), 3U);
EXPECT_EQ(r(), 4U);
// death
// EXPECT_EQ(r(), 4U);
}
}
<commit_msg>swap expected and actual<commit_after>// Copyright (c) 2014 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#include <gtest/gtest.h>
#include <stub/return_handler.hpp>
TEST(return_handler, void)
{
// Just checking that it can be instantiated
stub::return_handler<void> r;
r();
}
TEST(return_handler, api)
{
// Return a single value multiple times
{
stub::return_handler<uint32_t> r;
r.set_return(5U);
EXPECT_EQ(5U, r());
EXPECT_EQ(5U, r());
EXPECT_EQ(5U, r());
}
// Use the return value of set_return
{
stub::return_handler<uint32_t> r;
r.set_return({5U, 3U});
EXPECT_EQ(5U, r());
EXPECT_EQ(3U, r());
EXPECT_EQ(5U, r());
EXPECT_EQ(3U, r());
EXPECT_EQ(5U, r());
}
// Try with no_repeat
{
stub::return_handler<uint32_t> r;
r.set_return(5U).no_repeat();
EXPECT_EQ(5U, r());
r.set_return({3U,4U}).no_repeat();
EXPECT_EQ(3U, r());
EXPECT_EQ(4U, r());
}
// Death tests
{
stub::return_handler<uint32_t> r;
r.set_return({3U,4U}).no_repeat();
EXPECT_EQ(3U, r());
EXPECT_EQ(4U, r());
// death
// EXPECT_EQ(r(), 4U);
}
}
<|endoftext|> |
<commit_before>// bitmessage cracker, build with g++ or MSVS to a shared library, use included python code for usage under bitmessage
#ifdef _WIN32
#include "Winsock.h"
#include "Windows.h"
#define uint64_t unsigned __int64
#else
#include <arpa/inet.h>
#include <pthread.h>
#include <stdint.h>
#endif
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "openssl/sha.h"
#define HASH_SIZE 64
#define BUFLEN 16384
#if defined(__GNUC__)
#define EXPORT __attribute__ ((__visibility__("default")))
#elif defined(_WIN32)
#define EXPORT __declspec(dllexport)
#endif
#define ntohll(x) ( ( (uint64_t)(ntohl( (unsigned int)((x << 32) >> 32) )) << 32) | ntohl( ((unsigned int)(x >> 32)) ) )
unsigned long long max_val;
unsigned char *initialHash;
unsigned long long successval = 0;
unsigned int numthreads = 0;
#ifdef _WIN32
DWORD WINAPI threadfunc(LPVOID param) {
#else
void * threadfunc(void* param) {
#endif
unsigned int incamt = *((unsigned int*)param);
SHA512_CTX sha;
unsigned char buf[HASH_SIZE + sizeof(uint64_t)] = { 0 };
unsigned char output[HASH_SIZE] = { 0 };
memcpy(buf + sizeof(uint64_t), initialHash, HASH_SIZE);
unsigned long long tmpnonce = incamt;
unsigned long long * nonce = (unsigned long long *)buf;
unsigned long long * hash = (unsigned long long *)output;
while (successval == 0) {
tmpnonce += numthreads;
(*nonce) = ntohll(tmpnonce); /* increment nonce */
SHA512_Init(&sha);
SHA512_Update(&sha, buf, HASH_SIZE + sizeof(uint64_t));
SHA512_Final(output, &sha);
SHA512_Init(&sha);
SHA512_Update(&sha, output, HASH_SIZE);
SHA512_Final(output, &sha);
if (ntohll(*hash) < max_val) {
successval = tmpnonce;
}
}
return NULL;
}
void getnumthreads()
{
#ifdef _WIN32
DWORD_PTR dwProcessAffinity, dwSystemAffinity;
#elif __linux__
cpu_set_t dwProcessAffinity;
#else
int dwProcessAffinity = 0;
int32_t core_count = 0;
#endif
unsigned int len = sizeof(dwProcessAffinity);
if (numthreads > 0)
return;
#ifdef _WIN32
GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinity, &dwSystemAffinity);
#elif __linux__
sched_getaffinity(0, len, &dwProcessAffinity);
#else
if (sysctlbyname("hw.logicalcpu", &core_count, &len, 0, 0))
numthreads = core_count;
#endif
for (unsigned int i = 0; i < len * 8; i++)
#ifdef _WIN32
if (dwProcessAffinity & (1i64 << i)) {
#else
if (CPU_ISSET(i, &dwProcessAffinity)) {
#endif
numthreads++;
printf("Detected core on: %u\n", i);
}
printf("Number of threads: %i\n", (int)numthreads);
}
extern "C" EXPORT unsigned long long BitmessagePOW(unsigned char * starthash, unsigned long long target)
{
successval = 0;
max_val = target;
getnumthreads();
initialHash = (unsigned char *)starthash;
# ifdef _WIN32
HANDLE* threads = (HANDLE*)calloc(sizeof(HANDLE), numthreads);
# else
pthread_t* threads = (pthread_t*)calloc(sizeof(pthread_t), numthreads);
struct sched_param schparam;
# ifdef __linux__
schparam.sched_priority = 0;
# else
schparam.sched_priority = PTHREAD_MIN_PRIORITY;
# endif
# endif
unsigned int *threaddata = (unsigned int *)calloc(sizeof(unsigned int), numthreads);
for (unsigned int i = 0; i < numthreads; i++) {
threaddata[i] = i;
# ifdef _WIN32
threads[i] = CreateThread(NULL, 0, threadfunc, (LPVOID)&threaddata[i], 0, NULL);
SetThreadPriority(threads[i], THREAD_PRIORITY_IDLE);
# else
pthread_create(&threads[i], NULL, threadfunc, (void*)&threaddata[i]);
# ifdef __linux__
pthread_setschedparam(threads[i], SCHED_IDLE, &schparam);
# else
pthread_setschedparam(threads[i], SCHED_RR, &schparam)
# endif
# endif
}
# ifdef _WIN32
WaitForMultipleObjects(numthreads, threads, TRUE, INFINITE);
# else
for (unsigned int i = 0; i < numthreads; i++) {
pthread_join(threads[i], NULL);
}
# endif
free(threads);
free(threaddata);
return successval;
}
<commit_msg>Compile fixes<commit_after>// bitmessage cracker, build with g++ or MSVS to a shared library, use included python code for usage under bitmessage
#ifdef _WIN32
#include "Winsock.h"
#include "Windows.h"
#define uint64_t unsigned __int64
#else
#include <arpa/inet.h>
#include <pthread.h>
#include <stdint.h>
#endif
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef __APPLE__
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#include "openssl/sha.h"
#define HASH_SIZE 64
#define BUFLEN 16384
#if defined(__GNUC__)
#define EXPORT __attribute__ ((__visibility__("default")))
#elif defined(_WIN32)
#define EXPORT __declspec(dllexport)
#endif
#ifndef __APPLE__
#define ntohll(x) ( ( (uint64_t)(ntohl( (unsigned int)((x << 32) >> 32) )) << 32) | ntohl( ((unsigned int)(x >> 32)) ) )
#endif
unsigned long long max_val;
unsigned char *initialHash;
unsigned long long successval = 0;
unsigned int numthreads = 0;
#ifdef _WIN32
DWORD WINAPI threadfunc(LPVOID param) {
#else
void * threadfunc(void* param) {
#endif
unsigned int incamt = *((unsigned int*)param);
SHA512_CTX sha;
unsigned char buf[HASH_SIZE + sizeof(uint64_t)] = { 0 };
unsigned char output[HASH_SIZE] = { 0 };
memcpy(buf + sizeof(uint64_t), initialHash, HASH_SIZE);
unsigned long long tmpnonce = incamt;
unsigned long long * nonce = (unsigned long long *)buf;
unsigned long long * hash = (unsigned long long *)output;
while (successval == 0) {
tmpnonce += numthreads;
(*nonce) = ntohll(tmpnonce); /* increment nonce */
SHA512_Init(&sha);
SHA512_Update(&sha, buf, HASH_SIZE + sizeof(uint64_t));
SHA512_Final(output, &sha);
SHA512_Init(&sha);
SHA512_Update(&sha, output, HASH_SIZE);
SHA512_Final(output, &sha);
if (ntohll(*hash) < max_val) {
successval = tmpnonce;
}
}
return NULL;
}
void getnumthreads()
{
#ifdef _WIN32
DWORD_PTR dwProcessAffinity, dwSystemAffinity;
#elif __linux__
cpu_set_t dwProcessAffinity;
#else
int dwProcessAffinity = 0;
int32_t core_count = 0;
#endif
size_t len = sizeof(dwProcessAffinity);
if (numthreads > 0)
return;
#ifdef _WIN32
GetProcessAffinityMask(GetCurrentProcess(), &dwProcessAffinity, &dwSystemAffinity);
#elif __linux__
sched_getaffinity(0, len, &dwProcessAffinity);
#else
if (sysctlbyname("hw.logicalcpu", &core_count, &len, 0, 0) == 0)
numthreads = core_count;
#endif
for (unsigned int i = 0; i < len * 8; i++)
#if defined(_WIN32)
if (dwProcessAffinity & (1i64 << i)) {
#elif defined __linux__
if (CPU_ISSET(i, &dwProcessAffinity)) {
#else
if (dwProcessAffinity & (1 << i)) {
#endif
numthreads++;
printf("Detected core on: %u\n", i);
}
printf("Number of threads: %i\n", (int)numthreads);
}
extern "C" EXPORT unsigned long long BitmessagePOW(unsigned char * starthash, unsigned long long target)
{
successval = 0;
max_val = target;
getnumthreads();
initialHash = (unsigned char *)starthash;
# ifdef _WIN32
HANDLE* threads = (HANDLE*)calloc(sizeof(HANDLE), numthreads);
# else
pthread_t* threads = (pthread_t*)calloc(sizeof(pthread_t), numthreads);
struct sched_param schparam;
schparam.sched_priority = 0;
# endif
unsigned int *threaddata = (unsigned int *)calloc(sizeof(unsigned int), numthreads);
for (unsigned int i = 0; i < numthreads; i++) {
threaddata[i] = i;
# ifdef _WIN32
threads[i] = CreateThread(NULL, 0, threadfunc, (LPVOID)&threaddata[i], 0, NULL);
SetThreadPriority(threads[i], THREAD_PRIORITY_IDLE);
# else
pthread_create(&threads[i], NULL, threadfunc, (void*)&threaddata[i]);
# ifdef __linux__
pthread_setschedparam(threads[i], SCHED_IDLE, &schparam);
# else
pthread_setschedparam(threads[i], SCHED_RR, &schparam);
# endif
# endif
}
# ifdef _WIN32
WaitForMultipleObjects(numthreads, threads, TRUE, INFINITE);
# else
for (unsigned int i = 0; i < numthreads; i++) {
pthread_join(threads[i], NULL);
}
# endif
free(threads);
free(threaddata);
return successval;
}
<|endoftext|> |
<commit_before>/***************************************************************************
wpcontact.cpp - description
-------------------
begin : Fri Apr 12 2002
copyright : (C) 2002 by Gav Wood
email : gav@indigoarchive.net
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <kdebug.h>
#include <klocale.h>
#include <qfont.h>
// Local Includes
#include "wpcontact.h"
#include "wpprotocol.h"
#include "wpdebug.h"
// Kopete Includes
#include "kopetestdaction.h"
#include "kopetemessage.h"
#include "kopetemessagemanager.h"
// Qt Includes
#include <qdatetime.h>
#include <qregexp.h>
// KDE Includes
#include <kconfig.h>
WPContact::WPContact(const QString &userID, const QString &name, const QString &group, WPProtocol *protocol) : KopeteContact(protocol)
{
DEBUG(WPDMETHOD, "WPContact::WPContact(" << userID << ", " << name << ", " << group << ", <protocol>)");
setName(name.isNull() ? userID : name);
mProtocol = protocol;
mGroup = group;
mUserID = userID;
// connect(mProtocol, SIGNAL(contactUpdated(QString, QString, int, QString)), this, SLOT(slotUpdateContact(QString, QString, int, QString)));
// connect(mProtocol, SIGNAL(nukeContacts(bool)), this, SLOT(slotDeleteMySelf(bool)));
connect(&checkStatus, SIGNAL(timeout()), this, SLOT(slotCheckStatus()));
checkStatus.start(1000, false);
initActions();
slotUpdateContact(userID, STATUS_OFFLINE);
mMsgManagerKEW = 0;
mMsgManagerKCW = 0;
historyDialog = 0;
}
void WPContact::slotCheckStatus()
{
int oldStatus = mStatus;
mStatus = mProtocol->checkHost(mUserID) ? STATUS_ONLINE : STATUS_OFFLINE;
if(oldStatus != mStatus)
emit statusChanged();
}
KopeteMessageManager *WPContact::msgManagerKEW()
{
DEBUG(WPDMETHOD, "WPContact::msgManager()");
if(!mMsgManagerKEW)
{ KopeteContactList singleContact;
singleContact.append(this);
mMsgManagerKEW = kopeteapp->sessionFactory()->create(mProtocol->myself(), singleContact, mProtocol, "wp_logs/" + mUserID +".log", KopeteMessageManager::Email);
connect(mMsgManagerKEW, SIGNAL(messageSent(const KopeteMessage)), this, SLOT(slotSendMsgKEW(const KopeteMessage)));
}
return mMsgManagerKEW;
}
KopeteMessageManager *WPContact::msgManagerKCW()
{
DEBUG(WPDMETHOD, "WPContact::msgManager()");
if(!mMsgManagerKCW)
{ KopeteContactList singleContact;
singleContact.append(this);
mMsgManagerKCW = kopeteapp->sessionFactory()->create(mProtocol->myself(), singleContact, mProtocol, "wp_logs/" + mUserID +".log", KopeteMessageManager::ChatWindow);
connect(mMsgManagerKCW, SIGNAL(messageSent(const KopeteMessage)), this, SLOT(slotSendMsgKCW(const KopeteMessage)));
}
return mMsgManagerKCW;
}
void WPContact::initActions()
{
DEBUG(WPDMETHOD, "WPContact::initActions()");
actionChat = KopeteStdAction::sendMessage(this, SLOT(slotChatThisUser()), this, "actionChat");
actionMessage = new KAction(i18n("Send Email Message"), "mail_generic", 0, this, SLOT(slotEmailUser()), this, "actionMessage");
actionRemoveFromGroup = new KAction(i18n("Remove From Group"), "edittrash", 0, this, SLOT(slotRemoveFromGroup()), this, "actionRemove");
actionRemove = KopeteStdAction::deleteContact(this, SLOT(slotRemoveThisUser()), this, "actionDelete");
// actionContactMove = KopeteStdAction::moveContact(this, SLOT(slotMoveThisUser()), this, "actionMove");
actionHistory = KopeteStdAction::viewHistory(this, SLOT(slotViewHistory()), this, "actionHistory");
// actionRename = new KAction(i18n("Rename Contact"), "editrename", 0, this, SLOT(slotRenameContact()), this, "actionRename");
}
void WPContact::showContextMenu(QPoint position, QString group)
{
DEBUG(WPDMETHOD, "WPContact::showContextMenu(<position>, " << group << ")");
popup = new KPopupMenu(); // XXX: Needs deleting at some time?
popup->insertTitle(mUserID);
KGlobal::config()->setGroup("WinPopup");
if (KGlobal::config()->readBoolEntry("EmailDefault", false))
{
actionMessage->plug(popup);
actionChat->plug(popup);
}
else
{
actionChat->plug(popup);
actionMessage->plug(popup);
}
popup->insertSeparator();
actionHistory->plug(popup);
popup->insertSeparator();
// actionRename->plug(popup);
// actionContactMove->plug(popup);
actionRemoveFromGroup->plug(popup);
actionRemove->plug(popup);
popup->popup(position);//QCursor::pos());
}
void WPContact::slotUpdateContact(QString handle, int status)
{
DEBUG(WPDMETHOD, "WPContact::slotUpdateContact(" << handle << ", " << status << ")");
if(handle != userID())
return;
if(status != -1)
mStatus = status;
emit statusChanged();
}
void WPContact::slotRenameContact()
{
DEBUG(WPDMETHOD, "WPContact::slotRenameContact()");
/* kdDebug() << "WP contact: Renaming contact." << endl;
dlgRename = new dlgWPRename;
dlgRename->lblUserID->setText(userID());
dlgRename->leNickname->setText(name());
connect(dlgRename->btnRename, SIGNAL(clicked()), this,
SLOT(slotDoRenameContact()));
dlgRename->show();
*/
}
void WPContact::slotDoRenameContact()
{
DEBUG(WPDMETHOD, "WPContact::slotDoRenameContact()");
/* QString name = dlgRename->leNickname->text();
if (name == QString("")) { hasLocalName = false; name = mUserID; }
else { hasLocalName = true; }
setName(name);
delete dlgRename;
mProtocol->renameContact(userID(), hasLocalName ? name : QString(""), hasLocalGroup ? mGroup : QString(""));
*/
}
void WPContact::slotDeleteMySelf(bool)
{
DEBUG(WPDMETHOD, "WPContact::slotDeleteMyself()");
delete this;
}
WPContact::ContactStatus WPContact::status() const
{
DEBUG(WPDMETHOD, "WPContact::status()");
if(mStatus == STATUS_ONLINE)
return Online;
if(mStatus == STATUS_AWAY)
return Away;
return Offline;
}
QString WPContact::statusText() const
{
DEBUG(WPDMETHOD, "WPContact::statusText()");
if(mStatus == STATUS_ONLINE)
return "Online";
if(mStatus == STATUS_AWAY)
return "Away";
return "Offline";
}
QString WPContact::statusIcon() const
{
DEBUG(WPDMETHOD, "WPContact::statusIcon()");
if(mStatus == STATUS_ONLINE)
return "wp_available";
if(mStatus == STATUS_AWAY)
return "wp_away";
return "wp_offline";
}
void WPContact::slotRemoveThisUser()
{
DEBUG(WPDMETHOD, "WPContact::slotRemoveThisUser()");
// mProtocol->removeUser(mUserID);
// delete this; // use one-shot timer instead?
}
void WPContact::slotRemoveFromGroup()
{
DEBUG(WPDMETHOD, "WPContact::slotRemoveFromGroup()");
// mProtocol->moveUser(mUserID, mGroup = QString(""), name(), this);
}
void WPContact::slotMoveThisUser()
{
DEBUG(WPDMETHOD, "WPContact::slotMoveThisUser()");
/* if (!(mGroup = actionContactMove->currentText())) {
hasLocalGroup = false;
}
else {
hasLocalGroup = true;
}
mProtocol->moveUser(userID(), mGroup, name(), this);
*/
}
int WPContact::importance() const
{
DEBUG(WPDMETHOD, "WPContact::importance()");
if(mStatus == STATUS_ONLINE)
return 20;
if(mStatus == STATUS_AWAY)
return 15;
return 0;
}
void WPContact::slotChatThisUser()
{
DEBUG(WPDMETHOD, "WPContact::slotChatThisUser()");
msgManagerKCW()->readMessages();
}
void WPContact::slotEmailUser()
{
DEBUG(WPDMETHOD, "WPContact::slotChatThisUser()");
msgManagerKEW()->readMessages();
msgManagerKEW()->slotSendEnabled(true);
}
void WPContact::execute()
{
DEBUG(WPDMETHOD, "WPContact::execute()");
slotChatThisUser();
}
void WPContact::slotNewMessage(const QString &Body, const QDateTime &Arrival)
{
DEBUG(WPDMETHOD, "WPContact::slotNewMessage(" << Body << ", " << Arrival.toString() << ")");
KopeteContactList contactList;
contactList.append(mProtocol->myself());
QRegExp subj("^Subject: ([^\n]*)\n(.*)$");
if(subj.search(Body) == -1)
msgManagerKCW()->appendMessage(KopeteMessage(this, contactList, Body, KopeteMessage::Inbound));
else
{
msgManagerKEW()->appendMessage(KopeteMessage(this, contactList, subj.cap(2), subj.cap(1), KopeteMessage::Inbound));
msgManagerKEW()->slotSendEnabled(false);
}
}
void WPContact::slotViewHistory()
{
if(!historyDialog)
{
historyDialog = new KopeteHistoryDialog(QString("wp_logs/%1.log").arg(mUserID), name(), true, 50, 0, "WPHistoryDialog");
connect(historyDialog, SIGNAL(closing()), this, SLOT(slotCloseHistoryDialog()));
}
}
void WPContact::slotCloseHistoryDialog()
{
delete historyDialog;
historyDialog = 0;
}
void WPContact::slotSendMsgKEW(const KopeteMessage message)
{
DEBUG(WPDMETHOD, "WPContact::slotSendMsg(<message>)");
QString Message = message.body();
if(message.subject() != "")
Message = "Subject: " + message.subject() + "\n" + Message;
mProtocol->slotSendMessage(Message, dynamic_cast<WPContact *>(message.to().first())->userID());
msgManagerKEW()->appendMessage(message);
}
void WPContact::slotSendMsgKCW(const KopeteMessage message)
{
DEBUG(WPDMETHOD, "WPContact::slotSendMsg(<message>)");
mProtocol->slotSendMessage(message.body(), dynamic_cast<WPContact *>(message.to().first())->userID());
msgManagerKCW()->appendMessage(message);
}
#include "wpcontact.moc"
// vim: noet ts=4 sts=4 sw=4:
<commit_msg>Fixed wpcontact.cpp, so winpopup should now build.<commit_after>/***************************************************************************
wpcontact.cpp - description
-------------------
begin : Fri Apr 12 2002
copyright : (C) 2002 by Gav Wood
email : gav@indigoarchive.net
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <kdebug.h>
#include <klocale.h>
#include <qfont.h>
// Local Includes
#include "wpcontact.h"
#include "wpprotocol.h"
#include "wpdebug.h"
// Kopete Includes
#include "kopetestdaction.h"
#include "kopetemessage.h"
#include "kopetemessagemanager.h"
#include "kopetecontactlist.h"
// Qt Includes
#include <qdatetime.h>
#include <qregexp.h>
// KDE Includes
#include <kconfig.h>
WPContact::WPContact(const QString &userID, const QString &name, const QString &group, WPProtocol *protocol) : KopeteContact(protocol)
{
DEBUG(WPDMETHOD, "WPContact::WPContact(" << userID << ", " << name << ", " << group << ", <protocol>)");
setName(name.isNull() ? userID : name);
mProtocol = protocol;
mGroup = group;
mUserID = userID;
// connect(mProtocol, SIGNAL(contactUpdated(QString, QString, int, QString)), this, SLOT(slotUpdateContact(QString, QString, int, QString)));
// connect(mProtocol, SIGNAL(nukeContacts(bool)), this, SLOT(slotDeleteMySelf(bool)));
connect(&checkStatus, SIGNAL(timeout()), this, SLOT(slotCheckStatus()));
checkStatus.start(1000, false);
initActions();
slotUpdateContact(userID, STATUS_OFFLINE);
mMsgManagerKEW = 0;
mMsgManagerKCW = 0;
historyDialog = 0;
}
void WPContact::slotCheckStatus()
{
int oldStatus = mStatus;
mStatus = mProtocol->checkHost(mUserID) ? STATUS_ONLINE : STATUS_OFFLINE;
if(oldStatus != mStatus)
emit statusChanged();
}
KopeteMessageManager *WPContact::msgManagerKEW()
{
DEBUG(WPDMETHOD, "WPContact::msgManager()");
if(!mMsgManagerKEW)
{ QPtrList<KopeteContact> singleContact;
singleContact.append(this);
mMsgManagerKEW = kopeteapp->sessionFactory()->create(mProtocol->myself(), singleContact, mProtocol, "wp_logs/" + mUserID +".log", KopeteMessageManager::Email);
connect(mMsgManagerKEW, SIGNAL(messageSent(const KopeteMessage)), this, SLOT(slotSendMsgKEW(const KopeteMessage)));
}
return mMsgManagerKEW;
}
KopeteMessageManager *WPContact::msgManagerKCW()
{
DEBUG(WPDMETHOD, "WPContact::msgManager()");
if(!mMsgManagerKCW)
{ QPtrList<KopeteContact> singleContact;
singleContact.append(this);
mMsgManagerKCW = kopeteapp->sessionFactory()->create(mProtocol->myself(), singleContact, mProtocol, "wp_logs/" + mUserID +".log", KopeteMessageManager::ChatWindow);
connect(mMsgManagerKCW, SIGNAL(messageSent(const KopeteMessage)), this, SLOT(slotSendMsgKCW(const KopeteMessage)));
}
return mMsgManagerKCW;
}
void WPContact::initActions()
{
DEBUG(WPDMETHOD, "WPContact::initActions()");
actionChat = KopeteStdAction::sendMessage(this, SLOT(slotChatThisUser()), this, "actionChat");
actionMessage = new KAction(i18n("Send Email Message"), "mail_generic", 0, this, SLOT(slotEmailUser()), this, "actionMessage");
actionRemoveFromGroup = new KAction(i18n("Remove From Group"), "edittrash", 0, this, SLOT(slotRemoveFromGroup()), this, "actionRemove");
actionRemove = KopeteStdAction::deleteContact(this, SLOT(slotRemoveThisUser()), this, "actionDelete");
// actionContactMove = KopeteStdAction::moveContact(this, SLOT(slotMoveThisUser()), this, "actionMove");
actionHistory = KopeteStdAction::viewHistory(this, SLOT(slotViewHistory()), this, "actionHistory");
// actionRename = new KAction(i18n("Rename Contact"), "editrename", 0, this, SLOT(slotRenameContact()), this, "actionRename");
}
void WPContact::showContextMenu(QPoint position, QString group)
{
DEBUG(WPDMETHOD, "WPContact::showContextMenu(<position>, " << group << ")");
popup = new KPopupMenu(); // XXX: Needs deleting at some time?
popup->insertTitle(mUserID);
KGlobal::config()->setGroup("WinPopup");
if (KGlobal::config()->readBoolEntry("EmailDefault", false))
{
actionMessage->plug(popup);
actionChat->plug(popup);
}
else
{
actionChat->plug(popup);
actionMessage->plug(popup);
}
popup->insertSeparator();
actionHistory->plug(popup);
popup->insertSeparator();
// actionRename->plug(popup);
// actionContactMove->plug(popup);
actionRemoveFromGroup->plug(popup);
actionRemove->plug(popup);
popup->popup(position);//QCursor::pos());
}
void WPContact::slotUpdateContact(QString handle, int status)
{
DEBUG(WPDMETHOD, "WPContact::slotUpdateContact(" << handle << ", " << status << ")");
if(handle != userID())
return;
if(status != -1)
mStatus = status;
emit statusChanged();
}
void WPContact::slotRenameContact()
{
DEBUG(WPDMETHOD, "WPContact::slotRenameContact()");
/* kdDebug() << "WP contact: Renaming contact." << endl;
dlgRename = new dlgWPRename;
dlgRename->lblUserID->setText(userID());
dlgRename->leNickname->setText(name());
connect(dlgRename->btnRename, SIGNAL(clicked()), this,
SLOT(slotDoRenameContact()));
dlgRename->show();
*/
}
void WPContact::slotDoRenameContact()
{
DEBUG(WPDMETHOD, "WPContact::slotDoRenameContact()");
/* QString name = dlgRename->leNickname->text();
if (name == QString("")) { hasLocalName = false; name = mUserID; }
else { hasLocalName = true; }
setName(name);
delete dlgRename;
mProtocol->renameContact(userID(), hasLocalName ? name : QString(""), hasLocalGroup ? mGroup : QString(""));
*/
}
void WPContact::slotDeleteMySelf(bool)
{
DEBUG(WPDMETHOD, "WPContact::slotDeleteMyself()");
delete this;
}
WPContact::ContactStatus WPContact::status() const
{
DEBUG(WPDMETHOD, "WPContact::status()");
if(mStatus == STATUS_ONLINE)
return Online;
if(mStatus == STATUS_AWAY)
return Away;
return Offline;
}
QString WPContact::statusText() const
{
DEBUG(WPDMETHOD, "WPContact::statusText()");
if(mStatus == STATUS_ONLINE)
return "Online";
if(mStatus == STATUS_AWAY)
return "Away";
return "Offline";
}
QString WPContact::statusIcon() const
{
DEBUG(WPDMETHOD, "WPContact::statusIcon()");
if(mStatus == STATUS_ONLINE)
return "wp_available";
if(mStatus == STATUS_AWAY)
return "wp_away";
return "wp_offline";
}
void WPContact::slotRemoveThisUser()
{
DEBUG(WPDMETHOD, "WPContact::slotRemoveThisUser()");
// mProtocol->removeUser(mUserID);
// delete this; // use one-shot timer instead?
}
void WPContact::slotRemoveFromGroup()
{
DEBUG(WPDMETHOD, "WPContact::slotRemoveFromGroup()");
// mProtocol->moveUser(mUserID, mGroup = QString(""), name(), this);
}
void WPContact::slotMoveThisUser()
{
DEBUG(WPDMETHOD, "WPContact::slotMoveThisUser()");
/* if (!(mGroup = actionContactMove->currentText())) {
hasLocalGroup = false;
}
else {
hasLocalGroup = true;
}
mProtocol->moveUser(userID(), mGroup, name(), this);
*/
}
int WPContact::importance() const
{
DEBUG(WPDMETHOD, "WPContact::importance()");
if(mStatus == STATUS_ONLINE)
return 20;
if(mStatus == STATUS_AWAY)
return 15;
return 0;
}
void WPContact::slotChatThisUser()
{
DEBUG(WPDMETHOD, "WPContact::slotChatThisUser()");
msgManagerKCW()->readMessages();
}
void WPContact::slotEmailUser()
{
DEBUG(WPDMETHOD, "WPContact::slotChatThisUser()");
msgManagerKEW()->readMessages();
msgManagerKEW()->slotSendEnabled(true);
}
void WPContact::execute()
{
DEBUG(WPDMETHOD, "WPContact::execute()");
slotChatThisUser();
}
void WPContact::slotNewMessage(const QString &Body, const QDateTime &Arrival)
{
DEBUG(WPDMETHOD, "WPContact::slotNewMessage(" << Body << ", " << Arrival.toString() << ")");
QPtrList<KopeteContact> contactList;
contactList.append(mProtocol->myself());
QRegExp subj("^Subject: ([^\n]*)\n(.*)$");
if(subj.search(Body) == -1)
msgManagerKCW()->appendMessage(KopeteMessage(this, contactList, Body, KopeteMessage::Inbound));
else
{
msgManagerKEW()->appendMessage(KopeteMessage(this, contactList, subj.cap(2), subj.cap(1), KopeteMessage::Inbound));
msgManagerKEW()->slotSendEnabled(false);
}
}
void WPContact::slotViewHistory()
{
if(!historyDialog)
{
historyDialog = new KopeteHistoryDialog(QString("wp_logs/%1.log").arg(mUserID), name(), true, 50, 0, "WPHistoryDialog");
connect(historyDialog, SIGNAL(closing()), this, SLOT(slotCloseHistoryDialog()));
}
}
void WPContact::slotCloseHistoryDialog()
{
delete historyDialog;
historyDialog = 0;
}
void WPContact::slotSendMsgKEW(const KopeteMessage message)
{
DEBUG(WPDMETHOD, "WPContact::slotSendMsg(<message>)");
QString Message = message.body();
if(message.subject() != "")
Message = "Subject: " + message.subject() + "\n" + Message;
mProtocol->slotSendMessage(Message, dynamic_cast<WPContact *>(message.to().first())->userID());
msgManagerKEW()->appendMessage(message);
}
void WPContact::slotSendMsgKCW(const KopeteMessage message)
{
DEBUG(WPDMETHOD, "WPContact::slotSendMsg(<message>)");
mProtocol->slotSendMessage(message.body(), dynamic_cast<WPContact *>(message.to().first())->userID());
msgManagerKCW()->appendMessage(message);
}
#include "wpcontact.moc"
// vim: noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>de9cd911-313a-11e5-94af-3c15c2e10482<commit_msg>dea32951-313a-11e5-91b6-3c15c2e10482<commit_after>dea32951-313a-11e5-91b6-3c15c2e10482<|endoftext|> |
<commit_before>
/**
* @file CodeSmoother.hpp
* This class smoothes a given code observable using the corresponding phase observable.
*/
#ifndef CODE_SMOOTHER_GPSTK
#define CODE_SMOOTHER_GPSTK
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Dagoberto Salazar - gAGE. 2007
//
//============================================================================
#include "ComputeCombination.hpp"
namespace gpstk
{
/** @addtogroup DataStructures */
//@{
/** This class smoothes a given code observable using the corresponding phase observable.
* This class is meant to be used with the GNSS data structures objects
* found in "DataStructures" class.
*
* A typical way to use this class follows:
*
* @code
* RinexObsStream rin("ebre0300.02o");
*
* gnssRinex gRin;
* OneFreqCSDetector markCSC1; // We MUST mark cycle slips
* CodeSmoother smoothC1;
*
* while(rin >> gRin) {
* gRin >> markCSC1 >> smoothC1;
* }
* @endcode
*
* The "CodeSmoother" object will visit every satellite in the GNSS data
* structure that is "gRin" and will smooth the given code observation using
* the corresponding phase observation.
*
* By default, the algorithm will use C1 and L1 observables, and the CSL1 index
* will be consulted for cycle slip information. You can change these settings
* with the appropriate set methods.
*
* When used with the ">>" operator, this class returns the same incoming
* data structure with the code observation smoothed (unless the resultType
* field is changed). Be warned that if a given satellite does not have the
* observations required, it will be summarily deleted from the data
* structure.
*
* Another important parameter is the maxWindowSize field. By default, it is
* set to 100 samples (you may adjust that with the setMaxWindowSize() method).
*
* A window of 100 samples if typical and appropriate when working with data
* sampled at 1 Hz, because then the full window will last at most 100 seconds.
*
* However, if your samples are taken at 30 seconds, then a window of 50 minutes
* results and you will get badly distorted data because of ionosphere drift,
* among other effects.
*
* A good rule here is to make sure that the filter window lasts at most 5 minutes.
* Therefore, for a 30 s sampling data set you should set your smoother object like
* this:
*
* @code
* CodeSmoother smoothC1;
* smoothC1.setMaxWindowSize(8);
* @endcode
*
* Resulting in a 4 minutes filter window.
*
*/
class CodeSmoother
{
public:
/// Default constructor, setting default parameters and C1 and L1 as observables.
CodeSmoother() : codeType(TypeID::C1), phaseType(TypeID::L1), resultType(TypeID::C1), maxWindowSize(100), csFlag(TypeID::CSL1) { };
/** Common constructor
*
* @param codeT Type of code to be smoothed.
* @param mwSize Maximum size of filter window, in samples.
*/
CodeSmoother(const TypeID& codeT, const int& mwSize = 100) : codeType(codeT)
{
// Don't allow window sizes less than 1
if (mwSize > 1) maxWindowSize = mwSize; else maxWindowSize = 1;
switch ( codeT.type )
{
case TypeID::C1:
phaseType = TypeID::L1;
csFlag = TypeID::CSL1;
resultType = TypeID::C1;
break;
case TypeID::C2:
phaseType = TypeID::L2;
csFlag = TypeID::CSL2;
resultType = TypeID::C2;
break;
case TypeID::C5:
phaseType = TypeID::L5;
csFlag = TypeID::CSL5;
resultType = TypeID::C5;
break;
case TypeID::C6:
phaseType = TypeID::L6;
csFlag = TypeID::CSL6;
resultType = TypeID::C6;
break;
case TypeID::C7:
phaseType = TypeID::L7;
csFlag = TypeID::CSL7;
resultType = TypeID::C7;
break;
case TypeID::C8:
phaseType = TypeID::L8;
csFlag = TypeID::CSL8;
resultType = TypeID::C8;
break;
default:
phaseType = TypeID::L1;
csFlag = TypeID::CSL1;
resultType = TypeID::C1;
};
};
/** Returns a satTypeValueMap object, adding the new data generated when calling this object.
*
* @param gData Data object holding the data.
*/
virtual satTypeValueMap& Smooth(satTypeValueMap& gData)
{
double codeObs(0.0);
double phaseObs(0.0);
double flagObs(0.0);
SatIDSet satRejectedSet;
// Loop through all the satellites
satTypeValueMap::iterator it;
for (it = gData.begin(); it != gData.end(); ++it)
{
try
{
// Try to extract the values
codeObs = (*it).second(codeType);
phaseObs = (*it).second(phaseType);
flagObs = (*it).second(csFlag);
}
catch(...)
{
// If some value is missing, then schedule this satellite for removal
satRejectedSet.insert( (*it).first );
continue;
}
// If everything is OK, then process according if there is a cycle slip or not.
(*it).second[resultType] = getSmoothing((*it).first, codeObs, phaseObs, flagObs);
}
// Remove satellites with missing data
gData.removeSatID(satRejectedSet);
return gData;
};
/** Returns a gnnsSatTypeValue object, adding the new data generated when calling this object.
*
* @param gData Data object holding the data.
*/
virtual gnssSatTypeValue& Smooth(gnssSatTypeValue& gData)
{
(*this).Smooth(gData.body);
return gData;
};
/** Returns a gnnsRinex object, adding the new data generated when calling this object.
*
* @param gData Data object holding the data.
*/
virtual gnssRinex& Smooth(gnssRinex& gData)
{
(*this).Smooth(gData.body);
return gData;
};
/** Method to set the default code type to be used.
* @param codeT TypeID of code to be used
*/
virtual void setCodeType(const TypeID& codeT)
{
codeType = codeT;
};
/// Method to get the default code type being used.
virtual TypeID getCodeType() const
{
return codeType;
};
/** Method to set the default phase type to be used.
* @param phaseT TypeID of phase to be used
*/
virtual void setPhaseType(const TypeID& phaseT)
{
phaseType = phaseT;
};
/// Method to get the default phase type being used.
virtual TypeID getPhaseType() const
{
return phaseType;
};
/** Method to set the default cycle slip type to be used.
* @param csT Cycle slip type to be used
*/
virtual void setCSFlag(const TypeID& csT)
{
csFlag = csT;
};
/// Method to get the default cycle slip type being used.
virtual TypeID getCSFlag() const
{
return csFlag;
};
/** Method to set the default return type to be used.
* @param returnT TypeID to be returned
*/
virtual void setResultType(const TypeID& resultT)
{
resultType = resultT;
};
/// Method to get the default return type being used.
virtual TypeID getResultType() const
{
return resultType;
};
/** Method to set the maximum size of filter window, in samples.
* @param maxSize Maximum size of filter window, in samples.
*/
virtual void setMaxWindowSize(const int& maxSize)
{
// Don't allow window sizes less than 1
if (maxSize > 1) maxWindowSize = maxSize; else maxWindowSize = 1;
};
/// Method to get the maximum size of filter window, in samples.
virtual int getMaxWindowSize() const
{
return maxWindowSize;
};
/// Destructor
virtual ~CodeSmoother() {};
private:
/// Type of code observation to be used.
TypeID codeType;
/// Type of phase observation to be used.
TypeID phaseType;
/// Type assigned to the resulting smoothed code.
TypeID resultType;
/// Maximum size of filter window, in samples.
int maxWindowSize;
/// Cycle slip flag. It MUST be present. @sa OneFreqCSDetector.hpp class.
TypeID csFlag;
/// A structure used to store filter data for a SV.
struct filterData
{
// Default constructor initializing the data in the structure
filterData() : windowSize(1), previousCode(0.0), previousPhase(0.0) {};
int windowSize; ///< The filter window size.
double previousCode; ///< Accumulated mean bias (pseudorange - phase).
double previousPhase; ///< Accumulated mean bias sigma squared.
};
/// Map holding the information regarding every satellite
std::map<SatID, filterData> SmoothingData;
/// Compute the combination of observables.
virtual double getSmoothing(const SatID& sat, const double& code, const double& phase, const double& flag)
{
if ( flag!=0.0 ) // In case we have a cycle slip
{
// Prepare the structure for the next iteration
SmoothingData[sat].previousCode = code;
SmoothingData[sat].previousPhase = phase;
SmoothingData[sat].windowSize = 1;
return code; // We don't need any further processing
}
// In case we didn't have cycle slip
double smoothedCode(0.0);
// Increment size of window and check limit
++SmoothingData[sat].windowSize;
if (SmoothingData[sat].windowSize > maxWindowSize) SmoothingData[sat].windowSize = maxWindowSize;
// The formula used is the following:
//
// CSn = (1/n)*Cn + ((n-1)/n)*(CSn-1 + Ln - Ln-1)
//
// As window size "n" increases, the former formula gives more
// weight to the previous smoothed code CSn-1 plus the phase bias
// (Ln - Ln-1), and less weight to the current code observation Cn
smoothedCode = ( code + ((static_cast<double>(SmoothingData[sat].windowSize)) - 1.0) * (SmoothingData[sat].previousCode + (phase - SmoothingData[sat].previousPhase) ) ) / (static_cast<double>(SmoothingData[sat].windowSize));
// Store results for next iteration
SmoothingData[sat].previousCode = smoothedCode;
SmoothingData[sat].previousPhase = phase;
return smoothedCode;
};
}; // end class CodeSmoother
/// Input operator from gnssSatTypeValue to CodeSmoother.
inline gnssSatTypeValue& operator>>(gnssSatTypeValue& gData, CodeSmoother& codeS)
{
codeS.Smooth(gData);
return gData;
}
/// Input operator from gnssRinex to CodeSmoother.
inline gnssRinex& operator>>(gnssRinex& gData, CodeSmoother& codeS)
{
codeS.Smooth(gData);
return gData;
}
//@}
}
#endif
<commit_msg>Minor changes in documentation.<commit_after>
/**
* @file CodeSmoother.hpp
* This class smoothes a given code observable using the corresponding phase observable.
*/
#ifndef CODE_SMOOTHER_GPSTK
#define CODE_SMOOTHER_GPSTK
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Dagoberto Salazar - gAGE. 2007
//
//============================================================================
#include "ComputeCombination.hpp"
namespace gpstk
{
/** @addtogroup DataStructures */
//@{
/** This class smoothes a given code observable using the corresponding phase observable.
* This class is meant to be used with the GNSS data structures objects
* found in "DataStructures" class.
*
* A typical way to use this class follows:
*
* @code
* RinexObsStream rin("ebre0300.02o");
*
* gnssRinex gRin;
* OneFreqCSDetector markCSC1; // We MUST mark cycle slips
* CodeSmoother smoothC1;
*
* while(rin >> gRin) {
* gRin >> markCSC1 >> smoothC1;
* }
* @endcode
*
* The "CodeSmoother" object will visit every satellite in the GNSS data
* structure that is "gRin" and will smooth the given code observation using
* the corresponding phase observation.
*
* By default, the algorithm will use C1 and L1 observables, and the CSL1 index
* will be consulted for cycle slip information. You can change these settings
* with the appropriate set methods.
*
* When used with the ">>" operator, this class returns the same incoming
* data structure with the code observation smoothed (unless the resultType
* field is changed). Be warned that if a given satellite does not have the
* observations required, it will be summarily deleted from the data
* structure.
*
* Another important parameter is the maxWindowSize field. By default, it is
* set to 100 samples (you may adjust that with the setMaxWindowSize() method).
*
* A window of 100 samples is typical and appropriate when working with data
* sampled at 1 Hz, because then the full window will last at most 100 seconds.
*
* However, if for instance your samples are taken at 30 seconds (and you are
* working with C1/L1 or other ionosphere-affected observation pair), then a
* window of 50 minutes will be used and you will get badly distorted data
* because of ionosphere drift, among other effects.
*
* A good rule here is to make sure that the filter window lasts at most 5 minutes.
* Therefore, for a 30 s sampling data set you should set your smoother object like
* this:
*
* @code
* CodeSmoother smoothC1;
* smoothC1.setMaxWindowSize(8);
* @endcode
*
* Resulting in a 4 minutes filter window.
*
*/
class CodeSmoother
{
public:
/// Default constructor, setting default parameters and C1 and L1 as observables.
CodeSmoother() : codeType(TypeID::C1), phaseType(TypeID::L1), resultType(TypeID::C1), maxWindowSize(100), csFlag(TypeID::CSL1) { };
/** Common constructor
*
* @param codeT Type of code to be smoothed.
* @param mwSize Maximum size of filter window, in samples.
*/
CodeSmoother(const TypeID& codeT, const int& mwSize = 100) : codeType(codeT)
{
// Don't allow window sizes less than 1
if (mwSize > 1) maxWindowSize = mwSize; else maxWindowSize = 1;
switch ( codeT.type )
{
case TypeID::C1:
phaseType = TypeID::L1;
csFlag = TypeID::CSL1;
resultType = TypeID::C1;
break;
case TypeID::C2:
phaseType = TypeID::L2;
csFlag = TypeID::CSL2;
resultType = TypeID::C2;
break;
case TypeID::C5:
phaseType = TypeID::L5;
csFlag = TypeID::CSL5;
resultType = TypeID::C5;
break;
case TypeID::C6:
phaseType = TypeID::L6;
csFlag = TypeID::CSL6;
resultType = TypeID::C6;
break;
case TypeID::C7:
phaseType = TypeID::L7;
csFlag = TypeID::CSL7;
resultType = TypeID::C7;
break;
case TypeID::C8:
phaseType = TypeID::L8;
csFlag = TypeID::CSL8;
resultType = TypeID::C8;
break;
default:
phaseType = TypeID::L1;
csFlag = TypeID::CSL1;
resultType = TypeID::C1;
};
};
/** Returns a satTypeValueMap object, adding the new data generated when calling this object.
*
* @param gData Data object holding the data.
*/
virtual satTypeValueMap& Smooth(satTypeValueMap& gData)
{
double codeObs(0.0);
double phaseObs(0.0);
double flagObs(0.0);
SatIDSet satRejectedSet;
// Loop through all the satellites
satTypeValueMap::iterator it;
for (it = gData.begin(); it != gData.end(); ++it)
{
try
{
// Try to extract the values
codeObs = (*it).second(codeType);
phaseObs = (*it).second(phaseType);
flagObs = (*it).second(csFlag);
}
catch(...)
{
// If some value is missing, then schedule this satellite for removal
satRejectedSet.insert( (*it).first );
continue;
}
// If everything is OK, then process according if there is a cycle slip or not.
(*it).second[resultType] = getSmoothing((*it).first, codeObs, phaseObs, flagObs);
}
// Remove satellites with missing data
gData.removeSatID(satRejectedSet);
return gData;
};
/** Returns a gnnsSatTypeValue object, adding the new data generated when calling this object.
*
* @param gData Data object holding the data.
*/
virtual gnssSatTypeValue& Smooth(gnssSatTypeValue& gData)
{
(*this).Smooth(gData.body);
return gData;
};
/** Returns a gnnsRinex object, adding the new data generated when calling this object.
*
* @param gData Data object holding the data.
*/
virtual gnssRinex& Smooth(gnssRinex& gData)
{
(*this).Smooth(gData.body);
return gData;
};
/** Method to set the default code type to be used.
* @param codeT TypeID of code to be used
*/
virtual void setCodeType(const TypeID& codeT)
{
codeType = codeT;
};
/// Method to get the default code type being used.
virtual TypeID getCodeType() const
{
return codeType;
};
/** Method to set the default phase type to be used.
* @param phaseT TypeID of phase to be used
*/
virtual void setPhaseType(const TypeID& phaseT)
{
phaseType = phaseT;
};
/// Method to get the default phase type being used.
virtual TypeID getPhaseType() const
{
return phaseType;
};
/** Method to set the default cycle slip type to be used.
* @param csT Cycle slip type to be used
*/
virtual void setCSFlag(const TypeID& csT)
{
csFlag = csT;
};
/// Method to get the default cycle slip type being used.
virtual TypeID getCSFlag() const
{
return csFlag;
};
/** Method to set the default return type to be used.
* @param returnT TypeID to be returned
*/
virtual void setResultType(const TypeID& resultT)
{
resultType = resultT;
};
/// Method to get the default return type being used.
virtual TypeID getResultType() const
{
return resultType;
};
/** Method to set the maximum size of filter window, in samples.
* @param maxSize Maximum size of filter window, in samples.
*/
virtual void setMaxWindowSize(const int& maxSize)
{
// Don't allow window sizes less than 1
if (maxSize > 1) maxWindowSize = maxSize; else maxWindowSize = 1;
};
/// Method to get the maximum size of filter window, in samples.
virtual int getMaxWindowSize() const
{
return maxWindowSize;
};
/// Destructor
virtual ~CodeSmoother() {};
private:
/// Type of code observation to be used.
TypeID codeType;
/// Type of phase observation to be used.
TypeID phaseType;
/// Type assigned to the resulting smoothed code.
TypeID resultType;
/// Maximum size of filter window, in samples.
int maxWindowSize;
/// Cycle slip flag. It MUST be present. @sa OneFreqCSDetector.hpp class.
TypeID csFlag;
/// A structure used to store filter data for a SV.
struct filterData
{
// Default constructor initializing the data in the structure
filterData() : windowSize(1), previousCode(0.0), previousPhase(0.0) {};
int windowSize; ///< The filter window size.
double previousCode; ///< Accumulated mean bias (pseudorange - phase).
double previousPhase; ///< Accumulated mean bias sigma squared.
};
/// Map holding the information regarding every satellite
std::map<SatID, filterData> SmoothingData;
/// Compute the combination of observables.
virtual double getSmoothing(const SatID& sat, const double& code, const double& phase, const double& flag)
{
if ( flag!=0.0 ) // In case we have a cycle slip
{
// Prepare the structure for the next iteration
SmoothingData[sat].previousCode = code;
SmoothingData[sat].previousPhase = phase;
SmoothingData[sat].windowSize = 1;
return code; // We don't need any further processing
}
// In case we didn't have cycle slip
double smoothedCode(0.0);
// Increment size of window and check limit
++SmoothingData[sat].windowSize;
if (SmoothingData[sat].windowSize > maxWindowSize) SmoothingData[sat].windowSize = maxWindowSize;
// The formula used is the following:
//
// CSn = (1/n)*Cn + ((n-1)/n)*(CSn-1 + Ln - Ln-1)
//
// As window size "n" increases, the former formula gives more
// weight to the previous smoothed code CSn-1 plus the phase bias
// (Ln - Ln-1), and less weight to the current code observation Cn
smoothedCode = ( code + ((static_cast<double>(SmoothingData[sat].windowSize)) - 1.0) * (SmoothingData[sat].previousCode + (phase - SmoothingData[sat].previousPhase) ) ) / (static_cast<double>(SmoothingData[sat].windowSize));
// Store results for next iteration
SmoothingData[sat].previousCode = smoothedCode;
SmoothingData[sat].previousPhase = phase;
return smoothedCode;
};
}; // end class CodeSmoother
/// Input operator from gnssSatTypeValue to CodeSmoother.
inline gnssSatTypeValue& operator>>(gnssSatTypeValue& gData, CodeSmoother& codeS)
{
codeS.Smooth(gData);
return gData;
}
/// Input operator from gnssRinex to CodeSmoother.
inline gnssRinex& operator>>(gnssRinex& gData, CodeSmoother& codeS)
{
codeS.Smooth(gData);
return gData;
}
//@}
}
#endif
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2016 Stefan Tröger <stefantroeger@gmx.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
//#include "ViewProviderGroupExtensionPy.h"
#include "ViewProviderGroupExtension.h"
#include "Command.h"
#include "Application.h"
#include "Document.h"
#include <Base/Tools.h>
#include <App/Document.h>
#include <App/DocumentObject.h>
#include <App/GroupExtension.h>
#include <App/Expression.h>
#include <Base/Console.h>
#include <QMessageBox>
using namespace Gui;
EXTENSION_PROPERTY_SOURCE(Gui::ViewProviderGroupExtension, Gui::ViewProviderExtension)
ViewProviderGroupExtension::ViewProviderGroupExtension() : visible(false), guard(false)
{
initExtensionType(ViewProviderGroupExtension::getExtensionClassTypeId());
}
ViewProviderGroupExtension::~ViewProviderGroupExtension()
{
}
bool ViewProviderGroupExtension::extensionCanDragObjects() const {
return true;
}
bool ViewProviderGroupExtension::extensionCanDragObject(App::DocumentObject*) const {
//we can drag anything out
return true;
}
void ViewProviderGroupExtension::extensionDragObject(App::DocumentObject* obj) {
Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument(\"%s\").getObject(\"%s\").removeObject("
"App.getDocument(\"%s\").getObject(\"%s\"))",
getExtendedViewProvider()->getObject()->getDocument()->getName(), getExtendedViewProvider()->getObject()->getNameInDocument(),
obj->getDocument()->getName(), obj->getNameInDocument() );
}
bool ViewProviderGroupExtension::extensionCanDropObjects() const {
return true;
}
bool ViewProviderGroupExtension::extensionCanDropObject(App::DocumentObject* obj) const {
#ifdef FC_DEBUG
Base::Console().Log("Check ViewProviderGroupExtension");
#endif
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
//we cannot drop thing of this group into it again
if (group->hasObject(obj))
return false;
if (group->allowObject(obj))
return true;
return false;
}
void ViewProviderGroupExtension::extensionDropObject(App::DocumentObject* obj) {
App::DocumentObject* grp = static_cast<App::DocumentObject*>(getExtendedViewProvider()->getObject());
App::Document* doc = grp->getDocument();
// build Python command for execution
QString cmd;
cmd = QString::fromLatin1("App.getDocument(\"%1\").getObject(\"%2\").addObject("
"App.getDocument(\"%1\").getObject(\"%3\"))")
.arg(QString::fromLatin1(doc->getName()))
.arg(QString::fromLatin1(grp->getNameInDocument()))
.arg(QString::fromLatin1(obj->getNameInDocument()));
Gui::Command::doCommand(Gui::Command::App, cmd.toUtf8());
}
std::vector< App::DocumentObject* > ViewProviderGroupExtension::extensionClaimChildren(void) const {
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
return std::vector<App::DocumentObject*>(group->Group.getValues());
}
void ViewProviderGroupExtension::extensionShow(void) {
// avoid possible infinite recursion
if (guard)
return;
Base::StateLocker lock(guard);
// when reading the Visibility property from file then do not hide the
// objects of this group because they have stored their visibility status, too
if (!getExtendedViewProvider()->isRestoring() && !this->visible) {
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
const std::vector<App::DocumentObject*> & links = group->Group.getValues();
Gui::Document* doc = Application::Instance->getDocument(group->getExtendedObject()->getDocument());
for (std::vector<App::DocumentObject*>::const_iterator it = links.begin(); it != links.end(); ++it) {
ViewProvider* view = doc->getViewProvider(*it);
if (view)
view->show();
}
}
ViewProviderExtension::extensionShow();
this->visible = true;
}
void ViewProviderGroupExtension::extensionHide(void) {
// avoid possible infinite recursion
if (guard)
return;
Base::StateLocker lock(guard);
// when reading the Visibility property from file then do not hide the
// objects of this group because they have stored their visibility status, too
if (!getExtendedViewProvider()->isRestoring() && this->visible) {
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
const std::vector<App::DocumentObject*> & links = group->Group.getValues();
Gui::Document* doc = Application::Instance->getDocument(getExtendedViewProvider()->getObject()->getDocument());
// doc pointer can be null in case the document is about to be destroyed
// See https://forum.freecadweb.org/viewtopic.php?f=22&t=26797&p=218804#p218521
if (doc) {
for (std::vector<App::DocumentObject*>::const_iterator it = links.begin(); it != links.end(); ++it) {
ViewProvider* view = doc->getViewProvider(*it);
if (view)
view->hide();
}
}
}
ViewProviderExtension::extensionHide();
this->visible = false;
}
bool ViewProviderGroupExtension::extensionOnDelete(const std::vector< std::string >& ) {
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
// If the group is nonempty ask the user if he wants to delete its content
if ( group->Group.getSize () ) {
QMessageBox::StandardButton choice =
QMessageBox::question ( 0, QObject::tr ( "Delete group content?" ),
QObject::tr ( "The %1 is not empty, delete its content as well?")
.arg ( QString::fromUtf8 ( getExtendedViewProvider()->getObject()->Label.getValue () ) ),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes );
if ( choice == QMessageBox::Yes ) {
Gui::Command::doCommand(Gui::Command::Doc,
"App.getDocument(\"%s\").getObject(\"%s\").removeObjectsFromDocument()"
,getExtendedViewProvider()->getObject()->getDocument()->getName(), getExtendedViewProvider()->getObject()->getNameInDocument());
}
}
return true;
}
namespace Gui {
EXTENSION_PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderGroupExtensionPython, Gui::ViewProviderGroupExtension)
// explicit template instantiation
template class GuiExport ViewProviderExtensionPythonT<ViewProviderGroupExtension>;
}
<commit_msg>set parent widget to message box when asking user to delete content of a group<commit_after>/***************************************************************************
* Copyright (c) 2016 Stefan Tröger <stefantroeger@gmx.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
//#include "ViewProviderGroupExtensionPy.h"
#include "ViewProviderGroupExtension.h"
#include "Command.h"
#include "Application.h"
#include "Document.h"
#include "MainWindow.h"
#include <Base/Tools.h>
#include <App/Document.h>
#include <App/DocumentObject.h>
#include <App/GroupExtension.h>
#include <App/Expression.h>
#include <Base/Console.h>
#include <QMessageBox>
using namespace Gui;
EXTENSION_PROPERTY_SOURCE(Gui::ViewProviderGroupExtension, Gui::ViewProviderExtension)
ViewProviderGroupExtension::ViewProviderGroupExtension() : visible(false), guard(false)
{
initExtensionType(ViewProviderGroupExtension::getExtensionClassTypeId());
}
ViewProviderGroupExtension::~ViewProviderGroupExtension()
{
}
bool ViewProviderGroupExtension::extensionCanDragObjects() const {
return true;
}
bool ViewProviderGroupExtension::extensionCanDragObject(App::DocumentObject*) const {
//we can drag anything out
return true;
}
void ViewProviderGroupExtension::extensionDragObject(App::DocumentObject* obj) {
Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument(\"%s\").getObject(\"%s\").removeObject("
"App.getDocument(\"%s\").getObject(\"%s\"))",
getExtendedViewProvider()->getObject()->getDocument()->getName(), getExtendedViewProvider()->getObject()->getNameInDocument(),
obj->getDocument()->getName(), obj->getNameInDocument() );
}
bool ViewProviderGroupExtension::extensionCanDropObjects() const {
return true;
}
bool ViewProviderGroupExtension::extensionCanDropObject(App::DocumentObject* obj) const {
#ifdef FC_DEBUG
Base::Console().Log("Check ViewProviderGroupExtension");
#endif
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
//we cannot drop thing of this group into it again
if (group->hasObject(obj))
return false;
if (group->allowObject(obj))
return true;
return false;
}
void ViewProviderGroupExtension::extensionDropObject(App::DocumentObject* obj) {
App::DocumentObject* grp = static_cast<App::DocumentObject*>(getExtendedViewProvider()->getObject());
App::Document* doc = grp->getDocument();
// build Python command for execution
QString cmd;
cmd = QString::fromLatin1("App.getDocument(\"%1\").getObject(\"%2\").addObject("
"App.getDocument(\"%1\").getObject(\"%3\"))")
.arg(QString::fromLatin1(doc->getName()))
.arg(QString::fromLatin1(grp->getNameInDocument()))
.arg(QString::fromLatin1(obj->getNameInDocument()));
Gui::Command::doCommand(Gui::Command::App, cmd.toUtf8());
}
std::vector< App::DocumentObject* > ViewProviderGroupExtension::extensionClaimChildren(void) const {
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
return std::vector<App::DocumentObject*>(group->Group.getValues());
}
void ViewProviderGroupExtension::extensionShow(void) {
// avoid possible infinite recursion
if (guard)
return;
Base::StateLocker lock(guard);
// when reading the Visibility property from file then do not hide the
// objects of this group because they have stored their visibility status, too
if (!getExtendedViewProvider()->isRestoring() && !this->visible) {
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
const std::vector<App::DocumentObject*> & links = group->Group.getValues();
Gui::Document* doc = Application::Instance->getDocument(group->getExtendedObject()->getDocument());
for (std::vector<App::DocumentObject*>::const_iterator it = links.begin(); it != links.end(); ++it) {
ViewProvider* view = doc->getViewProvider(*it);
if (view)
view->show();
}
}
ViewProviderExtension::extensionShow();
this->visible = true;
}
void ViewProviderGroupExtension::extensionHide(void) {
// avoid possible infinite recursion
if (guard)
return;
Base::StateLocker lock(guard);
// when reading the Visibility property from file then do not hide the
// objects of this group because they have stored their visibility status, too
if (!getExtendedViewProvider()->isRestoring() && this->visible) {
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
const std::vector<App::DocumentObject*> & links = group->Group.getValues();
Gui::Document* doc = Application::Instance->getDocument(getExtendedViewProvider()->getObject()->getDocument());
// doc pointer can be null in case the document is about to be destroyed
// See https://forum.freecadweb.org/viewtopic.php?f=22&t=26797&p=218804#p218521
if (doc) {
for (std::vector<App::DocumentObject*>::const_iterator it = links.begin(); it != links.end(); ++it) {
ViewProvider* view = doc->getViewProvider(*it);
if (view)
view->hide();
}
}
}
ViewProviderExtension::extensionHide();
this->visible = false;
}
bool ViewProviderGroupExtension::extensionOnDelete(const std::vector< std::string >& ) {
auto* group = getExtendedViewProvider()->getObject()->getExtensionByType<App::GroupExtension>();
// If the group is nonempty ask the user if he wants to delete its content
if (group->Group.getSize() > 0) {
QMessageBox::StandardButton choice =
QMessageBox::question(getMainWindow(), QObject::tr ( "Delete group content?" ),
QObject::tr ( "The %1 is not empty, delete its content as well?")
.arg ( QString::fromUtf8 ( getExtendedViewProvider()->getObject()->Label.getValue () ) ),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes );
if (choice == QMessageBox::Yes) {
Gui::Command::doCommand(Gui::Command::Doc,
"App.getDocument(\"%s\").getObject(\"%s\").removeObjectsFromDocument()"
, getExtendedViewProvider()->getObject()->getDocument()->getName()
, getExtendedViewProvider()->getObject()->getNameInDocument());
}
}
return true;
}
namespace Gui {
EXTENSION_PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderGroupExtensionPython, Gui::ViewProviderGroupExtension)
// explicit template instantiation
template class GuiExport ViewProviderExtensionPythonT<ViewProviderGroupExtension>;
}
<|endoftext|> |
<commit_before>c2489545-4b02-11e5-b2dc-28cfe9171a43<commit_msg>No longer crashes if X<commit_after>c2556a11-4b02-11e5-bd11-28cfe9171a43<|endoftext|> |
<commit_before>// Copyright (C) 2012 Georgia Institute of Technology
//
// 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.
// ---
// Author: Hrishikesh Amur
#include <assert.h>
#include <stdio.h>
#define __STDC_LIMIT_MACROS /* for UINT32_MAX etc. */
#include <stdint.h>
#include <stdlib.h>
#include <deque>
#include "Buffer.h"
#include "CompressTree.h"
#include "Slaves.h"
namespace cbt {
uint32_t BUFFER_SIZE;
uint32_t MAX_ELS_PER_BUFFER;
uint32_t EMPTY_THRESHOLD;
CompressTree::CompressTree(uint32_t a, uint32_t b, uint32_t nodesInMemory,
uint32_t buffer_size, uint32_t pao_size,
const Operations* const ops) :
a_(a),
b_(b),
nodeCtr(1),
ops(ops),
alg_(SNAPPY),
allFlush_(true),
empty_(true),
lastLeafRead_(0),
lastOffset_(0),
lastElement_(0),
threadsStarted_(false) {
BUFFER_SIZE = buffer_size;
MAX_ELS_PER_BUFFER = BUFFER_SIZE / pao_size;
EMPTY_THRESHOLD = MAX_ELS_PER_BUFFER >> 1;
pthread_cond_init(&emptyRootAvailable_, NULL);
pthread_mutex_init(&emptyRootNodesMutex_, NULL);
#ifdef ENABLE_COUNTERS
monitor_ = NULL;
#endif
}
CompressTree::~CompressTree() {
pthread_cond_destroy(&emptyRootAvailable_);
pthread_mutex_destroy(&emptyRootNodesMutex_);
pthread_barrier_destroy(&threadsBarrier_);
}
bool CompressTree::bulk_insert(PartialAgg** paos, uint64_t num) {
bool ret = true;
// copy buf into root node buffer
// root node buffer always decompressed
if (num > 0)
allFlush_ = empty_ = false;
if (!threadsStarted_) {
startThreads();
}
for (uint64_t i = 0; i < num; ++i) {
PartialAgg* agg = paos[i];
if (inputNode_->isFull()) {
// add inputNode_ to be sorted
inputNode_->schedule(SORT);
// get an empty root. This function can block until there are
// empty roots available
inputNode_ = getEmptyRootNode();
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Now inputting into node %d\n",
inputNode_->id());
#endif // CT_NODE_DEBUG
}
ret &= inputNode_->insert(agg);
}
return ret;
}
bool CompressTree::insert(PartialAgg* agg) {
bool ret = bulk_insert(&agg, 1);
return ret;
}
bool CompressTree::bulk_read(PartialAgg** pao_list, uint64_t& num_read,
uint64_t max) {
uint64_t hash;
void* ptrToHash = reinterpret_cast<void*>(&hash);
num_read = 0;
while (num_read < max) {
if (!(nextValue(ptrToHash, pao_list[num_read])))
return false;
num_read++;
}
return true;
}
bool CompressTree::nextValue(void*& hash, PartialAgg*& agg) {
if (empty_)
return false;
if (!allFlush_) {
flushBuffers();
lastLeafRead_ = 0;
lastOffset_ = 0;
lastElement_ = 0;
allFlush_ = true;
// page in and decompress first leaf
Node* curLeaf = allLeaves_[0];
assert(curLeaf->buffer_.lists_.size() == 1);
while (curLeaf->buffer_.numElements() == 0)
curLeaf = allLeaves_[++lastLeafRead_];
curLeaf->schedule(DECOMPRESS_ONLY);
curLeaf->wait(DECOMPRESS_ONLY);
}
Node* curLeaf = allLeaves_[lastLeafRead_];
Buffer::List* l = curLeaf->buffer_.lists_[0];
hash = reinterpret_cast<void*>(&l->hashes_[lastElement_]);
ops->createPAO(NULL, &agg);
// if (lastLeafRead_ == 0)
// fprintf(stderr, "%ld\n", lastOffset_);
if (!(ops->deserialize(agg, l->data_ + lastOffset_,
l->sizes_[lastElement_]))) {
fprintf(stderr, "Can't deserialize at %u, index: %u\n", lastOffset_,
lastElement_);
assert(false);
}
lastOffset_ += l->sizes_[lastElement_];
lastElement_++;
if (lastElement_ >= curLeaf->buffer_.numElements()) {
curLeaf->schedule(COMPRESS);
if (++lastLeafRead_ == allLeaves_.size()) {
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Emptying tree!\n");
#endif
// Again wait for all to end
int all_done;
do {
usleep(100);
sem_getvalue(&sleepSemaphore_, &all_done);
} while (all_done);
emptyTree();
stopThreads();
return false;
}
Node *n = allLeaves_[lastLeafRead_];
while (curLeaf->buffer_.numElements() == 0)
curLeaf = allLeaves_[++lastLeafRead_];
n->schedule(DECOMPRESS_ONLY);
n->wait(DECOMPRESS_ONLY);
lastOffset_ = 0;
lastElement_ = 0;
}
return true;
}
void CompressTree::clear() {
emptyTree();
stopThreads();
}
void CompressTree::emptyTree() {
std::deque<Node*> delList1;
std::deque<Node*> delList2;
delList1.push_back(rootNode_);
while (!delList1.empty()) {
Node* n = delList1.front();
delList1.pop_front();
for (uint32_t i = 0; i < n->children_.size(); ++i) {
delList1.push_back(n->children_[i]);
}
delList2.push_back(n);
}
while (!delList2.empty()) {
Node* n = delList2.front();
delList2.pop_front();
delete n;
}
allLeaves_.clear();
leavesToBeEmptied_.clear();
allFlush_ = empty_ = true;
lastLeafRead_ = 0;
lastOffset_ = 0;
lastElement_ = 0;
nodeCtr = 0;
}
bool CompressTree::flushBuffers() {
Node* curNode;
std::deque<Node*> visitQueue;
fprintf(stderr, "Starting to flush\n");
emptyType_ = ALWAYS;
inputNode_->schedule(SORT);
int all_done;
do {
usleep(100);
sem_getvalue(&sleepSemaphore_, &all_done);
} while (all_done);
// add all leaves;
visitQueue.push_back(rootNode_);
while (!visitQueue.empty()) {
curNode = visitQueue.front();
visitQueue.pop_front();
if (curNode->isLeaf()) {
allLeaves_.push_back(curNode);
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Pushing node %d to all-leaves\t",
curNode->id_);
fprintf(stderr, "Now has: ");
for (uint32_t i = 0; i < allLeaves_.size(); ++i) {
fprintf(stderr, "%d ", allLeaves_[i]->id_);
}
fprintf(stderr, "\n");
#endif
continue;
}
for (uint32_t i = 0; i < curNode->children_.size(); ++i) {
visitQueue.push_back(curNode->children_[i]);
}
}
fprintf(stderr, "Tree has %ld leaves\n", allLeaves_.size());
uint32_t depth = 1;
curNode = rootNode_;
while (curNode->children_.size() > 0) {
depth++;
curNode = curNode->children_[0];
}
fprintf(stderr, "Tree has depth: %d\n", depth);
uint64_t numit = 0;
for (uint64_t i = 0; i < allLeaves_.size(); ++i)
numit += allLeaves_[i]->buffer_.numElements();
fprintf(stderr, "Tree has %ld elements\n", numit);
return true;
}
bool CompressTree::addLeafToEmpty(Node* node) {
leavesToBeEmptied_.push_back(node);
return true;
}
/* A full leaf is handled by splitting the leaf into two leaves.*/
void CompressTree::handleFullLeaves() {
while (!leavesToBeEmptied_.empty()) {
Node* node = leavesToBeEmptied_.front();
leavesToBeEmptied_.pop_front();
Node* newLeaf = node->splitLeaf();
Node *l1 = NULL, *l2 = NULL;
if (node->isFull()) {
l1 = node->splitLeaf();
}
if (newLeaf && newLeaf->isFull()) {
l2 = newLeaf->splitLeaf();
}
node->schedule(COMPRESS);
if (newLeaf) {
newLeaf->schedule(COMPRESS);
}
if (l1) {
l1->schedule(COMPRESS);
}
if (l2) {
l2->schedule(COMPRESS);
}
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Leaf node %d removed from full-leaf-list\n",
node->id_);
#endif
// % WHY?
//node->setQueueStatus(NONE);
}
}
Node* CompressTree::getEmptyRootNode() {
pthread_mutex_lock(&emptyRootNodesMutex_);
while (emptyRootNodes_.empty()) {
#ifdef CT_NODE_DEBUG
if (!rootNode_->buffer_.empty())
fprintf(stderr, "inserter sleeping (buffer not empty)\n");
else
fprintf(stderr, "inserter sleeping (queued somewhere %d)\n",
emptyRootNodes_.size());
#endif
pthread_cond_wait(&emptyRootAvailable_, &emptyRootNodesMutex_);
#ifdef CT_NODE_DEBUG
fprintf(stderr, "inserter fingered\n");
#endif
}
Node* e = emptyRootNodes_.front();
emptyRootNodes_.pop_front();
pthread_mutex_unlock(&emptyRootNodesMutex_);
return e;
}
void CompressTree::addEmptyRootNode(Node* n) {
bool no_empty_nodes = false;
pthread_mutex_lock(&emptyRootNodesMutex_);
// check if there are no empty nodes right now
if (emptyRootNodes_.empty())
no_empty_nodes = true;
emptyRootNodes_.push_back(n);
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Added empty root (now has: %d)\n",
emptyRootNodes_.size());
#endif
// if this is the first empty node, then signal
// if (no_empty_nodes)
pthread_cond_signal(&emptyRootAvailable_);
pthread_mutex_unlock(&emptyRootNodesMutex_);
}
bool CompressTree::rootNodeAvailable() {
if (!rootNode_->buffer_.empty() ||
rootNode_->getQueueStatus() != NONE)
return false;
return true;
}
void CompressTree::submitNodeForEmptying(Node* n) {
// perform the switch, schedule root, add node to empty list
Buffer temp;
temp.lists_ = rootNode_->buffer_.lists_;
rootNode_->buffer_.lists_ = n->buffer_.lists_;
rootNode_->schedule(EMPTY);
n->buffer_.lists_ = temp.lists_;
temp.clear();
addEmptyRootNode(n);
}
void CompressTree::startThreads() {
// create root node; initially a leaf
rootNode_ = new Node(this, 0);
rootNode_->buffer_.addList();
rootNode_->separator_ = UINT32_MAX;
rootNode_->buffer_.setCompressible(false);
#ifdef ENABLE_PAGING
rootNode_->buffer_.setPageable(false);
#endif // ENABLE_PAGING
inputNode_ = new Node(this, 0);
inputNode_->buffer_.addList();
inputNode_->separator_ = UINT32_MAX;
inputNode_->buffer_.setCompressible(false);
#ifdef ENABLE_PAGING
inputNode_->buffer_.setPageable(false);
#endif // ENABLE_PAGING
uint32_t number_of_root_nodes = 4;
for (uint32_t i = 0; i < number_of_root_nodes - 1; ++i) {
Node* n = new Node(this, 0);
n->buffer_.addList();
n->separator_ = UINT32_MAX;
n->buffer_.setCompressible(false);
#ifdef ENABLE_PAGING
n->buffer_.setPageable(false);
#endif // ENABLE_PAGING
emptyRootNodes_.push_back(n);
}
emptyType_ = IF_FULL;
uint32_t mergerThreadCount = 4;
uint32_t compressorThreadCount = 4;
uint32_t emptierThreadCount = 4;
uint32_t sorterThreadCount = 4;
// One for the inserter
uint32_t threadCount = mergerThreadCount + compressorThreadCount +
emptierThreadCount + sorterThreadCount + 1;
#ifdef ENABLE_PAGING
uint32_t pagerThreadCount = 1;
threadCount += pagerThreadCount;
#endif
#ifdef ENABLE_COUNTERS
uint32_t monitorThreadCount = 1;
threadCount += monitorThreadCount;
#endif
pthread_barrier_init(&threadsBarrier_, NULL, threadCount);
sem_init(&sleepSemaphore_, 0, threadCount - 1);
sorter_ = new Sorter(this);
sorter_->startThreads(sorterThreadCount);
merger_ = new Merger(this);
merger_->startThreads(mergerThreadCount);
compressor_ = new Compressor(this);
compressor_->startThreads(compressorThreadCount);
emptier_ = new Emptier(this);
emptier_->startThreads(emptierThreadCount);
#ifdef ENABLE_PAGING
pager_ = new Pager(this);
pager_->startThreads(pagerThreadCount);
#endif
#ifdef ENABLE_COUNTERS
monitor_ = new Monitor(this);
monitor_->startThreads(monitorThreadCount);
#endif
pthread_barrier_wait(&threadsBarrier_);
threadsStarted_ = true;
}
void CompressTree::stopThreads() {
delete inputNode_;
merger_->stopThreads();
sorter_->stopThreads();
emptier_->stopThreads();
compressor_->stopThreads();
#ifdef ENABLE_PAGING
pager_->stopThreads();
#endif
#ifdef ENABLE_COUNTERS
monitor_->stopThreads();
#endif
threadsStarted_ = false;
}
bool CompressTree::createNewRoot(Node* otherChild) {
Node* newRoot = new Node(this, rootNode_->level() + 1);
newRoot->buffer_.addList();
newRoot->separator_ = UINT32_MAX;
newRoot->buffer_.setCompressible(false);
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Node %d is new root; children are %d and %d\n",
newRoot->id_, rootNode_->id_, otherChild->id_);
#endif
// add two children of new root
newRoot->addChild(rootNode_);
newRoot->addChild(otherChild);
rootNode_ = newRoot;
return true;
}
}
<commit_msg>Increase sleep time<commit_after>// Copyright (C) 2012 Georgia Institute of Technology
//
// 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.
// ---
// Author: Hrishikesh Amur
#include <assert.h>
#include <stdio.h>
#define __STDC_LIMIT_MACROS /* for UINT32_MAX etc. */
#include <stdint.h>
#include <stdlib.h>
#include <deque>
#include "Buffer.h"
#include "CompressTree.h"
#include "Slaves.h"
namespace cbt {
uint32_t BUFFER_SIZE;
uint32_t MAX_ELS_PER_BUFFER;
uint32_t EMPTY_THRESHOLD;
CompressTree::CompressTree(uint32_t a, uint32_t b, uint32_t nodesInMemory,
uint32_t buffer_size, uint32_t pao_size,
const Operations* const ops) :
a_(a),
b_(b),
nodeCtr(1),
ops(ops),
alg_(SNAPPY),
allFlush_(true),
empty_(true),
lastLeafRead_(0),
lastOffset_(0),
lastElement_(0),
threadsStarted_(false) {
BUFFER_SIZE = buffer_size;
MAX_ELS_PER_BUFFER = BUFFER_SIZE / pao_size;
EMPTY_THRESHOLD = MAX_ELS_PER_BUFFER >> 1;
pthread_cond_init(&emptyRootAvailable_, NULL);
pthread_mutex_init(&emptyRootNodesMutex_, NULL);
#ifdef ENABLE_COUNTERS
monitor_ = NULL;
#endif
}
CompressTree::~CompressTree() {
pthread_cond_destroy(&emptyRootAvailable_);
pthread_mutex_destroy(&emptyRootNodesMutex_);
pthread_barrier_destroy(&threadsBarrier_);
}
bool CompressTree::bulk_insert(PartialAgg** paos, uint64_t num) {
bool ret = true;
// copy buf into root node buffer
// root node buffer always decompressed
if (num > 0)
allFlush_ = empty_ = false;
if (!threadsStarted_) {
startThreads();
}
for (uint64_t i = 0; i < num; ++i) {
PartialAgg* agg = paos[i];
if (inputNode_->isFull()) {
// add inputNode_ to be sorted
inputNode_->schedule(SORT);
// get an empty root. This function can block until there are
// empty roots available
inputNode_ = getEmptyRootNode();
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Now inputting into node %d\n",
inputNode_->id());
#endif // CT_NODE_DEBUG
}
ret &= inputNode_->insert(agg);
}
return ret;
}
bool CompressTree::insert(PartialAgg* agg) {
bool ret = bulk_insert(&agg, 1);
return ret;
}
bool CompressTree::bulk_read(PartialAgg** pao_list, uint64_t& num_read,
uint64_t max) {
uint64_t hash;
void* ptrToHash = reinterpret_cast<void*>(&hash);
num_read = 0;
while (num_read < max) {
if (!(nextValue(ptrToHash, pao_list[num_read])))
return false;
num_read++;
}
return true;
}
bool CompressTree::nextValue(void*& hash, PartialAgg*& agg) {
if (empty_)
return false;
if (!allFlush_) {
flushBuffers();
lastLeafRead_ = 0;
lastOffset_ = 0;
lastElement_ = 0;
allFlush_ = true;
// page in and decompress first leaf
Node* curLeaf = allLeaves_[0];
assert(curLeaf->buffer_.lists_.size() == 1);
while (curLeaf->buffer_.numElements() == 0)
curLeaf = allLeaves_[++lastLeafRead_];
curLeaf->schedule(DECOMPRESS_ONLY);
curLeaf->wait(DECOMPRESS_ONLY);
}
Node* curLeaf = allLeaves_[lastLeafRead_];
Buffer::List* l = curLeaf->buffer_.lists_[0];
hash = reinterpret_cast<void*>(&l->hashes_[lastElement_]);
ops->createPAO(NULL, &agg);
// if (lastLeafRead_ == 0)
// fprintf(stderr, "%ld\n", lastOffset_);
if (!(ops->deserialize(agg, l->data_ + lastOffset_,
l->sizes_[lastElement_]))) {
fprintf(stderr, "Can't deserialize at %u, index: %u\n", lastOffset_,
lastElement_);
assert(false);
}
lastOffset_ += l->sizes_[lastElement_];
lastElement_++;
if (lastElement_ >= curLeaf->buffer_.numElements()) {
curLeaf->schedule(COMPRESS);
if (++lastLeafRead_ == allLeaves_.size()) {
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Emptying tree!\n");
#endif
// Again wait for all to end
int all_done;
do {
usleep(1000);
sem_getvalue(&sleepSemaphore_, &all_done);
} while (all_done);
emptyTree();
stopThreads();
return false;
}
Node *n = allLeaves_[lastLeafRead_];
while (curLeaf->buffer_.numElements() == 0)
curLeaf = allLeaves_[++lastLeafRead_];
n->schedule(DECOMPRESS_ONLY);
n->wait(DECOMPRESS_ONLY);
lastOffset_ = 0;
lastElement_ = 0;
}
return true;
}
void CompressTree::clear() {
emptyTree();
stopThreads();
}
void CompressTree::emptyTree() {
std::deque<Node*> delList1;
std::deque<Node*> delList2;
delList1.push_back(rootNode_);
while (!delList1.empty()) {
Node* n = delList1.front();
delList1.pop_front();
for (uint32_t i = 0; i < n->children_.size(); ++i) {
delList1.push_back(n->children_[i]);
}
delList2.push_back(n);
}
while (!delList2.empty()) {
Node* n = delList2.front();
delList2.pop_front();
delete n;
}
allLeaves_.clear();
leavesToBeEmptied_.clear();
allFlush_ = empty_ = true;
lastLeafRead_ = 0;
lastOffset_ = 0;
lastElement_ = 0;
nodeCtr = 0;
}
bool CompressTree::flushBuffers() {
Node* curNode;
std::deque<Node*> visitQueue;
fprintf(stderr, "Starting to flush\n");
emptyType_ = ALWAYS;
inputNode_->schedule(SORT);
int all_done;
do {
usleep(1000);
sem_getvalue(&sleepSemaphore_, &all_done);
} while (all_done);
// add all leaves;
visitQueue.push_back(rootNode_);
while (!visitQueue.empty()) {
curNode = visitQueue.front();
visitQueue.pop_front();
if (curNode->isLeaf()) {
allLeaves_.push_back(curNode);
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Pushing node %d to all-leaves\t",
curNode->id_);
fprintf(stderr, "Now has: ");
for (uint32_t i = 0; i < allLeaves_.size(); ++i) {
fprintf(stderr, "%d ", allLeaves_[i]->id_);
}
fprintf(stderr, "\n");
#endif
continue;
}
for (uint32_t i = 0; i < curNode->children_.size(); ++i) {
visitQueue.push_back(curNode->children_[i]);
}
}
fprintf(stderr, "Tree has %ld leaves\n", allLeaves_.size());
uint32_t depth = 1;
curNode = rootNode_;
while (curNode->children_.size() > 0) {
depth++;
curNode = curNode->children_[0];
}
fprintf(stderr, "Tree has depth: %d\n", depth);
uint64_t numit = 0;
for (uint64_t i = 0; i < allLeaves_.size(); ++i)
numit += allLeaves_[i]->buffer_.numElements();
fprintf(stderr, "Tree has %ld elements\n", numit);
return true;
}
bool CompressTree::addLeafToEmpty(Node* node) {
leavesToBeEmptied_.push_back(node);
return true;
}
/* A full leaf is handled by splitting the leaf into two leaves.*/
void CompressTree::handleFullLeaves() {
while (!leavesToBeEmptied_.empty()) {
Node* node = leavesToBeEmptied_.front();
leavesToBeEmptied_.pop_front();
Node* newLeaf = node->splitLeaf();
Node *l1 = NULL, *l2 = NULL;
if (node->isFull()) {
l1 = node->splitLeaf();
}
if (newLeaf && newLeaf->isFull()) {
l2 = newLeaf->splitLeaf();
}
node->schedule(COMPRESS);
if (newLeaf) {
newLeaf->schedule(COMPRESS);
}
if (l1) {
l1->schedule(COMPRESS);
}
if (l2) {
l2->schedule(COMPRESS);
}
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Leaf node %d removed from full-leaf-list\n",
node->id_);
#endif
// % WHY?
//node->setQueueStatus(NONE);
}
}
Node* CompressTree::getEmptyRootNode() {
pthread_mutex_lock(&emptyRootNodesMutex_);
while (emptyRootNodes_.empty()) {
#ifdef CT_NODE_DEBUG
if (!rootNode_->buffer_.empty())
fprintf(stderr, "inserter sleeping (buffer not empty)\n");
else
fprintf(stderr, "inserter sleeping (queued somewhere %d)\n",
emptyRootNodes_.size());
#endif
pthread_cond_wait(&emptyRootAvailable_, &emptyRootNodesMutex_);
#ifdef CT_NODE_DEBUG
fprintf(stderr, "inserter fingered\n");
#endif
}
Node* e = emptyRootNodes_.front();
emptyRootNodes_.pop_front();
pthread_mutex_unlock(&emptyRootNodesMutex_);
return e;
}
void CompressTree::addEmptyRootNode(Node* n) {
bool no_empty_nodes = false;
pthread_mutex_lock(&emptyRootNodesMutex_);
// check if there are no empty nodes right now
if (emptyRootNodes_.empty())
no_empty_nodes = true;
emptyRootNodes_.push_back(n);
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Added empty root (now has: %d)\n",
emptyRootNodes_.size());
#endif
// if this is the first empty node, then signal
// if (no_empty_nodes)
pthread_cond_signal(&emptyRootAvailable_);
pthread_mutex_unlock(&emptyRootNodesMutex_);
}
bool CompressTree::rootNodeAvailable() {
if (!rootNode_->buffer_.empty() ||
rootNode_->getQueueStatus() != NONE)
return false;
return true;
}
void CompressTree::submitNodeForEmptying(Node* n) {
// perform the switch, schedule root, add node to empty list
Buffer temp;
temp.lists_ = rootNode_->buffer_.lists_;
rootNode_->buffer_.lists_ = n->buffer_.lists_;
rootNode_->schedule(EMPTY);
n->buffer_.lists_ = temp.lists_;
temp.clear();
addEmptyRootNode(n);
}
void CompressTree::startThreads() {
// create root node; initially a leaf
rootNode_ = new Node(this, 0);
rootNode_->buffer_.addList();
rootNode_->separator_ = UINT32_MAX;
rootNode_->buffer_.setCompressible(false);
#ifdef ENABLE_PAGING
rootNode_->buffer_.setPageable(false);
#endif // ENABLE_PAGING
inputNode_ = new Node(this, 0);
inputNode_->buffer_.addList();
inputNode_->separator_ = UINT32_MAX;
inputNode_->buffer_.setCompressible(false);
#ifdef ENABLE_PAGING
inputNode_->buffer_.setPageable(false);
#endif // ENABLE_PAGING
uint32_t number_of_root_nodes = 4;
for (uint32_t i = 0; i < number_of_root_nodes - 1; ++i) {
Node* n = new Node(this, 0);
n->buffer_.addList();
n->separator_ = UINT32_MAX;
n->buffer_.setCompressible(false);
#ifdef ENABLE_PAGING
n->buffer_.setPageable(false);
#endif // ENABLE_PAGING
emptyRootNodes_.push_back(n);
}
emptyType_ = IF_FULL;
uint32_t mergerThreadCount = 4;
uint32_t compressorThreadCount = 4;
uint32_t emptierThreadCount = 4;
uint32_t sorterThreadCount = 4;
// One for the inserter
uint32_t threadCount = mergerThreadCount + compressorThreadCount +
emptierThreadCount + sorterThreadCount + 1;
#ifdef ENABLE_PAGING
uint32_t pagerThreadCount = 1;
threadCount += pagerThreadCount;
#endif
#ifdef ENABLE_COUNTERS
uint32_t monitorThreadCount = 1;
threadCount += monitorThreadCount;
#endif
pthread_barrier_init(&threadsBarrier_, NULL, threadCount);
sem_init(&sleepSemaphore_, 0, threadCount - 1);
sorter_ = new Sorter(this);
sorter_->startThreads(sorterThreadCount);
merger_ = new Merger(this);
merger_->startThreads(mergerThreadCount);
compressor_ = new Compressor(this);
compressor_->startThreads(compressorThreadCount);
emptier_ = new Emptier(this);
emptier_->startThreads(emptierThreadCount);
#ifdef ENABLE_PAGING
pager_ = new Pager(this);
pager_->startThreads(pagerThreadCount);
#endif
#ifdef ENABLE_COUNTERS
monitor_ = new Monitor(this);
monitor_->startThreads(monitorThreadCount);
#endif
pthread_barrier_wait(&threadsBarrier_);
threadsStarted_ = true;
}
void CompressTree::stopThreads() {
delete inputNode_;
merger_->stopThreads();
sorter_->stopThreads();
emptier_->stopThreads();
compressor_->stopThreads();
#ifdef ENABLE_PAGING
pager_->stopThreads();
#endif
#ifdef ENABLE_COUNTERS
monitor_->stopThreads();
#endif
threadsStarted_ = false;
}
bool CompressTree::createNewRoot(Node* otherChild) {
Node* newRoot = new Node(this, rootNode_->level() + 1);
newRoot->buffer_.addList();
newRoot->separator_ = UINT32_MAX;
newRoot->buffer_.setCompressible(false);
#ifdef CT_NODE_DEBUG
fprintf(stderr, "Node %d is new root; children are %d and %d\n",
newRoot->id_, rootNode_->id_, otherChild->id_);
#endif
// add two children of new root
newRoot->addChild(rootNode_);
newRoot->addChild(otherChild);
rootNode_ = newRoot;
return true;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Copyright(c) 2020 jwellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include "UnitTest++/UnitTest++.h"
#include <thread>
#include <vector>
#include <numeric>
#include <array>
#include <algorithm>
#include <queue>
#include <atomic>
#include "etl/atomic.h"
#include "etl/queue_spsc_atomic.h"
#include "etl/buffer_descriptors.h"
#if defined(ETL_TARGET_OS_WINDOWS)
#include <Windows.h>
#endif
#define REALTIME_TEST 0
namespace
{
constexpr size_t BUFFER_SIZE = 16U;
constexpr size_t N_BUFFERS = 4U;
constexpr size_t DATA_COUNT = BUFFER_SIZE / 2;
using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>;
static char buffers[N_BUFFERS][BUFFER_SIZE];
//***********************************
struct Receiver
{
void receive(BD::notification n)
{
pbuffer = n.get_descriptor().data();
count = n.get_count();
}
BD::pointer pbuffer;
BD::size_type count;
};
SUITE(test_buffer_descriptors)
{
//*************************************************************************
TEST(test_constructor_plus_buffer)
{
BD bd(&buffers[0][0]);
CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS);
CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE);
CHECK(!bd.is_valid());
}
//*************************************************************************
TEST(test_constructor_plus_buffer_and_callback)
{
Receiver receiver;
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0], callback);
CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS);
CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE);
CHECK(bd.is_valid());
}
//*************************************************************************
TEST(test_constructor_plus_buffer_set_callback)
{
Receiver receiver;
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0]);
bd.set_callback(callback);
CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS);
CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE);
CHECK(bd.is_valid());
}
//*************************************************************************
TEST(test_buffers)
{
Receiver receiver;
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0], callback);
for (size_t i = 0U; i < N_BUFFERS; ++i)
{
BD::descriptor desc = bd.allocate();
CHECK_EQUAL(BUFFER_SIZE, desc.max_size());
CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data()));
}
}
//*************************************************************************
TEST(test_buffers_with_allocate_fill)
{
Receiver receiver;
std::array<char, BUFFER_SIZE> test =
{
char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF),
char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF)
};
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0], callback);
for (size_t i = 0U; i < N_BUFFERS; ++i)
{
BD::descriptor desc = bd.allocate(char(0xFF));
CHECK_EQUAL(BUFFER_SIZE, desc.max_size());
CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data()));
CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE);
}
}
//*************************************************************************
TEST(test_notifications)
{
Receiver receiver;
std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 };
std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U);
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0], callback);
for (size_t i = 0U; i < N_BUFFERS; ++i)
{
BD::descriptor desc = bd.allocate();
CHECK(desc.is_valid());
std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data());
bd.notify(BD::notification(desc, DATA_COUNT));
desc.release();
CHECK_EQUAL(DATA_COUNT, receiver.count);
CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer));
CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE);
}
}
//*************************************************************************
TEST(test_allocate_overflow)
{
Receiver receiver;
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0], callback);
// Use up all of the descriptors.
for (size_t i = 0U; i < N_BUFFERS; ++i)
{
BD::descriptor desc = bd.allocate();
CHECK(desc.is_valid());
}
BD::descriptor desc = bd.allocate();
CHECK(!desc.is_valid());
}
//*************************************************************************
TEST(test_allocate_release_rollover)
{
static Receiver receiver;
std::queue<BD::descriptor> desc_queue;
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0], callback);
// Use up all of the descriptors, then release/allocate for the rest.
for (size_t i = 0U; i < (N_BUFFERS * 2); ++i)
{
BD::descriptor desc = bd.allocate();
desc_queue.push(desc);
CHECK(desc.is_valid());
if (i >= (N_BUFFERS - 1))
{
desc_queue.front().release();
desc_queue.pop();
}
}
}
//*************************************************************************
TEST(test_descriptors)
{
BD bd(&buffers[0][0]);
BD::descriptor desc1 = bd.allocate();
BD::descriptor desc2 = bd.allocate();
BD::descriptor desc3 = bd.allocate();
BD::descriptor desc4 = bd.allocate();
CHECK(desc1.is_allocated());
CHECK(desc2.is_allocated());
CHECK(desc3.is_allocated());
CHECK(desc4.is_allocated());
CHECK(desc1.data() == &buffers[0][0]);
CHECK(desc2.data() == &buffers[1][0]);
CHECK(desc3.data() == &buffers[2][0]);
CHECK(desc4.data() == &buffers[3][0]);
CHECK(desc1.max_size() == BUFFER_SIZE);
CHECK(desc2.max_size() == BUFFER_SIZE);
CHECK(desc3.max_size() == BUFFER_SIZE);
CHECK(desc4.max_size() == BUFFER_SIZE);
CHECK(desc1.MAX_SIZE == BUFFER_SIZE);
CHECK(desc2.MAX_SIZE == BUFFER_SIZE);
CHECK(desc3.MAX_SIZE == BUFFER_SIZE);
CHECK(desc4.MAX_SIZE == BUFFER_SIZE);
CHECK(desc1.is_valid());
CHECK(desc2.is_valid());
CHECK(desc3.is_valid());
CHECK(desc4.is_valid());
desc1.release();
desc2.release();
desc3.release();
desc4.release();
CHECK(desc1.is_released());
CHECK(desc2.is_released());
CHECK(desc3.is_released());
CHECK(desc4.is_released());
}
//*************************************************************************
#if REALTIME_TEST
#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported
#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)
#define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1)
#define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2)
#else
#define RAISE_THREAD_PRIORITY
#define FIX_PROCESSOR_AFFINITY1
#define FIX_PROCESSOR_AFFINITY2
#endif
std::atomic_bool start = false;
//*********************************
struct Notification
{
BD::descriptor desc;
BD::size_type count;
};
constexpr int N_ITERATIONS = 1000000;
etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue;
//*********************************
void Callback(BD::notification n)
{
desc_queue.push(n);
}
//*********************************
void Producer()
{
static char buffers[N_BUFFERS][BUFFER_SIZE];
BD bd(&buffers[0][0], BD::callback_type::create<Callback>());
RAISE_THREAD_PRIORITY;
FIX_PROCESSOR_AFFINITY1;
// Wait for the start flag.
while (!start);
int errors = 0;
for (int i = 0; i < N_ITERATIONS; ++i)
{
BD::descriptor desc;
// Wait until we can allocate a descriptor.
do
{
desc = bd.allocate();
} while (desc.is_valid() == false);
if (!desc.is_allocated())
{
++errors;
}
// Send a notification to the callback function.
bd.notify(BD::notification(desc, BUFFER_SIZE));
}
CHECK_EQUAL(0, errors);
}
//*********************************
void Consumer()
{
RAISE_THREAD_PRIORITY;
FIX_PROCESSOR_AFFINITY2;
// Wait for the start flag.
while (!start);
int errors = 0;
for (int i = 0; i < N_ITERATIONS;)
{
BD::notification notification;
// Try to get a notification from the queue.
if (desc_queue.pop(notification))
{
CHECK_EQUAL(BUFFER_SIZE, notification.get_count());
CHECK(notification.get_descriptor().is_allocated());
if (!notification.get_descriptor().is_allocated())
{
++errors;
}
notification.get_descriptor().release();
++i;
}
CHECK_EQUAL(0, errors);
}
}
//*********************************
TEST(test_multi_thread)
{
std::thread t1(Producer);
std::thread t2(Consumer);
start = true;
t1.join();
t2.join();
}
#endif
};
}
<commit_msg>Refactor buffer_descriptors test<commit_after>/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Copyright(c) 2020 jwellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include "UnitTest++/UnitTest++.h"
#include <thread>
#include <vector>
#include <numeric>
#include <array>
#include <algorithm>
#include <queue>
#include <atomic>
#include "etl/atomic.h"
#include "etl/queue_spsc_atomic.h"
#include "etl/buffer_descriptors.h"
#if defined(ETL_TARGET_OS_WINDOWS)
#include <Windows.h>
#endif
#define REALTIME_TEST 0
namespace
{
constexpr size_t BUFFER_SIZE = 16U;
constexpr size_t N_BUFFERS = 4U;
constexpr size_t DATA_COUNT = BUFFER_SIZE / 2;
using BD = etl::buffer_descriptors<char, BUFFER_SIZE, N_BUFFERS, std::atomic_char>;
char buffers[N_BUFFERS][BUFFER_SIZE];
Receiver receiver;
//***********************************
struct Receiver
{
void receive(BD::notification n)
{
pbuffer = n.get_descriptor().data();
count = n.get_count();
}
void clear()
{
pbuffer = nullptr;
count = 0U;
}
BD::pointer pbuffer;
BD::size_type count;
};
SUITE(test_buffer_descriptors)
{
//*************************************************************************
TEST(test_constructor_plus_buffer)
{
BD bd(&buffers[0][0]);
CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS);
CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE);
CHECK(!bd.is_valid());
}
//*************************************************************************
TEST(test_constructor_plus_buffer_and_callback)
{
receiver.clear();
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0], callback);
CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS);
CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE);
CHECK(bd.is_valid());
}
//*************************************************************************
TEST(test_constructor_plus_buffer_set_callback)
{
receiver.clear();
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0]);
bd.set_callback(callback);
CHECK_EQUAL(N_BUFFERS, bd.N_BUFFERS);
CHECK_EQUAL(BUFFER_SIZE, bd.BUFFER_SIZE);
CHECK(bd.is_valid());
}
//*************************************************************************
TEST(test_buffers)
{
BD bd(&buffers[0][0]);
for (size_t i = 0U; i < N_BUFFERS; ++i)
{
BD::descriptor desc = bd.allocate();
CHECK_EQUAL(BUFFER_SIZE, desc.max_size());
CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data()));
}
}
//*************************************************************************
TEST(test_buffers_with_allocate_fill)
{
std::array<char, BUFFER_SIZE> test =
{
char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF),
char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF), char(0xFF)
};
BD bd(&buffers[0][0]);
for (size_t i = 0U; i < N_BUFFERS; ++i)
{
BD::descriptor desc = bd.allocate(char(0xFF));
CHECK_EQUAL(BUFFER_SIZE, desc.max_size());
CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(desc.data()));
CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE);
}
}
//*************************************************************************
TEST(test_notifications)
{
std::array<char, BUFFER_SIZE> test = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0 };
std::fill(&buffers[0][0], &buffers[N_BUFFERS - 1][0] + BUFFER_SIZE , 0U);
receiver.clear();
BD::callback_type callback = BD::callback_type::create<Receiver, &Receiver::receive>(receiver);
BD bd(&buffers[0][0], callback);
for (size_t i = 0U; i < N_BUFFERS; ++i)
{
BD::descriptor desc = bd.allocate();
CHECK(desc.is_valid());
std::copy(test.begin(), test.begin() + DATA_COUNT, desc.data());
bd.notify(BD::notification(desc, DATA_COUNT));
desc.release();
CHECK_EQUAL(DATA_COUNT, receiver.count);
CHECK_EQUAL(uintptr_t(&buffers[i][0]), uintptr_t(receiver.pbuffer));
CHECK_ARRAY_EQUAL(test.data(), desc.data(), BUFFER_SIZE);
}
}
//*************************************************************************
TEST(test_allocate_overflow)
{
BD bd(&buffers[0][0]);
// Use up all of the descriptors.
for (size_t i = 0U; i < N_BUFFERS; ++i)
{
BD::descriptor desc = bd.allocate();
CHECK(desc.is_valid());
}
BD::descriptor desc = bd.allocate();
CHECK(!desc.is_valid());
}
//*************************************************************************
TEST(test_allocate_release_rollover)
{
std::queue<BD::descriptor> desc_queue;
BD bd(&buffers[0][0]);
// Use up all of the descriptors, then release/allocate for the rest.
for (size_t i = 0U; i < (N_BUFFERS * 2); ++i)
{
BD::descriptor desc = bd.allocate();
desc_queue.push(desc);
CHECK(desc.is_valid());
if (i >= (N_BUFFERS - 1))
{
desc_queue.front().release();
desc_queue.pop();
}
}
}
//*************************************************************************
TEST(test_descriptors)
{
BD bd(&buffers[0][0]);
BD::descriptor desc1 = bd.allocate();
BD::descriptor desc2 = bd.allocate();
BD::descriptor desc3 = bd.allocate();
BD::descriptor desc4 = bd.allocate();
CHECK(desc1.is_allocated());
CHECK(desc2.is_allocated());
CHECK(desc3.is_allocated());
CHECK(desc4.is_allocated());
CHECK(desc1.data() == &buffers[0][0]);
CHECK(desc2.data() == &buffers[1][0]);
CHECK(desc3.data() == &buffers[2][0]);
CHECK(desc4.data() == &buffers[3][0]);
CHECK(desc1.max_size() == BUFFER_SIZE);
CHECK(desc2.max_size() == BUFFER_SIZE);
CHECK(desc3.max_size() == BUFFER_SIZE);
CHECK(desc4.max_size() == BUFFER_SIZE);
CHECK(desc1.MAX_SIZE == BUFFER_SIZE);
CHECK(desc2.MAX_SIZE == BUFFER_SIZE);
CHECK(desc3.MAX_SIZE == BUFFER_SIZE);
CHECK(desc4.MAX_SIZE == BUFFER_SIZE);
CHECK(desc1.is_valid());
CHECK(desc2.is_valid());
CHECK(desc3.is_valid());
CHECK(desc4.is_valid());
desc1.release();
desc2.release();
desc3.release();
desc4.release();
CHECK(desc1.is_released());
CHECK(desc2.is_released());
CHECK(desc3.is_released());
CHECK(desc4.is_released());
}
//*************************************************************************
#if REALTIME_TEST
#if defined(ETL_TARGET_OS_WINDOWS) // Only Windows priority is currently supported
#define RAISE_THREAD_PRIORITY SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)
#define FIX_PROCESSOR_AFFINITY1 SetThreadAffinityMask(GetCurrentThread(), 1)
#define FIX_PROCESSOR_AFFINITY2 SetThreadAffinityMask(GetCurrentThread(), 2)
#else
#define RAISE_THREAD_PRIORITY
#define FIX_PROCESSOR_AFFINITY1
#define FIX_PROCESSOR_AFFINITY2
#endif
std::atomic_bool start = false;
//*********************************
struct Notification
{
BD::descriptor desc;
BD::size_type count;
};
constexpr int N_ITERATIONS = 1000000;
etl::queue_spsc_atomic<BD::notification, N_ITERATIONS + 100> desc_queue;
//*********************************
void Callback(BD::notification n)
{
desc_queue.push(n);
}
//*********************************
void Producer()
{
static char buffers[N_BUFFERS][BUFFER_SIZE];
BD bd(&buffers[0][0], BD::callback_type::create<Callback>());
RAISE_THREAD_PRIORITY;
FIX_PROCESSOR_AFFINITY1;
// Wait for the start flag.
while (!start);
int errors = 0;
for (int i = 0; i < N_ITERATIONS; ++i)
{
BD::descriptor desc;
// Wait until we can allocate a descriptor.
do
{
desc = bd.allocate();
} while (desc.is_valid() == false);
if (!desc.is_allocated())
{
++errors;
}
// Send a notification to the callback function.
bd.notify(BD::notification(desc, BUFFER_SIZE));
}
CHECK_EQUAL(0, errors);
}
//*********************************
void Consumer()
{
RAISE_THREAD_PRIORITY;
FIX_PROCESSOR_AFFINITY2;
// Wait for the start flag.
while (!start);
int errors = 0;
for (int i = 0; i < N_ITERATIONS;)
{
BD::notification notification;
// Try to get a notification from the queue.
if (desc_queue.pop(notification))
{
CHECK_EQUAL(BUFFER_SIZE, notification.get_count());
CHECK(notification.get_descriptor().is_allocated());
if (!notification.get_descriptor().is_allocated())
{
++errors;
}
notification.get_descriptor().release();
++i;
}
CHECK_EQUAL(0, errors);
}
}
//*********************************
TEST(test_multi_thread)
{
std::thread t1(Producer);
std::thread t2(Consumer);
start = true;
t1.join();
t2.join();
}
#endif
};
}
<|endoftext|> |
<commit_before>769be054-5216-11e5-ada8-6c40088e03e4<commit_msg>76a2755c-5216-11e5-98df-6c40088e03e4<commit_after>76a2755c-5216-11e5-98df-6c40088e03e4<|endoftext|> |
<commit_before>#include "CopyDevice.h"
#include "CopyOpenFile.h"
#include <sys/types.h>
#include <fcntl.h>
#include "messmer/fspp/fuse/FuseErrnoException.h"
#include <messmer/cpp-utils/assert/assert.h>
namespace bf = boost::filesystem;
//TODO Get rid of this in favor of a exception hierarchy
using fspp::fuse::CHECK_RETVAL;
namespace copyfs {
CopyOpenFile::CopyOpenFile(const CopyDevice *device, const bf::path &path, int flags)
:_descriptor(::open((device->RootDir() / path).c_str(), flags)) {
CHECK_RETVAL(_descriptor);
}
CopyOpenFile::~CopyOpenFile() {
int retval = ::close(_descriptor);
CHECK_RETVAL(retval);
}
void CopyOpenFile::flush() {
}
void CopyOpenFile::stat(struct ::stat *result) const {
int retval = ::fstat(_descriptor, result);
CHECK_RETVAL(retval);
}
void CopyOpenFile::truncate(off_t size) const {
int retval = ::ftruncate(_descriptor, size);
CHECK_RETVAL(retval);
}
ssize_t CopyOpenFile::read(void *buf, size_t count, off_t offset) const {
int retval = ::pread(_descriptor, buf, count, offset);
CHECK_RETVAL(retval);
ASSERT(static_cast<unsigned int>(retval) <= count, "Read wrong number of bytes");
return retval;
}
void CopyOpenFile::write(const void *buf, size_t count, off_t offset) {
int retval = ::pwrite(_descriptor, buf, count, offset);
CHECK_RETVAL(retval);
ASSERT(static_cast<unsigned int>(retval) == count, "Wrong number of bytes written");
}
void CopyOpenFile::fsync() {
int retval = ::fsync(_descriptor);
CHECK_RETVAL(retval);
}
void CopyOpenFile::fdatasync() {
int retval = ::fdatasync(_descriptor);
CHECK_RETVAL(retval);
}
}
<commit_msg>Fix fdatasync for Mac OS X<commit_after>#include "CopyDevice.h"
#include "CopyOpenFile.h"
#include <sys/types.h>
#include <fcntl.h>
#include "messmer/fspp/fuse/FuseErrnoException.h"
#include <messmer/cpp-utils/assert/assert.h>
namespace bf = boost::filesystem;
//TODO Get rid of this in favor of a exception hierarchy
using fspp::fuse::CHECK_RETVAL;
namespace copyfs {
CopyOpenFile::CopyOpenFile(const CopyDevice *device, const bf::path &path, int flags)
:_descriptor(::open((device->RootDir() / path).c_str(), flags)) {
CHECK_RETVAL(_descriptor);
}
CopyOpenFile::~CopyOpenFile() {
int retval = ::close(_descriptor);
CHECK_RETVAL(retval);
}
void CopyOpenFile::flush() {
}
void CopyOpenFile::stat(struct ::stat *result) const {
int retval = ::fstat(_descriptor, result);
CHECK_RETVAL(retval);
}
void CopyOpenFile::truncate(off_t size) const {
int retval = ::ftruncate(_descriptor, size);
CHECK_RETVAL(retval);
}
ssize_t CopyOpenFile::read(void *buf, size_t count, off_t offset) const {
int retval = ::pread(_descriptor, buf, count, offset);
CHECK_RETVAL(retval);
ASSERT(static_cast<unsigned int>(retval) <= count, "Read wrong number of bytes");
return retval;
}
void CopyOpenFile::write(const void *buf, size_t count, off_t offset) {
int retval = ::pwrite(_descriptor, buf, count, offset);
CHECK_RETVAL(retval);
ASSERT(static_cast<unsigned int>(retval) == count, "Wrong number of bytes written");
}
void CopyOpenFile::fsync() {
int retval = ::fsync(_descriptor);
CHECK_RETVAL(retval);
}
void CopyOpenFile::fdatasync() {
#ifdef F_FULLFSYNC
// This is MacOSX, which doesn't know fdatasync
int retval = fcntl(_descriptor, F_FULLFSYNC);
#else
int retval = ::fdatasync(_descriptor);
#endif
CHECK_RETVAL(retval);
}
}
<|endoftext|> |
<commit_before>5626d223-2e4f-11e5-9aeb-28cfe91dbc4b<commit_msg>562dc1eb-2e4f-11e5-b764-28cfe91dbc4b<commit_after>562dc1eb-2e4f-11e5-b764-28cfe91dbc4b<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, 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/session.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/extensions/metadata_transfer.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"
#include <iostream>
using boost::tuples::ignore;
void test_transfer(bool clear_files, bool disconnect
, boost::shared_ptr<libtorrent::torrent_plugin> (*constructor)(libtorrent::torrent*, void*))
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48100, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49100, 50000), "0.0.0.0", 0);
ses1.add_extension(constructor);
ses2.add_extension(constructor);
torrent_handle tor1;
torrent_handle tor2;
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::forced;
pes.in_enc_policy = pe_settings::forced;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
#endif
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0, clear_files, true, true, "_meta");
for (int i = 0; i < 80; ++i)
{
// make sure this function can be called on
// torrents without metadata
if (!disconnect) tor2.status();
print_alerts(ses1, "ses1", false, true);
print_alerts(ses2, "ses2", false, true);
if (disconnect && tor2.is_valid()) ses2.remove_torrent(tor2);
if (!disconnect && tor2.status().has_metadata) break;
test_sleep(100);
}
if (disconnect) return;
TEST_CHECK(tor2.status().has_metadata);
std::cerr << "waiting for transfer to complete\n";
for (int i = 0; i < 30; ++i)
{
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
std::cerr
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< st1.num_peers << ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers
<< std::endl;
if (st2.is_seeding) break;
test_sleep(1000);
}
TEST_CHECK(tor2.status().is_seeding);
if (tor2.status().is_seeding) std::cerr << "done\n";
error_code ec;
remove_all("./tmp1_meta", ec);
remove_all("./tmp2_meta", ec);
remove_all("./tmp3_meta", ec);
}
int test_main()
{
using namespace libtorrent;
// test to disconnect one client prematurely
test_transfer(true, true, &create_metadata_plugin);
// test where one has data and one doesn't
test_transfer(true, false, &create_metadata_plugin);
// test where both have data (to trigger the file check)
test_transfer(false, false, &create_metadata_plugin);
// test to disconnect one client prematurely
test_transfer(true, true, &create_ut_metadata_plugin);
// test where one has data and one doesn't
test_transfer(true, false, &create_ut_metadata_plugin);
// test where both have data (to trigger the file check)
test_transfer(false, false, &create_ut_metadata_plugin);
error_code ec;
remove_all("./tmp1", ec);
remove_all("./tmp2", ec);
return 0;
}
<commit_msg>extend the metadata unit test to make sure the metadata is forwarded to a 3rd peer<commit_after>/*
Copyright (c) 2008, 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/session.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/extensions/metadata_transfer.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"
#include <iostream>
using boost::tuples::ignore;
void test_transfer(bool clear_files, bool disconnect
, boost::shared_ptr<libtorrent::torrent_plugin> (*constructor)(libtorrent::torrent*, void*))
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48100, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49100, 50000), "0.0.0.0", 0);
session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50100, 51000), "0.0.0.0", 0);
ses1.add_extension(constructor);
ses2.add_extension(constructor);
ses3.add_extension(constructor);
torrent_handle tor1;
torrent_handle tor2;
torrent_handle tor3;
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::forced;
pes.in_enc_policy = pe_settings::forced;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
ses3.set_pe_settings(pes);
#endif
boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, clear_files, true, true, "_meta");
for (int i = 0; i < 80; ++i)
{
// make sure this function can be called on
// torrents without metadata
if (!disconnect) tor2.status();
print_alerts(ses1, "ses1", false, true);
print_alerts(ses2, "ses2", false, true);
if (disconnect && tor2.is_valid()) ses2.remove_torrent(tor2);
if (!disconnect
&& tor2.status().has_metadata
&& tor3.status().has_metadata) break;
test_sleep(100);
}
if (disconnect) return;
TEST_CHECK(tor2.status().has_metadata);
TEST_CHECK(tor3.status().has_metadata);
std::cerr << "waiting for transfer to complete\n";
for (int i = 0; i < 30; ++i)
{
torrent_status st1 = tor1.status();
torrent_status st2 = tor2.status();
std::cerr
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< st1.num_peers << ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers
<< std::endl;
if (st2.is_seeding) break;
test_sleep(1000);
}
TEST_CHECK(tor2.status().is_seeding);
if (tor2.status().is_seeding) std::cerr << "done\n";
error_code ec;
remove_all("./tmp1_meta", ec);
remove_all("./tmp2_meta", ec);
remove_all("./tmp3_meta", ec);
}
int test_main()
{
using namespace libtorrent;
// test to disconnect one client prematurely
test_transfer(true, true, &create_metadata_plugin);
// test where one has data and one doesn't
test_transfer(true, false, &create_metadata_plugin);
// test where both have data (to trigger the file check)
test_transfer(false, false, &create_metadata_plugin);
// test to disconnect one client prematurely
test_transfer(true, true, &create_ut_metadata_plugin);
// test where one has data and one doesn't
test_transfer(true, false, &create_ut_metadata_plugin);
// test where both have data (to trigger the file check)
test_transfer(false, false, &create_ut_metadata_plugin);
error_code ec;
remove_all("./tmp1", ec);
remove_all("./tmp2", ec);
return 0;
}
<|endoftext|> |
<commit_before>#include <AlpinoCorpus/CorpusReader.hh>
#include <AlpinoCorpus/DbCorpusReader.hh>
#include <AlpinoCorpus/DirectoryCorpusReader.hh>
#include <AlpinoCorpus/Error.hh>
#include <AlpinoCorpus/IndexedCorpusReader.hh>
#include <QString>
#include <typeinfo>
#include <libxml/parser.h>
#include <QDebug>
namespace alpinocorpus {
CorpusReader *CorpusReader::open(QString const &corpusPath)
{
try {
return new DirectoryCorpusReader(corpusPath);
} catch (OpenError const &e) {
}
try {
return new IndexedCorpusReader(corpusPath);
} catch (OpenError const &e) {
}
return new DbCorpusReader(corpusPath);
}
bool CorpusReader::EntryIterator::operator==(EntryIterator const &other) const
{
if (!impl)
return !other.impl;
else if (!other.impl)
return !impl;
else
return impl->equals(*other.impl.data());
}
CorpusReader::EntryIterator &CorpusReader::EntryIterator::operator++()
{
impl->next();
return *this;
}
CorpusReader::EntryIterator CorpusReader::EntryIterator::operator++(int)
{
EntryIterator r(*this);
operator++();
return r;
}
CorpusReader::EntryIterator CorpusReader::query(CorpusReader::Dialect d,
QString const &q) const
{
switch (d) {
case XPATH: return runXPath(q);
case XQUERY: return runXQuery(q);
default: throw NotImplemented("unknown query language");
}
}
CorpusReader::EntryIterator CorpusReader::runXPath(QString const &query) const
{
//throw NotImplemented(typeid(*this).name(), "XQuery functionality");
return EntryIterator(new FilterIter(*this, getBegin(), getEnd(), query));
}
CorpusReader::EntryIterator CorpusReader::runXQuery(QString const &) const
{
throw NotImplemented(typeid(*this).name(), "XQuery functionality");
}
CorpusReader::FilterIter::FilterIter(CorpusReader const &corpus,
EntryIterator itr, EntryIterator end, QString const &query)
:
d_corpus(corpus),
d_itr(itr),
d_end(end),
d_query(query.toUtf8())
{
next();
}
QString CorpusReader::FilterIter::current() const
{
return d_file;
}
bool CorpusReader::FilterIter::equals(IterImpl const &itr) const
{
try {
// TODO fix me to be more like isEqual instead of hasNext.
return d_itr == d_end
&& d_buffer.size() == 0;
} catch (std::bad_cast const &e) {
return false;
}
}
void CorpusReader::FilterIter::next()
{
if (!d_buffer.isEmpty())
{
d_buffer.dequeue();
return;
}
while (d_buffer.isEmpty() && d_itr != d_end)
{
d_file = *d_itr;
parseFile(d_file);
++d_itr;
}
}
QString CorpusReader::FilterIter::contents(CorpusReader const &rdr) const
{
return d_buffer.isEmpty()
? QString()
: d_buffer.head();
}
void CorpusReader::FilterIter::parseFile(QString const &file)
{
QString xml(d_corpus.read(file));
QByteArray xmlData(xml.toUtf8());
xmlDocPtr doc = xmlParseMemory(xmlData.constData(), xmlData.size());
if (!doc)
{
qWarning() << "XPathMapper::run: could not parse XML data: " << *d_itr;
return;
}
// Parse XPath query
xmlXPathContextPtr ctx = xmlXPathNewContext(doc);
if (!ctx)
{
xmlFreeDoc(doc);
qWarning() << "XPathMapper::run: could not construct XPath context from document: " << *d_itr;
return;
}
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(
reinterpret_cast<xmlChar const *>(d_query.constData()), ctx);
if (!xpathObj)
{
xmlXPathFreeContext(ctx);
xmlFreeDoc(doc);
throw Error("XPathMapper::run: could not evaluate XPath expression.");
}
if (xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0)
{
for (int i = 0; i < xpathObj->nodesetval->nodeNr; ++i)
{
xmlChar *str = xmlNodeListGetString(doc, xpathObj->nodesetval->nodeTab[i]->children, 1);
QString value(QString::fromUtf8(reinterpret_cast<const char *>(str)));
xmlFree(str);
if (value.trimmed().isEmpty())
d_buffer.enqueue(QString());
else
d_buffer.enqueue(value);
}
}
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(ctx);
xmlFreeDoc(doc);
}
}
<commit_msg>Fix invalid FilterIter state.<commit_after>#include <AlpinoCorpus/CorpusReader.hh>
#include <AlpinoCorpus/DbCorpusReader.hh>
#include <AlpinoCorpus/DirectoryCorpusReader.hh>
#include <AlpinoCorpus/Error.hh>
#include <AlpinoCorpus/IndexedCorpusReader.hh>
#include <QString>
#include <typeinfo>
#include <libxml/parser.h>
#include <QDebug>
namespace alpinocorpus {
CorpusReader *CorpusReader::open(QString const &corpusPath)
{
try {
return new DirectoryCorpusReader(corpusPath);
} catch (OpenError const &e) {
}
try {
return new IndexedCorpusReader(corpusPath);
} catch (OpenError const &e) {
}
return new DbCorpusReader(corpusPath);
}
bool CorpusReader::EntryIterator::operator==(EntryIterator const &other) const
{
if (!impl)
return !other.impl;
else if (!other.impl)
return !impl;
else
return impl->equals(*other.impl.data());
}
CorpusReader::EntryIterator &CorpusReader::EntryIterator::operator++()
{
impl->next();
return *this;
}
CorpusReader::EntryIterator CorpusReader::EntryIterator::operator++(int)
{
EntryIterator r(*this);
operator++();
return r;
}
CorpusReader::EntryIterator CorpusReader::query(CorpusReader::Dialect d,
QString const &q) const
{
switch (d) {
case XPATH: return runXPath(q);
case XQUERY: return runXQuery(q);
default: throw NotImplemented("unknown query language");
}
}
CorpusReader::EntryIterator CorpusReader::runXPath(QString const &query) const
{
//throw NotImplemented(typeid(*this).name(), "XQuery functionality");
return EntryIterator(new FilterIter(*this, getBegin(), getEnd(), query));
}
CorpusReader::EntryIterator CorpusReader::runXQuery(QString const &) const
{
throw NotImplemented(typeid(*this).name(), "XQuery functionality");
}
CorpusReader::FilterIter::FilterIter(CorpusReader const &corpus,
EntryIterator itr, EntryIterator end, QString const &query)
:
d_corpus(corpus),
d_itr(itr),
d_end(end),
d_query(query.toUtf8())
{
next();
}
QString CorpusReader::FilterIter::current() const
{
return d_file;
}
bool CorpusReader::FilterIter::equals(IterImpl const &itr) const
{
try {
// TODO fix me to be more like isEqual instead of hasNext.
return d_itr == d_end
&& d_buffer.size() == 0;
} catch (std::bad_cast const &e) {
return false;
}
}
void CorpusReader::FilterIter::next()
{
if (!d_buffer.isEmpty())
d_buffer.dequeue();
while (d_buffer.isEmpty() && d_itr != d_end)
{
d_file = *d_itr;
parseFile(d_file);
++d_itr;
}
}
QString CorpusReader::FilterIter::contents(CorpusReader const &rdr) const
{
return d_buffer.isEmpty()
? QString()
: d_buffer.head();
}
void CorpusReader::FilterIter::parseFile(QString const &file)
{
QString xml(d_corpus.read(file));
QByteArray xmlData(xml.toUtf8());
xmlDocPtr doc = xmlParseMemory(xmlData.constData(), xmlData.size());
if (!doc)
{
qWarning() << "XPathMapper::run: could not parse XML data: " << *d_itr;
return;
}
// Parse XPath query
xmlXPathContextPtr ctx = xmlXPathNewContext(doc);
if (!ctx)
{
xmlFreeDoc(doc);
qWarning() << "XPathMapper::run: could not construct XPath context from document: " << *d_itr;
return;
}
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(
reinterpret_cast<xmlChar const *>(d_query.constData()), ctx);
if (!xpathObj)
{
xmlXPathFreeContext(ctx);
xmlFreeDoc(doc);
throw Error("XPathMapper::run: could not evaluate XPath expression.");
}
if (xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0)
{
for (int i = 0; i < xpathObj->nodesetval->nodeNr; ++i)
{
xmlChar *str = xmlNodeListGetString(doc, xpathObj->nodesetval->nodeTab[i]->children, 1);
QString value(QString::fromUtf8(reinterpret_cast<const char *>(str)));
xmlFree(str);
if (value.trimmed().isEmpty())
d_buffer.enqueue(QString());
else
d_buffer.enqueue(value);
}
}
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(ctx);
xmlFreeDoc(doc);
}
}
<|endoftext|> |
<commit_before>68fbccf4-2fa5-11e5-97aa-00012e3d3f12<commit_msg>68fe3df4-2fa5-11e5-be2c-00012e3d3f12<commit_after>68fe3df4-2fa5-11e5-be2c-00012e3d3f12<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <stack>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
using namespace std;
/*
* The function returns directories found in directory.
* First parameter is path where you want to find directories.
* You can also use double slashes like this ...../dir/dir//dir. Not reomanded!
*/
vector<string> getDirs(string dirPath)
{
// Converting path to const char* because the function opendir is programmed in c
// and c methods parameters accepts only const char* so I must convert it.
const char* DIR_PATH = dirPath.c_str();
// Declaration of dynamic array that contains found directories by path.
vector<string> directories;
// Call a function to try to open the dir by path.
// If it doesnt exists the function will return segmentation error.
DIR *dir = opendir(DIR_PATH);
// Then try to read the dir
struct dirent *entry = readdir(dir);
// While dir has a directory.
while (entry != NULL)
{
// If type of stream is directory.
if (entry->d_type == DT_DIR) {
// If the "directory" name is not ".." or ".".
if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {
} else {
// push the actual dir path PLUS actual directory to the dynamic array.
directories.push_back(dirPath + "/" + entry->d_name);
}
}
entry = readdir(dir);
}
// Close the dir.
closedir(dir);
return directories;
}
vector<string> getFiles(string dirPath)
{
// Converting path to const char* because the function opendir is programmed in c
// and c methods parameters accepts only const char* so I must convert it.
const char* DIR_PATH = dirPath.c_str();
// Declaration of dynamic array that contains found directories by path.
vector<string> files;
// Call a function to try to open the dir by path.
// If it doesnt exists the function will return segmentation error.
DIR *dir = opendir(DIR_PATH);
// Then try to read the dir
struct dirent *entry = readdir(dir);
// While dir has a directory.
while (entry != NULL)
{
// If type of stream is directory.
if (entry->d_type != DT_DIR) {
// If the "directory" name is not ".." or ".".
if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {
} else {
// push the actual dir path PLUS actual directory to the dynamic array.
files.push_back(entry->d_name);
}
}
entry = readdir(dir);
}
// Close the dir.
closedir(dir);
return files;
}
int main(void)
{
// A root path where you want to start searching.
// User will specify (UWS).
string searchedDir = "/home/simon/Plocha/Simon/Data/Pokus";
// UWS
string searchedFile = "VEPR.TXT";
stack<string> actDir;
actDir.push(searchedDir);
string actSearchedDir;
vector<string> dirFound;
vector<string> fileFound;
int dirCount = 0;
while(actDir.size() > 0) {
actSearchedDir = actDir.top();actDir.pop();
cout << actSearchedDir << endl;
dirFound = getDirs(actSearchedDir.c_str());
fileFound = getFiles(actSearchedDir.c_str());
for(unsigned j = 0; j < fileFound.size(); j++) {
cout << "Soubor: " << fileFound.at(j) << endl;
cout << "POROVNAVAM: " << fileFound.at(j) << " a " << searchedFile << endl;
if(fileFound.at(j) == searchedFile) {
cout << "Soubor nalezen ve slozce " << actSearchedDir << "." << endl;
cout << "Soubor se tedy nachází v" << actSearchedDir << "/" << searchedFile << endl;
return 0;
}
}
for(unsigned i = 0; i < dirFound.size(); i++) {
if(!dirFound.empty()) {
actDir.push(dirFound.at(i));
} else {
break;
}
}
dirCount++;
}
cout << "Bylo nalezeno celkem " << dirCount-1 << " složek";
return 0;
}
<commit_msg>Komplet<commit_after>#include <iostream>
#include <vector>
#include <stack>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/timeb.h>
using namespace std;
/*
* The function returns directories found in directory.
* First parameter is path where you want to find directories.
* You can also use double slashes like this ...../dir/dir//dir. Not reomanded!
*/
vector<string> getDirs(string dirPath)
{
// Converting path to const char* because the function opendir is programmed in c
// and c methods parameters accepts only const char* so I must convert it.
const char* DIR_PATH = dirPath.c_str();
// Declaration of dynamic array that contains found directories by path.
vector<string> directories;
// Call a function to try to open the dir by path.
// If it doesnt exists the function will return segmentation error.
DIR *dir = opendir(DIR_PATH);
// Then try to read the dir
struct dirent *entry = readdir(dir);
// While dir has a directory.
while (entry != NULL)
{
// If type of stream is directory.
if (entry->d_type == DT_DIR) {
// If the "directory" name is not ".." or ".".
if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {
} else {
// push the actual dir path PLUS actual directory to the dynamic array.
directories.push_back(dirPath + "/" + entry->d_name);
}
}
entry = readdir(dir);
}
// Close the dir.
closedir(dir);
return directories;
}
vector<string> getFiles(string dirPath)
{
// Converting path to const char* because the function opendir is programmed in c
// and c methods parameters accepts only const char* so I must convert it.
const char* DIR_PATH = dirPath.c_str();
// Declaration of dynamic array that contains found directories by path.
vector<string> files;
// Call a function to try to open the dir by path.
// If it doesnt exists the function will return segmentation error.
DIR *dir = opendir(DIR_PATH);
// Then try to read the dir
struct dirent *entry = readdir(dir);
// While dir has a directory.
while (entry != NULL)
{
// If type of stream is directory.
if (entry->d_type != DT_DIR) {
// If the "directory" name is not ".." or ".".
if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {
} else {
// push the actual dir path PLUS actual directory to the dynamic array.
files.push_back(entry->d_name);
}
}
entry = readdir(dir);
}
// Close the dir.
closedir(dir);
return files;
}
void getFoundMessage(string actSearchedDir, string fileName) {
cout << "Soubor nalezen ve slozce " << actSearchedDir << "." << endl;
cout << "Soubor se tedy nachází v " << actSearchedDir << "/" << fileName << endl;
}
long getCurrentTime() {
timeb timebstr;
ftime( &timebstr );
return (long)(timebstr.time)*1000 + timebstr.millitm;
}
int main(void)
{
// A root path where you want to start searching.
// User will specify (UWS).
// For example: "/home/simon/Plocha/Simon/Data/Pokus" if it exists of course
string searchedDir;
// UWS
// For example: "VEPR.TXT"
string searchedFile;
// File is/isnt exactly matching with name.
bool exactMatch = false;
string strExactMath;
cout << "Zadej adresář, ve kterém chceš hledat: ";
cin >> searchedDir;
cout << "Budu hledat ve složce: " << searchedDir << endl;
cout << "Zadej soubor, který chceš hledat: ";
cin >> searchedFile;
cout << "Hledám soubor: " << searchedFile << endl;
while(true) {
cout << "Musí se soubor shodovat přesně? (y/n): ";
cin >> strExactMath;
if(!strExactMath.empty()) {
if(strExactMath == "y" || strExactMath == "n") {
if(strExactMath == "y") {
exactMatch = true;
}
break;
} else {
cout << "Povolené odpovědi jsou pouze y nebo n!";
}
} else {
cout << "Nic jsi nezadal!" << endl;
return 1;
}
}
bool allFiles = true;
string strAllFiles;
while(true) {
cout << "Přejete si hledat všechny soubory? (y/n): ";
cin >> strAllFiles;
if(!strAllFiles.empty()) {
if(strAllFiles == "y" || strAllFiles == "n") {
if(strAllFiles == "n") {
allFiles = false;
}
break;
} else {
cout << "Povolené odpovědi jsou pouze y, nebo n!";
}
} else {
cout << "Nic jsi nezadal!" << endl;
return 1;
}
}
long startTime = getCurrentTime();
stack<string> actDir;
actDir.push(searchedDir);
string actSearchedDir;
vector<string> dirFound;
vector<string> fileFound;
vector<string> results;
int dirCount = 0;
while(actDir.size() > 0) {
actSearchedDir = actDir.top();actDir.pop();
cout << actSearchedDir << endl;
dirFound = getDirs(actSearchedDir.c_str());
fileFound = getFiles(actSearchedDir.c_str());
for(unsigned j = 0; j < fileFound.size(); j++) {
//cout << "Soubor: " << fileFound.at(j) << endl;
//cout << "POROVNAVAM: " << fileFound.at(j) << " a " << searchedFile << endl;
if(exactMatch) {
if(fileFound.at(j) == searchedFile) {
if(allFiles) {
results.push_back(actSearchedDir + "/" + fileFound.at(j));
} else {
getFoundMessage(actSearchedDir, fileFound.at(j));
return 0;
}
}
} else {
if(fileFound.at(j).find(searchedFile) != string::npos) {
if(allFiles) {
results.push_back(actSearchedDir + "/" + fileFound.at(j));
} else {
getFoundMessage(actSearchedDir, fileFound.at(j));
return 0;
}
}
}
}
for(unsigned i = 0; i < dirFound.size(); i++) {
if(!dirFound.empty()) {
actDir.push(dirFound.at(i));
} else {
break;
}
}
dirCount++;
}
if(allFiles) {
cout << "------------------------------" << endl;
cout << "-- Výpis nalezených souborů --" << endl;
cout << "------------------------------" << endl;
for(unsigned k = 0; k < results.size(); k++) {
cout << results.at(k) << endl;
}
}
long endTime = getCurrentTime();
cout << "Bylo nalezeno celkem " << dirCount-1 << " složek" << endl;
cout << "Hledání celkem zabralo " << int(endTime - startTime) << " milisekund." << endl;
cout << "To je asi " << double(endTime - startTime) / 1000 << " sekund." << endl;
return 0;
}
<|endoftext|> |
<commit_before>a5c3367d-327f-11e5-974d-9cf387a8033e<commit_msg>a5c97317-327f-11e5-a0bc-9cf387a8033e<commit_after>a5c97317-327f-11e5-a0bc-9cf387a8033e<|endoftext|> |
<commit_before>dd5c0621-313a-11e5-8d4b-3c15c2e10482<commit_msg>dd61cc19-313a-11e5-ba5c-3c15c2e10482<commit_after>dd61cc19-313a-11e5-ba5c-3c15c2e10482<|endoftext|> |
<commit_before>d4439976-35ca-11e5-ad99-6c40088e03e4<commit_msg>d44c8f22-35ca-11e5-991d-6c40088e03e4<commit_after>d44c8f22-35ca-11e5-991d-6c40088e03e4<|endoftext|> |
<commit_before>/*
Copyright (C) 2014 Marcus Soll
All rights reserved.
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Jolla Ltd 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 HOLDERS 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 <QDebug>
#include <QList>
#include <QTime>
#include <QString>
#include <QtAlgorithms>
#include "getscore.h"
#include "gene.h"
#include "omp.h"
// Parameters of learning
int rounds = 1000000;
int population = 32;
int children = 32;
int mutationRate = 0.1;
int redoTests = 5;
struct TestScenario {
QString player1;
QString player2;
int player;
};
QList<TestScenario> getScenarios();
int main(int argc, char *argv[])
{
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
omp_set_num_threads(omp_get_num_procs()*2);
QList<Gene> currentPopulation;
QList<TestScenario> scenatios = getScenarios();
GetScore calc;
for(int i = 0; i < population; ++i)
{
currentPopulation.append(Gene(mutationRate));
}
for(int round = 1; round <= rounds; ++round)
{
qDebug() << "Current round: " << round;
QList<Gene> newPopulation = currentPopulation;
for(int i = 0; i < children; ++i)
{
Gene children = currentPopulation[qrand()%population];
children.mutate();
newPopulation.append(children);
}
for(int testnr=0; testnr < population+children; ++testnr)
{
qDebug() << "\tGene " << testnr;
int score = 0;
newPopulation[testnr].saveFiles();
#pragma omp parallel for schedule(dynamic) private(calc) reduction(+:score)
for(int test = 0; test < scenatios.size(); ++test)
{
calc.startTest(scenatios[test].player1, scenatios[test].player2,scenatios[test].player);
while(calc.scoreCalculated()) {qDebug() << "Waiting";}
score += calc.getScore();
}
newPopulation[testnr].saveScore(score);
}
currentPopulation.clear();
qSort(newPopulation);
for(int i = 0; i < population; ++i)
{
currentPopulation.append(newPopulation[i]);
}
qDebug() << "++++++++++\nBest score: " << currentPopulation[0].getScore() << "\n++++++++++\n";
currentPopulation[0].saveFiles("./inputToHidden1.endOfRound.txt", "./hidden1ToHidden2.endOfRound.txt", "./hidden2ToOutput.endOfRound.txt");
}
currentPopulation[0].saveFiles();
qDebug() << "Finished";
}
QList<TestScenario> getScenarios()
{
QList<TestScenario> scenarios;
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Greedy AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Greedy AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Balanced AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Balanced AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Static Rule AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Static Rule AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Adaptive Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Adaptive Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Control AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Control AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Assembly AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Assembly AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
return scenarios;
}
<commit_msg>More efficiency<commit_after>/*
Copyright (C) 2014 Marcus Soll
All rights reserved.
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Jolla Ltd 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 HOLDERS 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 <QDebug>
#include <QList>
#include <QTime>
#include <QString>
#include <QtAlgorithms>
#include "getscore.h"
#include "gene.h"
#include "omp.h"
// Parameters of learning
int rounds = 1000000;
int population = 32;
int children = 32;
int mutationRate = 0.01;
int redoTests = 5;
struct TestScenario {
QString player1;
QString player2;
int player;
};
QList<TestScenario> getScenarios();
int main(int argc, char *argv[])
{
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
QList<Gene> currentPopulation;
QList<TestScenario> scenatios = getScenarios();
GetScore calc;
qDebug() << "Initializing";
for(int i = 0; i < population; ++i)
{
qDebug() << "\tGene " << i;
Gene g(mutationRate);
int score = 0;
g.saveFiles();
#pragma omp parallel for schedule(dynamic) private(calc) reduction(+:score)
for(int test = 0; test < scenatios.size(); ++test)
{
calc.startTest(scenatios[test].player1, scenatios[test].player2,scenatios[test].player);
while(calc.scoreCalculated()) {qDebug() << "Waiting";}
score += calc.getScore();
}
g.saveScore(score);
currentPopulation.append(g);
}
for(int round = 1; round <= rounds; ++round)
{
qDebug() << "Current round: " << round;
QList<Gene> newPopulation = currentPopulation;
for(int i = 0; i < children; ++i)
{
qDebug() << "\tGene " << i;
Gene children = currentPopulation[qrand()%population];
children.mutate();
int score = 0;
children.saveFiles();
#pragma omp parallel for schedule(dynamic) private(calc) reduction(+:score)
for(int test = 0; test < scenatios.size(); ++test)
{
calc.startTest(scenatios[test].player1, scenatios[test].player2,scenatios[test].player);
while(calc.scoreCalculated()) {qDebug() << "Waiting";}
score += calc.getScore();
}
children.saveScore(score);
newPopulation.append(children);
}
currentPopulation.clear();
qSort(newPopulation);
for(int i = 0; i < population; ++i)
{
currentPopulation.append(newPopulation[i]);
}
qDebug() << "++++++++++\nBest score: " << currentPopulation[0].getScore() << "\n++++++++++\n";
currentPopulation[0].saveFiles("./inputToHidden1.endOfRound.txt", "./hidden1ToHidden2.endOfRound.txt", "./hidden2ToOutput.endOfRound.txt");
}
currentPopulation[0].saveFiles();
qDebug() << "Finished";
}
QList<TestScenario> getScenarios()
{
QList<TestScenario> scenarios;
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Greedy AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Greedy AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Balanced AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Balanced AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Static Rule AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Static Rule AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Adaptive Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Adaptive Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Control AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Control AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Assembly AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Assembly AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
return scenarios;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
#include <fstream>
#include "Game/Game.h"
#include "Game/Board.h"
#include "Moves/Move.h"
#include "Players/Genetic_AI.h"
#include "Players/Human_Player.h"
#include "Players/Random_AI.h"
#include "Players/Outside_Player.h"
#include "Genes/Gene_Pool.h"
#include "Exceptions/Illegal_Move_Exception.h"
#include "Exceptions/Game_Ending_Exception.h"
#include "Utility.h"
#include "Testing.h"
void print_help();
void replay_game(const std::string& file_name, int game_number);
int find_last_id(const std::string& filename);
int main(int argc, char *argv[])
{
try
{
run_tests();
if(argc > 1)
{
if(std::string(argv[1]) == "-genepool")
{
std::string gene_pool_config_file_name;
if(argc > 2)
{
gene_pool_config_file_name = argv[2];
}
gene_pool(gene_pool_config_file_name);
}
else if(std::string(argv[1]) == "-replay")
{
if(argc > 2)
{
std::string file_name = argv[2];
int game_number = -1;
if(argc > 3)
{
game_number = std::stoi(argv[3]);
}
replay_game(file_name, game_number);
}
else
{
std::cout << "Provide a file containing a game to replay." << std::endl;
return 1;
}
}
else
{
// Use pointers since each player could be Human, Genetic, Random, etc.
std::unique_ptr<Player> white;
std::unique_ptr<Player> black;
std::unique_ptr<Player> latest;
int game_time = 0;
int moves_per_reset = 0;
int increment_time = 0;
for(int i = 1; i < argc; ++i)
{
std::string opt = argv[i];
if(opt == "-human")
{
latest.reset(new Human_Player());
}
else if(opt == "-random")
{
latest.reset(new Random_AI());
}
else if(opt == "-genetic")
{
Genetic_AI *genetic_ptr = nullptr;
std::string filename;
int id = -1;
if(i + 1 < argc)
{
filename = argv[i+1];
if(filename.front() == '-')
{
filename.clear();
}
}
if(i + 2 < argc)
{
try
{
id = std::stoi(argv[i+2]);
}
catch(const std::exception&)
{
}
}
if(filename.empty())
{
genetic_ptr = new Genetic_AI;
for(int j = 0; j < 100; ++j)
{
genetic_ptr->mutate();
}
genetic_ptr->print_genome("single_game_player.txt");
}
else
{
if(id < 0)
{
genetic_ptr = new Genetic_AI(filename, find_last_id(filename));
i += 1;
}
else
{
genetic_ptr = new Genetic_AI(filename, id);
i += 2;
}
}
latest.reset(genetic_ptr);
}
else if(opt == "-time")
{
game_time = std::stoi(argv[++i]);
}
else if(opt == "-reset_moves")
{
moves_per_reset = std::stoi(argv[++i]);
}
else if(opt == "-increment_time")
{
increment_time = std::stoi(argv[++i]);
}
else
{
throw std::runtime_error("Invalid option: " + opt);
}
if(latest)
{
if( ! white)
{
white = std::move(latest);
}
else if( ! black)
{
black = std::move(latest);
}
else
{
throw std::runtime_error("More than two players specified.");
}
}
}
std::string game_file_name = "game.pgn";
if(black)
{
play_game(*white, *black, game_time, moves_per_reset, increment_time, game_file_name);
}
else
{
auto outside = connect_to_outside(*white);
game_time = outside->get_game_time();
moves_per_reset = outside->get_reset_moves();
increment_time = outside->get_increment();
if(outside->get_ai_color() == WHITE)
{
play_game(*white, *outside, game_time, moves_per_reset, increment_time, game_file_name);
}
else
{
play_game(*outside, *white, game_time, moves_per_reset, increment_time, game_file_name);
}
}
}
}
else
{
print_help();
}
}
catch(const std::exception& e)
{
std::cerr << "\n\nERROR: " << e.what() << std::endl;
return 1;
}
return 0;
}
void print_help()
{
std::cout << "\n\nGenetic Chess" << std::endl
<< "=============" << std::endl << std::endl
<< "Options:" << std::endl
<< "\t-genepool [file name]" << std::endl
<< "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name." << std::endl << std::endl
<< "\t-replay [filename]" << std::endl
<< "\t\tStep through a PGN game file, drawing the board after each\n\t\tmove with an option to begin playing at any time." << std::endl << std::endl
<< "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP command from outside to start\nplaying." << std::endl << std::endl
<< "\t-human" << std::endl
<< "\t\tSpecify a human player for a game." << std::endl << std::endl
<< "\t-genetic [filename [number]]" << std::endl
<< "\t\tSpecify a genetic AI player for a game. Optional file name and\n\t\tID number to load an AI from a file." << std::endl << std::endl
<< "\t-random" << std::endl
<< "\t\tSpecify a player that makes random moves for a game." << std::endl << std::endl
<< "\t-time [number]" << std::endl
<< "\t\tSpecify the time each player has to play the game or to make\n\t\ta set number of moves (see -reset_moves option)." << std::endl << std::endl
<< "\t-reset_moves [number]" << std::endl
<< "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock resets to the initial time every time this\n\t\tnumber of moves is made." << std::endl << std::endl
<< "\t-increment_time [number]" << std::endl
<< "\t\tSpecify seconds to add to time after each move." << std::endl << std::endl;
}
int find_last_id(const std::string& players_file_name)
{
std::ifstream player_input(players_file_name);
std::string line;
std::vector<int> all_players;
while(std::getline(player_input, line))
{
if(String::starts_with(line, "ID:"))
{
all_players.push_back(std::stoi(String::split(line).back()));
}
}
// Filter out players with zero wins
auto games_file = players_file_name + "_games.txt";
std::ifstream games_input(games_file);
std::map<int, int> games_won;
std::map<Color, int> player_colors;
while(std::getline(games_input, line))
{
if(String::starts_with(line, "[White"))
{
player_colors[WHITE] = std::stoi(String::split(String::split(line, "\"")[1])[2]);
}
else if(String::starts_with(line, "[Black"))
{
player_colors[BLACK] = std::stoi(String::split(String::split(line, "\"")[1])[2]);
}
else if(String::starts_with(line, "[Result"))
{
auto result_string = String::split(line, "\"")[1];
if(result_string == "1-0")
{
++games_won[player_colors[WHITE]];
}
else if(result_string == "0-1")
{
++games_won[player_colors[BLACK]];
}
player_colors.clear();
}
}
int best_id = -1;
for(auto id_won : games_won)
{
if(id_won.second >= 3) // require at least 3 wins
{
best_id = id_won.first;
}
}
if(best_id == -1)
{
return all_players.back();
}
else
{
return best_id;
}
}
void replay_game(const std::string& file_name, int game_number)
{
std::ifstream ifs(file_name);
std::vector<std::string> game_headers;
std::string line;
if(game_number >= 0)
{
// fast forward to indicated game
while(std::getline(ifs, line))
{
line = String::trim_outer_whitespace(line);
if(String::starts_with(line, '['))
{
game_headers.push_back(line);
}
else
{
game_headers.clear();
}
if(String::starts_with(line, "[Round"))
{
auto number = std::stoi(String::split(line, "\"")[1]);
if(number == game_number)
{
break;
}
}
}
if( ! ifs)
{
std::cout << "No game with ID number " << game_number << " found." << std::endl;
}
for(const auto& header : game_headers)
{
std::cout << header << std::endl;
}
}
Board board;
bool game_started = false;
while( ! board.game_has_ended() && std::getline(ifs, line))
{
line = String::trim_outer_whitespace(line);
line = String::strip_block_comment(line, '{', '}');
line = String::strip_comments(line, ';');
if(line.empty())
{
if(game_started)
{
break;
}
else
{
continue;
}
}
if(line[0] == '[')
{
std::cout << line << std::endl;
continue;
}
for(const auto& s : String::split(line))
{
try
{
board.submit_move(board.get_complete_move(s));
}
catch(const Illegal_Move_Exception&)
{
std::cout << "Ignoring: " << s << std::endl;
continue;
}
catch(const Game_Ending_Exception& e)
{
std::cout << e.what() << std::endl;
}
board.ascii_draw(WHITE);
game_started = true;
std::cout << "Last move: ";
std::cout << (board.get_game_record().size() + 1)/2 << ". ";
std::cout << (board.whose_turn() == WHITE ? "... " : "");
std::cout << board.get_game_record().back() << std::endl;
if(board.game_has_ended())
{
break;
}
std::cout << "Enter \"y\" to play game from here: " << std::endl;
char response = std::cin.get();
if(std::tolower(response) == 'y')
{
play_game_with_board(Human_Player(),
Human_Player(),
0,
0,
0,
file_name + "_continued.pgn",
board);
break;
}
}
}
}
<commit_msg>Use doubles when entering clock settings on command line<commit_after>#include <iostream>
#include <memory>
#include <fstream>
#include "Game/Game.h"
#include "Game/Board.h"
#include "Moves/Move.h"
#include "Players/Genetic_AI.h"
#include "Players/Human_Player.h"
#include "Players/Random_AI.h"
#include "Players/Outside_Player.h"
#include "Genes/Gene_Pool.h"
#include "Exceptions/Illegal_Move_Exception.h"
#include "Exceptions/Game_Ending_Exception.h"
#include "Utility.h"
#include "Testing.h"
void print_help();
void replay_game(const std::string& file_name, int game_number);
int find_last_id(const std::string& filename);
int main(int argc, char *argv[])
{
try
{
run_tests();
if(argc > 1)
{
if(std::string(argv[1]) == "-genepool")
{
std::string gene_pool_config_file_name;
if(argc > 2)
{
gene_pool_config_file_name = argv[2];
}
gene_pool(gene_pool_config_file_name);
}
else if(std::string(argv[1]) == "-replay")
{
if(argc > 2)
{
std::string file_name = argv[2];
int game_number = -1;
if(argc > 3)
{
game_number = std::stoi(argv[3]);
}
replay_game(file_name, game_number);
}
else
{
std::cout << "Provide a file containing a game to replay." << std::endl;
return 1;
}
}
else
{
// Use pointers since each player could be Human, Genetic, Random, etc.
std::unique_ptr<Player> white;
std::unique_ptr<Player> black;
std::unique_ptr<Player> latest;
double game_time = 0;
int moves_per_reset = 0;
double increment_time = 0;
for(int i = 1; i < argc; ++i)
{
std::string opt = argv[i];
if(opt == "-human")
{
latest.reset(new Human_Player());
}
else if(opt == "-random")
{
latest.reset(new Random_AI());
}
else if(opt == "-genetic")
{
Genetic_AI *genetic_ptr = nullptr;
std::string filename;
int id = -1;
if(i + 1 < argc)
{
filename = argv[i+1];
if(filename.front() == '-')
{
filename.clear();
}
}
if(i + 2 < argc)
{
try
{
id = std::stoi(argv[i+2]);
}
catch(const std::exception&)
{
}
}
if(filename.empty())
{
genetic_ptr = new Genetic_AI;
for(int j = 0; j < 100; ++j)
{
genetic_ptr->mutate();
}
genetic_ptr->print_genome("single_game_player.txt");
}
else
{
if(id < 0)
{
genetic_ptr = new Genetic_AI(filename, find_last_id(filename));
i += 1;
}
else
{
genetic_ptr = new Genetic_AI(filename, id);
i += 2;
}
}
latest.reset(genetic_ptr);
}
else if(opt == "-time")
{
game_time = std::stod(argv[++i]);
}
else if(opt == "-reset_moves")
{
moves_per_reset = std::stoi(argv[++i]);
}
else if(opt == "-increment_time")
{
increment_time = std::stod(argv[++i]);
}
else
{
throw std::runtime_error("Invalid option: " + opt);
}
if(latest)
{
if( ! white)
{
white = std::move(latest);
}
else if( ! black)
{
black = std::move(latest);
}
else
{
throw std::runtime_error("More than two players specified.");
}
}
}
std::string game_file_name = "game.pgn";
if(black)
{
play_game(*white, *black, game_time, moves_per_reset, increment_time, game_file_name);
}
else
{
auto outside = connect_to_outside(*white);
game_time = outside->get_game_time();
moves_per_reset = outside->get_reset_moves();
increment_time = outside->get_increment();
if(outside->get_ai_color() == WHITE)
{
play_game(*white, *outside, game_time, moves_per_reset, increment_time, game_file_name);
}
else
{
play_game(*outside, *white, game_time, moves_per_reset, increment_time, game_file_name);
}
}
}
}
else
{
print_help();
}
}
catch(const std::exception& e)
{
std::cerr << "\n\nERROR: " << e.what() << std::endl;
return 1;
}
return 0;
}
void print_help()
{
std::cout << "\n\nGenetic Chess" << std::endl
<< "=============" << std::endl << std::endl
<< "Options:" << std::endl
<< "\t-genepool [file name]" << std::endl
<< "\t\tStart a run of a gene pool with parameters set in the given\n\t\tfile name." << std::endl << std::endl
<< "\t-replay [filename]" << std::endl
<< "\t\tStep through a PGN game file, drawing the board after each\n\t\tmove with an option to begin playing at any time." << std::endl << std::endl
<< "The following options start a game with various players. If two players are\nspecified, the first plays white and the second black. If only one player is\nspecified, the program will wait for a CECP command from outside to start\nplaying." << std::endl << std::endl
<< "\t-human" << std::endl
<< "\t\tSpecify a human player for a game." << std::endl << std::endl
<< "\t-genetic [filename [number]]" << std::endl
<< "\t\tSpecify a genetic AI player for a game. Optional file name and\n\t\tID number to load an AI from a file." << std::endl << std::endl
<< "\t-random" << std::endl
<< "\t\tSpecify a player that makes random moves for a game." << std::endl << std::endl
<< "\t-time [number]" << std::endl
<< "\t\tSpecify the time each player has to play the game or to make\n\t\ta set number of moves (see -reset_moves option)." << std::endl << std::endl
<< "\t-reset_moves [number]" << std::endl
<< "\t\tSpecify the number of moves a player must make within the time\n\t\tlimit. The clock resets to the initial time every time this\n\t\tnumber of moves is made." << std::endl << std::endl
<< "\t-increment_time [number]" << std::endl
<< "\t\tSpecify seconds to add to time after each move." << std::endl << std::endl;
}
int find_last_id(const std::string& players_file_name)
{
std::ifstream player_input(players_file_name);
std::string line;
std::vector<int> all_players;
while(std::getline(player_input, line))
{
if(String::starts_with(line, "ID:"))
{
all_players.push_back(std::stoi(String::split(line).back()));
}
}
// Filter out players with zero wins
auto games_file = players_file_name + "_games.txt";
std::ifstream games_input(games_file);
std::map<int, int> games_won;
std::map<Color, int> player_colors;
while(std::getline(games_input, line))
{
if(String::starts_with(line, "[White"))
{
player_colors[WHITE] = std::stoi(String::split(String::split(line, "\"")[1])[2]);
}
else if(String::starts_with(line, "[Black"))
{
player_colors[BLACK] = std::stoi(String::split(String::split(line, "\"")[1])[2]);
}
else if(String::starts_with(line, "[Result"))
{
auto result_string = String::split(line, "\"")[1];
if(result_string == "1-0")
{
++games_won[player_colors[WHITE]];
}
else if(result_string == "0-1")
{
++games_won[player_colors[BLACK]];
}
player_colors.clear();
}
}
int best_id = -1;
for(auto id_won : games_won)
{
if(id_won.second >= 3) // require at least 3 wins
{
best_id = id_won.first;
}
}
if(best_id == -1)
{
return all_players.back();
}
else
{
return best_id;
}
}
void replay_game(const std::string& file_name, int game_number)
{
std::ifstream ifs(file_name);
std::vector<std::string> game_headers;
std::string line;
if(game_number >= 0)
{
// fast forward to indicated game
while(std::getline(ifs, line))
{
line = String::trim_outer_whitespace(line);
if(String::starts_with(line, '['))
{
game_headers.push_back(line);
}
else
{
game_headers.clear();
}
if(String::starts_with(line, "[Round"))
{
auto number = std::stoi(String::split(line, "\"")[1]);
if(number == game_number)
{
break;
}
}
}
if( ! ifs)
{
std::cout << "No game with ID number " << game_number << " found." << std::endl;
}
for(const auto& header : game_headers)
{
std::cout << header << std::endl;
}
}
Board board;
bool game_started = false;
while( ! board.game_has_ended() && std::getline(ifs, line))
{
line = String::trim_outer_whitespace(line);
line = String::strip_block_comment(line, '{', '}');
line = String::strip_comments(line, ';');
if(line.empty())
{
if(game_started)
{
break;
}
else
{
continue;
}
}
if(line[0] == '[')
{
std::cout << line << std::endl;
continue;
}
for(const auto& s : String::split(line))
{
try
{
board.submit_move(board.get_complete_move(s));
}
catch(const Illegal_Move_Exception&)
{
std::cout << "Ignoring: " << s << std::endl;
continue;
}
catch(const Game_Ending_Exception& e)
{
std::cout << e.what() << std::endl;
}
board.ascii_draw(WHITE);
game_started = true;
std::cout << "Last move: ";
std::cout << (board.get_game_record().size() + 1)/2 << ". ";
std::cout << (board.whose_turn() == WHITE ? "... " : "");
std::cout << board.get_game_record().back() << std::endl;
if(board.game_has_ended())
{
break;
}
std::cout << "Enter \"y\" to play game from here: " << std::endl;
char response = std::cin.get();
if(std::tolower(response) == 'y')
{
play_game_with_board(Human_Player(),
Human_Player(),
0,
0,
0,
file_name + "_continued.pgn",
board);
break;
}
}
}
}
<|endoftext|> |
<commit_before>f7e39721-ad5b-11e7-aaec-ac87a332f658<commit_msg>Finished?<commit_after>f84f674a-ad5b-11e7-a4bc-ac87a332f658<|endoftext|> |
<commit_before>a672b161-2e4f-11e5-b2c1-28cfe91dbc4b<commit_msg>a679a9d4-2e4f-11e5-ab3e-28cfe91dbc4b<commit_after>a679a9d4-2e4f-11e5-ab3e-28cfe91dbc4b<|endoftext|> |
<commit_before>2f31b240-5216-11e5-9b21-6c40088e03e4<commit_msg>2f38c134-5216-11e5-b833-6c40088e03e4<commit_after>2f38c134-5216-11e5-b833-6c40088e03e4<|endoftext|> |
<commit_before>0569ed88-585b-11e5-bf03-6c40088e03e4<commit_msg>05709e7e-585b-11e5-a478-6c40088e03e4<commit_after>05709e7e-585b-11e5-a478-6c40088e03e4<|endoftext|> |
<commit_before>dda72123-ad58-11e7-a283-ac87a332f658<commit_msg>bug fix<commit_after>de1127f3-ad58-11e7-b156-ac87a332f658<|endoftext|> |
<commit_before>3b795014-2e4f-11e5-bb43-28cfe91dbc4b<commit_msg>3b8007ba-2e4f-11e5-b6c5-28cfe91dbc4b<commit_after>3b8007ba-2e4f-11e5-b6c5-28cfe91dbc4b<|endoftext|> |
<commit_before>// Copyright (c) 2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include <sys/syscall.h>
#include <unistd.h>
#include <iostream>
#include "syscallfilter.h"
enum ReadPerm {
kAllowRead,
kDenyRead,
kKillRead,
kDontRead
};
int main(int argc, char **argv) {
ReadPerm readPerm = kKillRead;
if (argc >= 2) {
std::string arg{argv[1]};
if (arg == "allow_read") {
readPerm = kAllowRead;
} else if (arg == "deny_read") {
readPerm = kDenyRead;
} else if (arg == "dont_read") {
readPerm = kDontRead;
} else {
std::cerr << "Argument must be 'allow_read' or 'deny_read'\n";
return 1;
}
}
SyscallFilter filter;
filter.allow(SYS_exit_group);
filter.allow(SYS_write);
filter.allow(SYS_fstat);
filter.allow(SYS_mmap);
if (readPerm == kAllowRead) {
filter.allow(SYS_read);
} else if (readPerm == kDenyRead) {
filter.deny(SYS_read);
}
auto err = filter.install();
if (err) {
std::cerr << "Filter returned " << err.message() << '\n';
return 1;
}
std::cout << filter.toString() << '\n';
if (readPerm != kDontRead) {
char buf = 0;
int result = read(0, &buf, 1);
if (result < 0) {
int err = errno;
std::cerr << "read() errno=" << err << '\n';
return err;
} else {
std::cerr << "read() returned " << result << std::endl;
}
}
return 0;
}
<commit_msg>Run clang-format.<commit_after>// Copyright (c) 2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include <sys/syscall.h>
#include <unistd.h>
#include <iostream>
#include "syscallfilter.h"
enum ReadPerm { kAllowRead, kDenyRead, kKillRead, kDontRead };
int main(int argc, char **argv) {
ReadPerm readPerm = kKillRead;
if (argc >= 2) {
std::string arg{argv[1]};
if (arg == "allow_read") {
readPerm = kAllowRead;
} else if (arg == "deny_read") {
readPerm = kDenyRead;
} else if (arg == "dont_read") {
readPerm = kDontRead;
} else {
std::cerr << "Argument must be 'allow_read' or 'deny_read'\n";
return 1;
}
}
SyscallFilter filter;
filter.allow(SYS_exit_group);
filter.allow(SYS_write);
filter.allow(SYS_fstat);
filter.allow(SYS_mmap);
if (readPerm == kAllowRead) {
filter.allow(SYS_read);
} else if (readPerm == kDenyRead) {
filter.deny(SYS_read);
}
auto err = filter.install();
if (err) {
std::cerr << "Filter returned " << err.message() << '\n';
return 1;
}
std::cout << filter.toString() << '\n';
if (readPerm != kDontRead) {
char buf = 0;
int result = read(0, &buf, 1);
if (result < 0) {
int err = errno;
std::cerr << "read() errno=" << err << '\n';
return err;
} else {
std::cerr << "read() returned " << result << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>6497a9d1-2e4f-11e5-a584-28cfe91dbc4b<commit_msg>649eb999-2e4f-11e5-a75a-28cfe91dbc4b<commit_after>649eb999-2e4f-11e5-a75a-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <stdio.h>
#include <openssl/evp.h>
#include <string.h>
#define BYTES 3
bool same(unsigned char md_value1[EVP_MAX_MD_SIZE], unsigned char md_value2[EVP_MAX_MD_SIZE]) {
for (int i = 0; i < BYTES; i++)
if (md_value1[i] != md_value2[i])
return false;
return true;
}
int main(int argc, char *argv[]) {
EVP_MD_CTX *mdctx;
const EVP_MD *md;
char mess1[] = "Test Message\n";
char mess2[32];
unsigned char md_value1[EVP_MAX_MD_SIZE];
unsigned char md_value2[EVP_MAX_MD_SIZE];
int md_len;
srand((unsigned int) time(NULL));
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha256");
if (!md) {
printf("Unknown message digest %s\n", argv[1]);
exit(1);
}
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, mess1, strlen(mess1));
EVP_DigestFinal_ex(mdctx, md_value1, (unsigned int *) &md_len);
EVP_MD_CTX_destroy(mdctx);
printf("Rounds to find a 3 byte hash collision \n");
for (int t = 0; t < 70; t++) {
long nonce = rand() + (rand() * 20720703);
int rounds = 0;
do {
snprintf(mess2, 32, "%lu", nonce);
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, mess2, strlen(mess2));
EVP_DigestFinal_ex(mdctx, md_value2, (unsigned int *) &md_len);
EVP_MD_CTX_destroy(mdctx);
nonce++;
rounds++;
} while (!same(md_value1, md_value2));
printf("Rounds: %d\n", rounds);
}
/* Call this once before exit. */
EVP_cleanup();
exit(0);
}<commit_msg>strong collision resistance<commit_after>#include <stdio.h>
#include <openssl/evp.h>
#include <string.h>
#include <unordered_set>
#include <string>
int main(int argc, char *argv[]) {
std::unordered_set<std::string> myset;
std::string my_value_copy;
EVP_MD_CTX *mdctx;
const EVP_MD *md;
char mess[32];
unsigned char md_value[EVP_MAX_MD_SIZE];
int md_len;
srand((unsigned int) time(NULL));
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha256");
if (!md) {
printf("Unknown message digest %s\n", argv[1]);
exit(1);
}
printf("Rounds to find a 3 byte hash collision \n");
for (int t = 0; t < 1000; t++) {
unsigned int rounds = 0;
long nonce = rand() + (rand() * 20720703);
myset.clear();
do {
snprintf(mess, 32, "%lu", nonce);
mdctx = EVP_MD_CTX_create();
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, mess, strlen(mess));
EVP_DigestFinal_ex(mdctx, md_value, (unsigned int *) &md_len);
EVP_MD_CTX_destroy(mdctx);
rounds++;
nonce++;
my_value_copy.clear();
my_value_copy += md_value[0];
my_value_copy += md_value[1];
my_value_copy += md_value[2];
if (myset.count(my_value_copy) == 1)
break;
myset.insert(my_value_copy);
} while (true);
printf("Rounds: %d\n", rounds);
}
/* Call this once before exit. */
EVP_cleanup();
exit(0);
}<|endoftext|> |
<commit_before>86aaa045-ad5b-11e7-a067-ac87a332f658<commit_msg>Backup, rebase this later<commit_after>871a8828-ad5b-11e7-bc6c-ac87a332f658<|endoftext|> |
<commit_before>a0a28b8f-2e4f-11e5-acd3-28cfe91dbc4b<commit_msg>a0acbeb3-2e4f-11e5-b107-28cfe91dbc4b<commit_after>a0acbeb3-2e4f-11e5-b107-28cfe91dbc4b<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATORS_ELLIPTIC_HH
#define DUNE_GDT_OPERATORS_ELLIPTIC_HH
#include <type_traits>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/localevaluation/elliptic.hh>
#include <dune/gdt/localoperator/codim0.hh>
#include "base.hh"
namespace Dune {
namespace GDT {
namespace Operators {
// forward, to be used in the traits
template< class DiffusionImp
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp = SourceSpaceImp
, class GridViewImp = typename SourceSpaceImp::GridViewType >
class EllipticCG;
template< class DiffusionImp
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp = SourceSpaceImp
, class GridViewImp = typename SourceSpaceImp::GridViewType >
class EllipticCGTraits
{
static_assert(std::is_base_of< Stuff::LocalizableFunctionInterface< typename DiffusionImp::EntityType
, typename DiffusionImp::DomainFieldType
, DiffusionImp::dimDomain
, typename DiffusionImp::RangeFieldType
, DiffusionImp::dimRange
, DiffusionImp::dimRangeCols >
, DiffusionImp >::value,
"DiffusionImp has to be derived from Stuff::LocalizableFunctionInterface!");
static_assert(std::is_base_of< Stuff::LA::MatrixInterface< typename MatrixImp::Traits >, MatrixImp >::value,
"MatrixImp has to be derived from Stuff::LA::MatrixInterface!");
static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value,
"SourceSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value,
"RangeSpaceImp has to be derived from SpaceInterface!");
public:
typedef EllipticCG< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > derived_type;
typedef MatrixImp MatrixType;
typedef SourceSpaceImp SourceSpaceType;
typedef RangeSpaceImp RangeSpaceType;
typedef GridViewImp GridViewType;
private:
typedef DiffusionImp DiffusionType;
public:
typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< DiffusionType > > LocalOperatorType;
private:
friend class EllipticCG< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp >;
}; // class EllipticTraits
template< class DiffusionImp
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp
, class GridViewImp >
class EllipticCG
: public Operators::AssemblableVolumeBase< EllipticCGTraits< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > >
{
public:
typedef EllipticCGTraits< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > Traits;
private:
typedef Operators::AssemblableVolumeBase< Traits > BaseType;
typedef typename Traits::DiffusionType DiffusionType;
typedef typename Traits::LocalOperatorType LocalOperatorType;
public:
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::SourceSpaceType SourceSpaceType;
typedef typename Traits::RangeSpaceType RangeSpaceType;
typedef typename Traits::GridViewType GridViewType;
using BaseType::pattern;
static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,
const SourceSpaceType& source_space,
const GridViewType& grid_view)
{
return range_space.compute_volume_pattern(grid_view, source_space);
}
EllipticCG(const DiffusionType& diffusion,
MatrixType& matrix,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space,
const GridViewType& grid_view)
: BaseType(matrix, source_space, range_space, grid_view)
, local_operator_(diffusion)
{}
EllipticCG(const DiffusionType& diffusion,
MatrixType& matrix,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space)
: BaseType(matrix, source_space, range_space)
, local_operator_(diffusion)
{}
EllipticCG(const DiffusionType& diffusion,
MatrixType& matrix,
const SourceSpaceType& source_space)
: BaseType(matrix, source_space)
, local_operator_(diffusion)
{}
private:
virtual const LocalOperatorType& local_operator() const DS_OVERRIDE DS_FINAL
{
return local_operator_;
}
const LocalOperatorType local_operator_;
}; // class EllipticCG
} // namespace Operators
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_ELLIPTIC_HH
<commit_msg>[operators.elliptic] based EllipticCG on SystemAssembler<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATORS_ELLIPTIC_HH
#define DUNE_GDT_OPERATORS_ELLIPTIC_HH
#include <type_traits>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/localevaluation/elliptic.hh>
#include <dune/gdt/localoperator/codim0.hh>
#include <dune/gdt/assembler/local/codim0.hh>
#include "base.hh"
namespace Dune {
namespace GDT {
namespace Operators {
// forward, to be used in the traits
template< class DiffusionImp
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp = SourceSpaceImp
, class GridViewImp = typename SourceSpaceImp::GridViewType >
class EllipticCG;
template< class DiffusionImp
, class MatrixImp
, class SourceSpaceImp
, class RangeSpaceImp = SourceSpaceImp
, class GridViewImp = typename SourceSpaceImp::GridViewType >
class EllipticCGTraits
{
static_assert(std::is_base_of< Stuff::LocalizableFunctionInterface< typename DiffusionImp::EntityType
, typename DiffusionImp::DomainFieldType
, DiffusionImp::dimDomain
, typename DiffusionImp::RangeFieldType
, DiffusionImp::dimRange
, DiffusionImp::dimRangeCols >
, DiffusionImp >::value,
"DiffusionImp has to be derived from Stuff::LocalizableFunctionInterface!");
static_assert(std::is_base_of< Stuff::LA::MatrixInterface< typename MatrixImp::Traits >, MatrixImp >::value,
"MatrixImp has to be derived from Stuff::LA::MatrixInterface!");
static_assert(std::is_base_of< SpaceInterface< typename SourceSpaceImp::Traits >, SourceSpaceImp >::value,
"SourceSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename RangeSpaceImp::Traits >, RangeSpaceImp >::value,
"RangeSpaceImp has to be derived from SpaceInterface!");
public:
typedef EllipticCG< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > derived_type;
typedef MatrixImp MatrixType;
typedef SourceSpaceImp SourceSpaceType;
typedef RangeSpaceImp RangeSpaceType;
typedef GridViewImp GridViewType;
private:
typedef DiffusionImp DiffusionType;
public:
typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< DiffusionType > > LocalOperatorType;
private:
friend class EllipticCG< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp >;
}; // class EllipticTraits
template< class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp >
class EllipticCG
: public Operators::MatrixBasedBase< internal::EllipticCGTraits< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > >
, public SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp >
{
typedef SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp > AssemblerBaseType;
typedef Operators::MatrixBasedBase< internal::EllipticCGTraits< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > >
OperatorBaseType;
typedef DiffusionImp DiffusionType;
typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< DiffusionType > > LocalOperatorType;
typedef LocalAssembler::Codim0Matrix< LocalOperatorType > LocalAssemblerType;
public:
typedef internal::EllipticCGTraits< DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp > Traits;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::SourceSpaceType SourceSpaceType;
typedef typename Traits::RangeSpaceType RangeSpaceType;
typedef typename Traits::GridViewType GridViewType;
using OperatorBaseType::pattern;
static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,
const SourceSpaceType& source_space,
const GridViewType& grid_view)
{
return range_space.compute_volume_pattern(grid_view, source_space);
}
EllipticCG(const DiffusionType& diffusion,
MatrixType& matrix,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space,
const GridViewType& grid_view)
: OperatorBaseType(matrix, source_space, range_space, grid_view)
, AssemblerBaseType(range_space, grid_view, source_space)
, local_operator_(diffusion)
, local_assembler_(local_operator_)
{
this->add(local_assembler_, this->matrix());
}
EllipticCG(const DiffusionType& diffusion,
MatrixType& matrix,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space)
: OperatorBaseType(matrix, source_space, range_space)
, AssemblerBaseType(range_space, source_space)
, local_operator_(diffusion)
, local_assembler_(local_operator_)
{
this->add(local_assembler_, this->matrix());
}
EllipticCG(const DiffusionType& diffusion,
MatrixType& matrix,
const SourceSpaceType& source_space)
: OperatorBaseType(matrix, source_space)
, AssemblerBaseType(source_space)
, local_operator_(diffusion)
, local_assembler_(local_operator_)
{
this->add(local_assembler_, this->matrix());
}
virtual void assemble() DS_OVERRIDE DS_FINAL
{
AssemblerBaseType::assemble();
}
private:
const LocalOperatorType local_operator_;
const LocalAssemblerType local_assembler_;
}; // class EllipticCG
} // namespace Operators
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_ELLIPTIC_HH
<|endoftext|> |
<commit_before>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <string>
#include <gtest/gtest.h>
#include <clipper.hpp>
#include "../src/infill.h"
#include "../src/utils/math.h"
#include "../src/PathOrderMonotonic.h"
#include "../src/utils/polygon.h"
#include "ReadTestPolygons.h"
#define TEST_PATHS_SVG_OUTPUT
#ifdef TEST_PATHS_SVG_OUTPUT
#include <cstdlib>
#include "../src/utils/SVG.h"
#endif //TEST_PATHS_SVG_OUTPUT
namespace cura
{
/* Fixture to allow parameterized tests.
*/
class PathOrderMonotonicTest : public testing::TestWithParam<std::tuple<std::string, AngleRadians>>
{};
inline Point startVertex(const PathOrderMonotonic<ConstPolygonRef>::Path& path)
{
return path.vertices[path.start_vertex];
}
inline Point endVertex(const PathOrderMonotonic<ConstPolygonRef>::Path& path)
{
return path.vertices[path.vertices.size() - (1 + path.start_vertex)];
}
coord_t projectPathAlongAxis(const PathOrderMonotonic<ConstPolygonRef>::Path& path, const Point& vector)
{
return dot(startVertex(path), vector);
}
coord_t projectEndAlongAxis(const PathOrderMonotonic<ConstPolygonRef>::Path& path, const Point& vector)
{
return dot(endVertex(path), vector);
}
bool rangeOverlaps(const std::pair<coord_t, coord_t>& range_b, const std::pair<coord_t, coord_t>& range_a)
{
const coord_t len_b = std::abs(range_b.first - range_b.second);
const coord_t len_a = std::abs(range_a.first - range_a.second);
const coord_t len_total = std::max({ range_b.first, range_b.second, range_a.first, range_a.second })
- std::min({ range_b.first, range_b.second, range_a.first, range_a.second });
return len_total < (len_b + len_a);
}
coord_t shortestDistance(const PathOrderMonotonic<ConstPolygonRef>::Path& path_a, const PathOrderMonotonic<ConstPolygonRef>::Path& path_b)
{
// NOTE: Assume these are more or less lines.
return std::numeric_limits<coord_t>::max(); // TODO!
}
constexpr EFillMethod pattern = EFillMethod::LINES;
constexpr bool zig_zagify = false;
constexpr bool connect_polygons = false;
constexpr coord_t line_distance = 350;
constexpr coord_t outline_offset = 0;
constexpr coord_t infill_line_width = 350;
constexpr coord_t infill_overlap = 0;
constexpr size_t infill_multiplier = 1;
constexpr coord_t z = 2;
constexpr coord_t shift = 0;
constexpr coord_t max_resolution = 10;
constexpr coord_t max_deviation = 5;
bool getInfillLines(const std::string& filename, const AngleRadians& angle, Polygons& output)
{
std::vector<Polygons> shapes;
if (!readTestPolygons(filename, shapes))
{
return false;
}
Polygons dummy_polys;
for (const auto& shape : shapes)
{
Infill infill_comp
(
pattern,
zig_zagify,
connect_polygons,
shape,
outline_offset,
infill_line_width,
line_distance,
infill_overlap,
infill_multiplier,
AngleDegrees(angle),
z,
shift,
max_resolution,
max_deviation
);
infill_comp.generate(dummy_polys, output);
}
return true;
}
#ifdef TEST_PATHS_SVG_OUTPUT
void writeDebugSVG
(
const std::string& original_filename,
const AngleRadians& angle,
const Point& monotonic_vec,
const std::vector<std::vector<PathOrderMonotonic<ConstPolygonRef>::Path>>& sections
)
{
constexpr int buff_size = 1024;
char buff[buff_size];
const size_t xx = original_filename.find_first_of('_');
std::string basename = original_filename.substr(xx, original_filename.find_last_of('.') - xx);
std::snprintf(buff, buff_size, "C:/bob/%s_%d.svg", basename.c_str(), (int) AngleDegrees(angle));
const std::string filename(buff);
AABB aabb;
for (const auto& section : sections)
{
for (const auto& path : section)
{
aabb.include(startVertex(path.vertices));
aabb.include(endVertex(path.vertices));
}
}
aabb.include(Point{0, 0});
aabb.include(monotonic_vec);
SVG svgFile(filename.c_str(), aabb);
int color_id = -1;
for (const auto& section : sections)
{
++color_id;
SVG::Color section_color{ (SVG::Color) (((int) SVG::Color::GRAY) + (color_id % 7)) };
for (const auto& path : section)
{
svgFile.writePolyline(path.vertices, section_color);
}
}
svgFile.writeArrow(Point{ 0, 0 }, monotonic_vec, SVG::Color::BLACK);
// Note: SVG writes 'itself' when the object is destroyed.
}
#endif //TEST_PATHS_SVG_OUTPUT
TEST_P(PathOrderMonotonicTest, SectionsTest)
{
const auto params = GetParam();
const double angle_radians{ std::get<1>(params) };
const auto& filename = std::get<0>(params);
Polygons polylines;
ASSERT_TRUE(getInfillLines(filename, angle_radians, polylines)) << "Input test-file could not be read, check setup.";
const Point& pt_r = polylines.begin()->at(0);
const Point& pt_s = polylines.begin()->at(1);
const double angle_from_first_line = std::atan2(pt_s.Y - pt_r.Y, pt_s.X - pt_r.X) + 0.5 * M_PI;
const Point monotonic_axis{ std::cos(angle_from_first_line) * 1000, std::sin(angle_from_first_line) * 1000 };
const Point perpendicular_axis{ turn90CCW(monotonic_axis) };
constexpr coord_t max_adjacent_distance = line_distance + 1;
PathOrderMonotonic<ConstPolygonRef> object_under_test(angle_from_first_line, max_adjacent_distance, monotonic_axis * -1000);
for (const auto& polyline : polylines)
{
object_under_test.addPolyline(polyline);
}
object_under_test.optimize();
// Collect sections:
std::vector<std::vector<PathOrderMonotonic<ConstPolygonRef>::Path>> sections;
sections.emplace_back();
coord_t last_path_mono_projection = projectPathAlongAxis(object_under_test.paths.front(), monotonic_axis);
for (const auto& path : object_under_test.paths)
{
const coord_t path_mono_projection{ projectPathAlongAxis(path, monotonic_axis) };
if (path_mono_projection < last_path_mono_projection && ! sections.back().empty())
{
sections.emplace_back();
}
sections.back().push_back(path);
last_path_mono_projection = path_mono_projection;
}
#ifdef TEST_PATHS_SVG_OUTPUT
writeDebugSVG(filename, angle_radians, monotonic_axis, sections);
#endif //TEST_PATHS_SVG_OUTPUT
// Each section that intersects another section on the monotonic axis,
// needs to --for that overlapping (sub-)section-- _not_ overlap for the perpendicular axis.
// Each section that _doesn't_ intersect another on the monotonic axis,
// the earlier section has to have a lower starting point on that axis then the later one.
size_t section_a_id = 0;
for (const auto& section_a : sections)
{
++section_a_id;
size_t section_b_id = 0;
for (const auto& section_b : sections)
{
++section_b_id;
if (section_a_id >= section_b_id)
{
continue; // <-- So section B will always be 'later' than section A.
}
// Check if the start of A is lower than the start of B, since it is ordered first.
const coord_t mono_a{ projectPathAlongAxis(section_a.front(), monotonic_axis) };
const coord_t mono_b{ projectPathAlongAxis(section_b.front(), monotonic_axis) };
EXPECT_LE(mono_a, mono_b)
<< "Section ordered before another, A's start point should be before B when ordered along the monotonic axis.";
// 'Neighbouring' lines should only overlap when projected to the perpendicular axis if they're from the same section.
// (This is technically not true in general,
// but the gap would have to be small enough for the neighbouring lines to touch; this won't really happen in practice.)
// Already tested for A start < B start in the monotonic direction,
// so assume A begins before B, so there is either no overlap, B lies 'witin' A, or B stops later than A.
auto it_a = section_a.begin();
for (auto it_b = section_b.begin(); it_b != section_b.end(); ++it_b)
{
const coord_t mono_b = projectPathAlongAxis(*it_b, monotonic_axis);
for (; it_a != section_a.end() && projectPathAlongAxis(*it_a, monotonic_axis) <= mono_b; ++it_a) {}
const std::pair<coord_t, coord_t> perp_b_range
{
projectPathAlongAxis(*it_b, perpendicular_axis),
projectEndAlongAxis(*it_b, perpendicular_axis)
};
if (it_a == section_a.end())
{
if (it_b == section_b.begin())
{
// A is wholly before B in the monotonic direction, should A and B have been merged?
it_a = std::prev(it_a); // end of section A
const std::pair<coord_t, coord_t> perp_a_range
{
projectPathAlongAxis(*it_a, perpendicular_axis),
projectEndAlongAxis(*it_a, perpendicular_axis)
};
EXPECT_FALSE(rangeOverlaps(perp_b_range, perp_a_range) && shortestDistance(*it_a, *it_b) < max_adjacent_distance)
<< "Sections A and B should have been one section, printed continuosly";
}
}
else
{
// A and B intersect in monotonic direction, check if they overlap in the perpendicular direction:
const std::pair<coord_t, coord_t> perp_a_range
{
projectPathAlongAxis(*it_a, perpendicular_axis),
projectEndAlongAxis(*it_a, perpendicular_axis)
};
EXPECT_FALSE(rangeOverlaps(perp_b_range, perp_a_range))
<< "Perpendicular range overlaps for neighbouring lines in different sections (next line of A / line in B).";
}
}
}
}
}
const std::vector<std::string> polygon_filenames =
{
"../tests/resources/polygon_concave.txt",
"../tests/resources/polygon_concave_hole.txt",
"../tests/resources/polygon_square.txt",
"../tests/resources/polygon_square_hole.txt",
"../tests/resources/polygon_triangle.txt",
"../tests/resources/polygon_two_squares.txt",
"../tests/resources/polygon_slant_gap.txt",
"../tests/resources/polygon_sawtooth.txt",
};
const std::vector<AngleRadians> angle_radians =
{
0,
0.1,
0.25 * M_PI,
1.0,
0.5 * M_PI,
0.75 * M_PI,
M_PI,
1.25 * M_PI,
4.0,
1.5 * M_PI,
1.75 * M_PI,
5.0,
(2.0 * M_PI) - 0.1
};
INSTANTIATE_TEST_CASE_P(PathOrderMonotonicTestInstantiation, PathOrderMonotonicTest,
testing::Combine(testing::ValuesIn(polygon_filenames), testing::ValuesIn(angle_radians)));
} // namespace cura
<commit_msg>Test path order monotonic: finish up big test.<commit_after>//Copyright (c) 2021 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <string>
#include <gtest/gtest.h>
#include <clipper.hpp>
#include "../src/infill.h"
#include "../src/utils/linearAlg2D.h"
#include "../src/utils/math.h"
#include "../src/PathOrderMonotonic.h"
#include "../src/utils/polygon.h"
#include "ReadTestPolygons.h"
//#define TEST_PATHS_SVG_OUTPUT
#ifdef TEST_PATHS_SVG_OUTPUT
#include <cstdlib>
#include "../src/utils/SVG.h"
#endif //TEST_PATHS_SVG_OUTPUT
namespace cura
{
/* Fixture to allow parameterized tests.
*/
class PathOrderMonotonicTest : public testing::TestWithParam<std::tuple<std::string, AngleRadians>>
{};
inline Point startVertex(const PathOrderMonotonic<ConstPolygonRef>::Path& path)
{
return path.vertices[path.start_vertex];
}
inline Point endVertex(const PathOrderMonotonic<ConstPolygonRef>::Path& path)
{
return path.vertices[path.vertices.size() - (1 + path.start_vertex)];
}
coord_t projectPathAlongAxis(const PathOrderMonotonic<ConstPolygonRef>::Path& path, const Point& vector)
{
return dot(startVertex(path), vector);
}
coord_t projectEndAlongAxis(const PathOrderMonotonic<ConstPolygonRef>::Path& path, const Point& vector)
{
return dot(endVertex(path), vector);
}
bool rangeOverlaps(const std::pair<coord_t, coord_t>& range_b, const std::pair<coord_t, coord_t>& range_a)
{
const coord_t len_b = std::abs(range_b.first - range_b.second);
const coord_t len_a = std::abs(range_a.first - range_a.second);
const coord_t len_total = std::max({ range_b.first, range_b.second, range_a.first, range_a.second })
- std::min({ range_b.first, range_b.second, range_a.first, range_a.second });
return len_total < (len_b + len_a);
}
coord_t shortestDistance
(
const PathOrderMonotonic<ConstPolygonRef>::Path& path_a,
const PathOrderMonotonic<ConstPolygonRef>::Path& path_b
)
{
// NOTE: Assume these are more or less lines.
const auto point_pair =
LinearAlg2D::getClosestConnection(startVertex(path_a), endVertex(path_a), startVertex(path_b), endVertex(path_b));
return vSize(point_pair.second - point_pair.first);
}
coord_t pathLength(const PathOrderMonotonic<ConstPolygonRef>::Path& path)
{
// NOTE: Assume these are more or less lines.
return vSize(endVertex(path) - startVertex(path));
}
constexpr EFillMethod pattern = EFillMethod::LINES;
constexpr bool zig_zagify = false;
constexpr bool connect_polygons = false;
constexpr coord_t line_distance = 350;
constexpr coord_t outline_offset = 0;
constexpr coord_t infill_line_width = 350;
constexpr coord_t infill_overlap = 0;
constexpr size_t infill_multiplier = 1;
constexpr coord_t z = 2;
constexpr coord_t shift = 0;
constexpr coord_t max_resolution = 10;
constexpr coord_t max_deviation = 5;
bool getInfillLines(const std::string& filename, const AngleRadians& angle, Polygons& output)
{
std::vector<Polygons> shapes;
if (!readTestPolygons(filename, shapes))
{
return false;
}
Polygons dummy_polys;
for (const auto& shape : shapes)
{
Infill infill_comp
(
pattern,
zig_zagify,
connect_polygons,
shape,
outline_offset,
infill_line_width,
line_distance,
infill_overlap,
infill_multiplier,
AngleDegrees(angle),
z,
shift,
max_resolution,
max_deviation
);
infill_comp.generate(dummy_polys, output);
}
return true;
}
#ifdef TEST_PATHS_SVG_OUTPUT
void writeDebugSVG
(
const std::string& original_filename,
const AngleRadians& angle,
const Point& monotonic_vec,
const std::vector<std::vector<PathOrderMonotonic<ConstPolygonRef>::Path>>& sections
)
{
constexpr int buff_size = 1024;
char buff[buff_size];
const size_t xx = original_filename.find_first_of('_');
std::string basename = original_filename.substr(xx, original_filename.find_last_of('.') - xx);
std::snprintf(buff, buff_size, "/tmp/%s_%d.svg", basename.c_str(), (int) AngleDegrees(angle));
const std::string filename(buff);
AABB aabb;
for (const auto& section : sections)
{
for (const auto& path : section)
{
aabb.include(startVertex(path.vertices));
aabb.include(endVertex(path.vertices));
}
}
aabb.include(Point{0, 0});
aabb.include(monotonic_vec);
SVG svgFile(filename.c_str(), aabb);
int color_id = -1;
for (const auto& section : sections)
{
++color_id;
SVG::Color section_color{ (SVG::Color) (((int) SVG::Color::GRAY) + (color_id % 7)) };
for (const auto& path : section)
{
svgFile.writePolyline(path.vertices, section_color);
}
}
svgFile.writeArrow(Point{ 0, 0 }, monotonic_vec, SVG::Color::BLACK);
// Note: SVG writes 'itself' when the object is destroyed.
}
#endif //TEST_PATHS_SVG_OUTPUT
TEST_P(PathOrderMonotonicTest, SectionsTest)
{
const auto params = GetParam();
const double angle_radians{ std::get<1>(params) };
const auto& filename = std::get<0>(params);
Polygons polylines;
ASSERT_TRUE(getInfillLines(filename, angle_radians, polylines)) << "Input test-file could not be read, check setup.";
const Point& pt_r = polylines.begin()->at(0);
const Point& pt_s = polylines.begin()->at(1);
const double angle_from_first_line = std::atan2(pt_s.Y - pt_r.Y, pt_s.X - pt_r.X) + 0.5 * M_PI;
const Point monotonic_axis{ std::cos(angle_from_first_line) * 1000, std::sin(angle_from_first_line) * 1000 };
const Point perpendicular_axis{ turn90CCW(monotonic_axis) };
constexpr coord_t max_adjacent_distance = line_distance + 1;
PathOrderMonotonic<ConstPolygonRef> object_under_test(angle_from_first_line, max_adjacent_distance, monotonic_axis * -1000);
for (const auto& polyline : polylines)
{
object_under_test.addPolyline(polyline);
}
object_under_test.optimize();
// Collect sections:
std::vector<std::vector<PathOrderMonotonic<ConstPolygonRef>::Path>> sections;
sections.emplace_back();
coord_t last_path_mono_projection = projectPathAlongAxis(object_under_test.paths.front(), monotonic_axis);
for (const auto& path : object_under_test.paths)
{
const coord_t path_mono_projection{ projectPathAlongAxis(path, monotonic_axis) };
if (path_mono_projection < last_path_mono_projection && ! sections.back().empty())
{
sections.emplace_back();
}
sections.back().push_back(path);
last_path_mono_projection = path_mono_projection;
}
#ifdef TEST_PATHS_SVG_OUTPUT
writeDebugSVG(filename, angle_radians, monotonic_axis, sections);
#endif //TEST_PATHS_SVG_OUTPUT
std::unordered_map<std::pair<Point, Point>, size_t> split_section_counts_per_split_line;
size_t section_a_id = 0;
for (const auto& section_a : sections)
{
++section_a_id;
size_t section_b_id = 0;
for (const auto& section_b : sections)
{
++section_b_id;
if (section_a_id >= section_b_id)
{
continue; // <-- So section B will always be 'later' than section A.
}
// Check if the start of A is lower than the start of B, since it is ordered first.
const coord_t mono_a{ projectPathAlongAxis(section_a.front(), monotonic_axis) };
const coord_t mono_b{ projectPathAlongAxis(section_b.front(), monotonic_axis) };
EXPECT_LE(mono_a, mono_b)
<< "Section ordered before another, A's start point should be before B when ordered along the monotonic axis.";
// Already tested for A start < B start in the monotonic direction,
// so assume A begins before B, so there is either no overlap, B lies 'witin' A, or B stops later than A.
auto it_a = section_a.begin();
for (auto it_b = section_b.begin(); it_b != section_b.end(); ++it_b)
{
const coord_t mono_b = projectPathAlongAxis(*it_b, monotonic_axis);
for (; it_a != section_a.end() && projectPathAlongAxis(*it_a, monotonic_axis) < mono_b; ++it_a) {}
const std::pair<coord_t, coord_t> perp_b_range
{
projectPathAlongAxis(*it_b, perpendicular_axis),
projectEndAlongAxis(*it_b, perpendicular_axis)
};
if (it_a == section_a.end())
{
// A is wholly before B in the monotonic direction, test if A and B should indeed have been different sections:
if (it_b == section_b.begin())
{
it_a = std::prev(it_a); // end of section A
const std::pair<coord_t, coord_t> perp_a_range
{
projectPathAlongAxis(*it_a, perpendicular_axis),
projectEndAlongAxis(*it_a, perpendicular_axis)
};
if (rangeOverlaps(perp_b_range, perp_a_range) && shortestDistance(*it_a, *it_b) <= max_adjacent_distance)
{
// This is only wrong if there is no split, so no 3rd or more section that ends at the same line,
// so collect those lines.
// Take the longer line:
const std::pair<Point, Point> line = pathLength(*it_a) > pathLength(*it_b) ?
std::make_pair(startVertex(*it_a), endVertex(*it_a)) :
std::make_pair(startVertex(*it_b), endVertex(*it_b));
// Collect the edges of the sections that split before that line:
if (split_section_counts_per_split_line.count(line) == 0)
{
split_section_counts_per_split_line[line] = 0;
}
++split_section_counts_per_split_line[line];
}
}
else
{
break;
}
}
else
{
// A and B intersect in monotonic direction, check if they overlap in the perpendicular direction:
const std::pair<coord_t, coord_t> perp_a_range
{
projectPathAlongAxis(*it_a, perpendicular_axis),
projectEndAlongAxis(*it_a, perpendicular_axis)
};
EXPECT_FALSE(rangeOverlaps(perp_b_range, perp_a_range))
<< "Perpendicular range overlaps for neighbouring lines in different sections (next line of A / line in B).";
}
}
}
}
// If there is a line where a section ends, and only one other section begins, then they should've been 1 section to begin with:
for (const auto& line_count_pair : split_section_counts_per_split_line)
{
EXPECT_GE(line_count_pair.second, 2) << "A section was split up while it could have been printed monotonically.";
}
}
const std::vector<std::string> polygon_filenames =
{
"../tests/resources/polygon_concave.txt",
"../tests/resources/polygon_concave_hole.txt",
"../tests/resources/polygon_square.txt",
"../tests/resources/polygon_square_hole.txt",
"../tests/resources/polygon_triangle.txt",
"../tests/resources/polygon_two_squares.txt",
"../tests/resources/polygon_slant_gap.txt",
"../tests/resources/polygon_sawtooth.txt",
};
const std::vector<AngleRadians> angle_radians =
{
0,
0.1,
0.25 * M_PI,
1.0,
0.5 * M_PI,
0.75 * M_PI,
M_PI,
1.25 * M_PI,
4.0,
1.5 * M_PI,
1.75 * M_PI,
5.0,
(2.0 * M_PI) - 0.1
};
INSTANTIATE_TEST_CASE_P(PathOrderMonotonicTestInstantiation, PathOrderMonotonicTest,
testing::Combine(testing::ValuesIn(polygon_filenames), testing::ValuesIn(angle_radians)));
} // namespace cura
<|endoftext|> |
<commit_before>/*
* Copyright © 2012-2013 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <fstream>
#include "xit-server-test.h"
#include "helpers.h"
#define TEST_TIMEOUT 10
void XITServerTest::SetUpEventListener() {
failed = false;
synchronized = false;
testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners();
listeners.Append(this);
}
void XITServerTest::SetUpConfigAndLog() {
}
void XITServerTest::SetUp() {
SetUpEventListener();
SetUpConfigAndLog();
StartServer();
}
::Display* XITServerTest::Display() {
::Display *dpy = xorg::testing::Test::Display();
if (!synchronized) {
XSynchronize(dpy, True);
synchronized = true;
}
return dpy;
}
void XITServerTest::TearDown() {
alarm(0);
if (server.Pid() != -1) {
if (!server.Terminate(3000))
server.Kill(3000);
EXPECT_EQ(server.GetState(), xorg::testing::Process::FINISHED_SUCCESS) << "Unclean server shutdown";
failed = failed || (server.GetState() != xorg::testing::Process::FINISHED_SUCCESS);
std::ifstream logfile(server.GetLogFilePath().c_str());
std::string line;
std::string bug_warn("BUG");
if (logfile.is_open()) {
while(getline(logfile, line)) {
size_t found = line.find(bug_warn);
bool error = (found != std::string::npos);
EXPECT_FALSE(error) << "BUG warning found in log" << std::endl << line << std::endl;
failed = failed || error;
break;
}
}
}
if (!Failed()) {
config.RemoveConfig();
server.RemoveLogFile();
}
testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners();
listeners.Release(this);
}
class XITServerTimeoutError : public std::runtime_error {
public:
XITServerTimeoutError(const std::string &msg) : std::runtime_error(msg) {}
};
static void sighandler_alarm(int sig)
{
static int exception = 0;
if (exception++ == 0) {
alarm(2);
FAIL() << "Test has timed out (" << __func__ << "). Adjust TEST_TIMEOUT (" << TEST_TIMEOUT << "s) if needed.";
} else {
exception = 0;
throw XITServerTimeoutError("Test has timed out. Adjust TEST_TIMEOUT if needed");
}
}
void XITServerTest::StartServer() {
/* No test takes longer than 60 seconds unless we have some envs set
that suggest we're actually debugging the server */
if (!getenv("XORG_GTEST_XSERVER_SIGSTOP") &&
!getenv("XORG_GTEST_XSERVER_KEEPALIVE")) {
alarm(TEST_TIMEOUT);
signal(SIGALRM, sighandler_alarm);
}
server.SetOption("-noreset", "");
server.SetOption("-logverbose", "12");
server.Start();
xorg::testing::Test::SetDisplayString(server.GetDisplayString());
ASSERT_NO_FATAL_FAILURE(xorg::testing::Test::SetUp());
}
bool XITServerTest::Failed() {
return failed;
}
void XITServerTest::OnTestPartResult(const ::testing::TestPartResult &test_part_result) {
failed = failed || test_part_result.failed();
}
std::string XITServer::GetNormalizedTestName() {
const ::testing::TestInfo *const test_info =
::testing::UnitTest::GetInstance()->current_test_info();
std::string testname = test_info->test_case_name();
testname += ".";
testname += test_info->name();
/* parameterized tests end with /0, replace with '.'*/
size_t found;
while ((found = testname.find_first_of("/")) != std::string::npos)
testname[found] = '.';
return testname;
}
std::string XITServer::GetDefaultLogFile() {
return std::string(LOG_BASE_PATH) + std::string("/") + GetNormalizedTestName() + std::string(".log");
}
std::string XITServer::GetDefaultConfigFile() {
return std::string(LOG_BASE_PATH) + std::string("/") + GetNormalizedTestName() + std::string(".conf");
}
<commit_msg>common: allow overriding the test DISPLAY connection<commit_after>/*
* Copyright © 2012-2013 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <fstream>
#include "xit-server-test.h"
#include "helpers.h"
#define TEST_TIMEOUT 10
void XITServerTest::SetUpEventListener() {
failed = false;
synchronized = false;
testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners();
listeners.Append(this);
}
void XITServerTest::SetUpConfigAndLog() {
}
void XITServerTest::SetUp() {
SetUpEventListener();
SetUpConfigAndLog();
StartServer();
}
::Display* XITServerTest::Display() {
::Display *dpy = xorg::testing::Test::Display();
if (!synchronized) {
XSynchronize(dpy, True);
synchronized = true;
}
return dpy;
}
void XITServerTest::TearDown() {
alarm(0);
if (server.Pid() != -1) {
if (!server.Terminate(3000))
server.Kill(3000);
EXPECT_EQ(server.GetState(), xorg::testing::Process::FINISHED_SUCCESS) << "Unclean server shutdown";
failed = failed || (server.GetState() != xorg::testing::Process::FINISHED_SUCCESS);
std::ifstream logfile(server.GetLogFilePath().c_str());
std::string line;
std::string bug_warn("BUG");
if (logfile.is_open()) {
while(getline(logfile, line)) {
size_t found = line.find(bug_warn);
bool error = (found != std::string::npos);
EXPECT_FALSE(error) << "BUG warning found in log" << std::endl << line << std::endl;
failed = failed || error;
break;
}
}
}
if (!Failed()) {
config.RemoveConfig();
server.RemoveLogFile();
}
testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners();
listeners.Release(this);
}
class XITServerTimeoutError : public std::runtime_error {
public:
XITServerTimeoutError(const std::string &msg) : std::runtime_error(msg) {}
};
static void sighandler_alarm(int sig)
{
static int exception = 0;
if (exception++ == 0) {
alarm(2);
FAIL() << "Test has timed out (" << __func__ << "). Adjust TEST_TIMEOUT (" << TEST_TIMEOUT << "s) if needed.";
} else {
exception = 0;
throw XITServerTimeoutError("Test has timed out. Adjust TEST_TIMEOUT if needed");
}
}
void XITServerTest::StartServer() {
/* No test takes longer than 60 seconds unless we have some envs set
that suggest we're actually debugging the server */
if (!getenv("XORG_GTEST_XSERVER_SIGSTOP") &&
!getenv("XORG_GTEST_XSERVER_KEEPALIVE")) {
alarm(TEST_TIMEOUT);
signal(SIGALRM, sighandler_alarm);
}
server.SetOption("-noreset", "");
server.SetOption("-logverbose", "12");
server.Start();
std::string display;
const char *dpy = getenv("XORG_GTEST_XSERVER_OVERRIDE_DISPLAY");
if (dpy)
display = std::string(dpy);
else
display = server.GetDisplayString();
xorg::testing::Test::SetDisplayString(display);
ASSERT_NO_FATAL_FAILURE(xorg::testing::Test::SetUp());
}
bool XITServerTest::Failed() {
return failed;
}
void XITServerTest::OnTestPartResult(const ::testing::TestPartResult &test_part_result) {
failed = failed || test_part_result.failed();
}
std::string XITServer::GetNormalizedTestName() {
const ::testing::TestInfo *const test_info =
::testing::UnitTest::GetInstance()->current_test_info();
std::string testname = test_info->test_case_name();
testname += ".";
testname += test_info->name();
/* parameterized tests end with /0, replace with '.'*/
size_t found;
while ((found = testname.find_first_of("/")) != std::string::npos)
testname[found] = '.';
return testname;
}
std::string XITServer::GetDefaultLogFile() {
return std::string(LOG_BASE_PATH) + std::string("/") + GetNormalizedTestName() + std::string(".log");
}
std::string XITServer::GetDefaultConfigFile() {
return std::string(LOG_BASE_PATH) + std::string("/") + GetNormalizedTestName() + std::string(".conf");
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "containers/Vector.h"
TEST(vector, vectorTest) {
cuhksz::Vector<int> testVector;
testVector.push(1);
testVector.push(2);
testVector.push(3);
EXPECT_EQ(testVector.size(), 3);
testVector.erase(0);
EXPECT_EQ(testVector[0], 2);
testVector.insert(0, 1);
EXPECT_EQ(testVector[0], 1);
EXPECT_EQ(testVector.size(), 3);
testVector.insert(2, 4);
EXPECT_EQ(testVector[2], 4);
EXPECT_EQ(testVector.size(), 4);
testVector.set(2, 5);
EXPECT_EQ(testVector[2], 5);
testVector.clear();
EXPECT_TRUE(testVector.isEmpty());
//to be added range-based for loop
}
<commit_msg>improved vector_test.cpp<commit_after>#include "gtest/gtest.h"
#include "containers/Vector.h"
cuhksz::Vector<int> testVector;
TEST(vectorTest, push) {
testVector.push(1);
testVector.push(2);
testVector.push(3);
EXPECT_EQ(testVector.size(), 3);
}
TEST(vectorTest, erase) {
testVector.erase(0);
EXPECT_EQ(testVector[0], 2);
}
TEST(vectorTest, insert) {
testVector.insert(0, 1);
EXPECT_EQ(testVector[0], 1);
EXPECT_EQ(testVector.size(), 3);
testVector.insert(2, 4);
EXPECT_EQ(testVector[2], 4);
EXPECT_EQ(testVector.size(), 4);
}
TEST(vectorTest, set) {
testVector.set(2, 5);
EXPECT_EQ(testVector[2], 5);
}
TEST(vectorTest, clear) {
testVector.clear();
EXPECT_TRUE(testVector.isEmpty());
}
TEST(forDeathTest, rangeForLoop) {
EXPECT_EXIT(
for (auto x:testVector) {continue;},
testing::ExitedWithCode(0),
""
);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010-2014 Jeremy Lainé
* Contact: https://github.com/jlaine/qdjango
*
* This file is part of the QDjango 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 <QSqlDriver>
#include <QThread>
#include <QTimer>
#include "QDjango.h"
#include "QDjangoModel.h"
#include "util.h"
class Author : public QDjangoModel
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
public:
Author(QObject *parent = 0) : QDjangoModel(parent) {}
QString name() const { return m_name; }
void setName(const QString &name) { m_name = name; }
private:
QString m_name;
};
class Worker : public QObject
{
Q_OBJECT
public slots:
void doIt();
signals:
void done();
};
void Worker::doIt()
{
qDebug("DO IT!");
QDjango::database();
emit done();
}
class tst_QDjango : public QObject
{
Q_OBJECT
private slots:
void database();
void databaseTables();
void databaseThreaded();
void debugEnabled();
void debugQuery();
};
void tst_QDjango::database()
{
QCOMPARE(QDjango::database().isOpen(), false);
QVERIFY(initialiseDatabase());
QCOMPARE(QDjango::database().isOpen(), true);
}
void tst_QDjango::databaseTables()
{
QDjango::registerModel<Author>();
QSqlDatabase db = QDjango::database();
QVERIFY(db.tables().indexOf("author") == -1);
QVERIFY(QDjango::createTables());
QVERIFY(db.tables().indexOf("author") != -1);
QVERIFY(QDjango::dropTables());
QVERIFY(db.tables().indexOf("author") == -1);
}
void tst_QDjango::databaseThreaded()
{
Worker worker;
QThread workerThread;
worker.moveToThread(&workerThread);
connect(&worker, SIGNAL(done()), &workerThread, SLOT(quit()));
QTimer::singleShot(100, &worker, SLOT(doIt()));
QEventLoop loop;
QObject::connect(&workerThread, SIGNAL(finished()), &loop, SLOT(quit()));
workerThread.start();
loop.exec();
}
void tst_QDjango::debugEnabled()
{
QCOMPARE(QDjango::isDebugEnabled(), false);
QDjango::setDebugEnabled(true);
QCOMPARE(QDjango::isDebugEnabled(), true);
QDjango::setDebugEnabled(false);
QCOMPARE(QDjango::isDebugEnabled(), false);
}
void tst_QDjango::debugQuery()
{
QDjangoQuery query(QDjango::database());
QDjango::setDebugEnabled(true);
QVERIFY(!query.exec("SELECT foo"));
QDjango::setDebugEnabled(false);
}
QTEST_MAIN(tst_QDjango)
#include "tst_qdjango.moc"
<commit_msg>actually test database access from thread<commit_after>/*
* Copyright (C) 2010-2014 Jeremy Lainé
* Contact: https://github.com/jlaine/qdjango
*
* This file is part of the QDjango 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 <QSqlDriver>
#include <QThread>
#include <QTimer>
#include "QDjango.h"
#include "QDjangoModel.h"
#include "QDjangoQuerySet.h"
#include "util.h"
class Author : public QDjangoModel
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
public:
Author(QObject *parent = 0) : QDjangoModel(parent) {}
QString name() const { return m_name; }
void setName(const QString &name) { m_name = name; }
private:
QString m_name;
};
class Worker : public QObject
{
Q_OBJECT
public slots:
void doIt();
signals:
void done();
};
void Worker::doIt()
{
Author author;
author.setName("someone");
QVERIFY(author.save());
emit done();
}
class tst_QDjango : public QObject
{
Q_OBJECT
private slots:
void database();
void databaseTables();
void databaseThreaded();
void debugEnabled();
void debugQuery();
};
void tst_QDjango::database()
{
QCOMPARE(QDjango::database().isOpen(), false);
QVERIFY(initialiseDatabase());
QCOMPARE(QDjango::database().isOpen(), true);
}
void tst_QDjango::databaseTables()
{
QDjango::registerModel<Author>();
QSqlDatabase db = QDjango::database();
QVERIFY(db.tables().indexOf("author") == -1);
QVERIFY(QDjango::createTables());
QVERIFY(db.tables().indexOf("author") != -1);
QVERIFY(QDjango::dropTables());
QVERIFY(db.tables().indexOf("author") == -1);
}
void tst_QDjango::databaseThreaded()
{
QVERIFY(QDjango::createTables());
QDjangoQuerySet<Author> qs;
Worker worker;
QThread workerThread;
worker.moveToThread(&workerThread);
connect(&worker, SIGNAL(done()), &workerThread, SLOT(quit()));
QTimer::singleShot(0, &worker, SLOT(doIt()));
QEventLoop loop;
QObject::connect(&workerThread, SIGNAL(finished()), &loop, SLOT(quit()));
workerThread.start();
loop.exec();
QCOMPARE(qs.count(), 1);
QVERIFY(QDjango::dropTables());
}
void tst_QDjango::debugEnabled()
{
QCOMPARE(QDjango::isDebugEnabled(), false);
QDjango::setDebugEnabled(true);
QCOMPARE(QDjango::isDebugEnabled(), true);
QDjango::setDebugEnabled(false);
QCOMPARE(QDjango::isDebugEnabled(), false);
}
void tst_QDjango::debugQuery()
{
QDjangoQuery query(QDjango::database());
QDjango::setDebugEnabled(true);
QVERIFY(!query.exec("SELECT foo"));
QDjango::setDebugEnabled(false);
}
QTEST_MAIN(tst_QDjango)
#include "tst_qdjango.moc"
<|endoftext|> |
<commit_before><commit_msg>Add missing breaks<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_layout_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/test/test_file_util.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
#if defined(OS_WIN)
static const char kPlatformName[] = "chromium-win";
#elif defined(OS_MACOSX)
static const char kPlatformName[] = "chromium-mac";
#elif defined(OS_LINUX)
static const char kPlatformName[] = "chromium-linux";
#else
#error No known OS defined
#endif
static const char kTestCompleteCookie[] = "status";
UILayoutTest::UILayoutTest()
: initialized_for_layout_test_(false),
test_count_(0) {
}
UILayoutTest::~UILayoutTest() {
if (!temp_test_dir_.empty()) {
// The deletion might fail because HTTP server process might not been
// completely shut down yet and is still holding certain handle to it.
// To work around this problem, we try to repeat the deletion several
// times.
EXPECT_TRUE(file_util::DieFileDie(temp_test_dir_, true));
}
}
void UILayoutTest::InitializeForLayoutTest(const FilePath& test_parent_dir,
const FilePath& test_case_dir,
int port) {
FilePath src_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &src_dir);
src_dir = src_dir.AppendASCII("chrome");
src_dir = src_dir.AppendASCII("test");
src_dir = src_dir.AppendASCII("data");
src_dir = src_dir.AppendASCII("layout_tests");
src_dir = src_dir.AppendASCII("LayoutTests");
// Gets the file path to WebKit ui layout tests, that is,
// chrome/test/data/ui_tests/LayoutTests/...
// Note that we have to use our own copy of WebKit layout tests because our
// build machines do not have WebKit layout tests added.
layout_test_dir_ = src_dir.Append(test_parent_dir);
layout_test_dir_ = layout_test_dir_.Append(test_case_dir);
ASSERT_TRUE(file_util::DirectoryExists(layout_test_dir_));
// Gets the file path to rebased expected result directory for the current
// platform.
// chrome/test/data/layout_tests/LayoutTests/platform/chromium_***/...
rebase_result_dir_ = src_dir.AppendASCII("platform");
rebase_result_dir_ = rebase_result_dir_.AppendASCII(kPlatformName);
rebase_result_dir_ = rebase_result_dir_.Append(test_parent_dir);
rebase_result_dir_ = rebase_result_dir_.Append(test_case_dir);
// Generic chromium expected results. Not OS-specific. For example,
// v8-specific differences go here.
// chrome/test/data/layout_tests/LayoutTests/platform/chromium/...
rebase_result_chromium_dir_ = src_dir.AppendASCII("platform")
.AppendASCII("chromium")
.Append(test_parent_dir)
.Append(test_case_dir);
// Gets the file path to rebased expected result directory under the
// win32 platform. This is used by other non-win32 platform to use the same
// rebased expected results.
#if !defined(OS_WIN)
rebase_result_win_dir_ = src_dir.AppendASCII("platform")
.AppendASCII("chromium-win")
.Append(test_parent_dir)
.Append(test_case_dir);
#endif
// Creates the temporary directory.
ASSERT_TRUE(file_util::CreateNewTempDirectory(
FILE_PATH_LITERAL("chrome_ui_layout_tests_"), &temp_test_dir_));
// Creates the new layout test subdirectory under the temp directory.
// Note that we have to mimic the same layout test directory structure,
// like .../LayoutTests/fast/workers/.... Otherwise those layout tests
// dealing with location property, like worker-location.html, could fail.
new_layout_test_dir_ = temp_test_dir_;
new_layout_test_dir_ = new_layout_test_dir_.AppendASCII("LayoutTests");
new_layout_test_dir_ = new_layout_test_dir_.Append(test_parent_dir);
if (port == kHttpPort) {
new_http_root_dir_ = new_layout_test_dir_;
test_case_dir_ = test_case_dir;
}
new_layout_test_dir_ = new_layout_test_dir_.Append(test_case_dir);
ASSERT_TRUE(file_util::CreateDirectory(new_layout_test_dir_));
// Copy the resource subdirectory if it exists.
FilePath layout_test_resource_path(layout_test_dir_);
layout_test_resource_path =
layout_test_resource_path.AppendASCII("resources");
FilePath new_layout_test_resource_path(new_layout_test_dir_);
new_layout_test_resource_path =
new_layout_test_resource_path.AppendASCII("resources");
file_util::CopyDirectory(layout_test_resource_path,
new_layout_test_resource_path, true);
// Copies the parent resource subdirectory. This is needed in order to run
// http layout tests.
if (port == kHttpPort) {
FilePath parent_resource_path(layout_test_dir_.DirName());
parent_resource_path = parent_resource_path.AppendASCII("resources");
FilePath new_parent_resource_path(new_layout_test_dir_.DirName());
new_parent_resource_path =
new_parent_resource_path.AppendASCII("resources");
ASSERT_TRUE(file_util::CopyDirectory(
parent_resource_path, new_parent_resource_path, true));
}
// Reads the layout test controller simulation script.
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.AppendASCII("layout_tests");
path = path.AppendASCII("layout_test_controller.html");
ASSERT_TRUE(file_util::ReadFileToString(path, &layout_test_controller_));
}
void UILayoutTest::AddResourceForLayoutTest(const FilePath& parent_dir,
const FilePath& resource_name) {
FilePath root_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &root_dir);
FilePath source = root_dir.AppendASCII("chrome");
source = source.AppendASCII("test");
source = source.AppendASCII("data");
source = source.AppendASCII("layout_tests");
source = source.AppendASCII("LayoutTests");
source = source.Append(parent_dir);
source = source.Append(resource_name);
ASSERT_TRUE(file_util::PathExists(source));
FilePath dest_parent_dir = temp_test_dir_.
AppendASCII("LayoutTests").Append(parent_dir);
ASSERT_TRUE(file_util::CreateDirectory(dest_parent_dir));
FilePath dest = dest_parent_dir.Append(resource_name);
if (file_util::DirectoryExists(source)) {
ASSERT_TRUE(file_util::CopyDirectory(source, dest, true));
} else {
ASSERT_TRUE(file_util::CopyFile(source, dest));
}
}
static size_t FindInsertPosition(const std::string& html) {
size_t tag_start = html.find("<html");
if (tag_start == std::string::npos)
return 0;
size_t tag_end = html.find(">", tag_start);
if (tag_end == std::string::npos)
return 0;
return tag_end + 1;
}
void UILayoutTest::RunLayoutTest(const std::string& test_case_file_name,
int port) {
base::Time start = base::Time::Now();
SCOPED_TRACE(test_case_file_name.c_str());
ASSERT_TRUE(!layout_test_controller_.empty());
// Creates a new cookie name. We will have to use a new cookie because
// this function could be called multiple times.
std::string status_cookie(kTestCompleteCookie);
status_cookie += base::IntToString(test_count_);
test_count_++;
// Reads the layout test HTML file.
FilePath test_file_path(layout_test_dir_);
test_file_path = test_file_path.AppendASCII(test_case_file_name);
std::string test_html;
ASSERT_TRUE(file_util::ReadFileToString(test_file_path, &test_html));
// Injects the layout test controller into the test HTML.
size_t insertion_position = FindInsertPosition(test_html);
test_html.insert(insertion_position, layout_test_controller_);
ReplaceFirstSubstringAfterOffset(
&test_html, insertion_position, "%COOKIE%", status_cookie.c_str());
// Creates the new layout test HTML file.
FilePath new_test_file_path(new_layout_test_dir_);
new_test_file_path = new_test_file_path.AppendASCII(test_case_file_name);
ASSERT_TRUE(file_util::WriteFile(new_test_file_path,
&test_html.at(0),
static_cast<int>(test_html.size())));
// We expect the test case dir to be ASCII. It might be empty, so we
// can't test whether MaybeAsASCII succeeded, but the tests will fail
// loudly in that case anyway.
std::string url_path = test_case_dir_.MaybeAsASCII();
scoped_ptr<GURL> new_test_url;
if (port != kNoHttpPort)
new_test_url.reset(new GURL(
StringPrintf("http://127.0.0.1:%d/", port) +
url_path + "/" + test_case_file_name));
else
new_test_url.reset(new GURL(net::FilePathToFileURL(new_test_file_path)));
// Runs the new layout test.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(*new_test_url.get()));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), *new_test_url.get(),
status_cookie.c_str(), TestTimeouts::action_max_timeout_ms());
// Unescapes and normalizes the actual result.
std::string value = net::UnescapeURLComponent(escaped_value,
UnescapeRule::NORMAL | UnescapeRule::SPACES |
UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS);
value += "\n";
ReplaceSubstringsAfterOffset(&value, 0, "\r", "");
// Reads the expected result. First try to read from rebase directory.
// If failed, read from original directory.
std::string expected_result_value;
if (!ReadExpectedResult(rebase_result_dir_,
test_case_file_name,
&expected_result_value) &&
!ReadExpectedResult(rebase_result_chromium_dir_,
test_case_file_name,
&expected_result_value)) {
if (rebase_result_win_dir_.empty() ||
!ReadExpectedResult(rebase_result_win_dir_,
test_case_file_name,
&expected_result_value))
ReadExpectedResult(layout_test_dir_,
test_case_file_name,
&expected_result_value);
}
ASSERT_TRUE(!expected_result_value.empty());
// Normalizes the expected result.
ReplaceSubstringsAfterOffset(&expected_result_value, 0, "\r", "");
// Compares the results.
EXPECT_STREQ(expected_result_value.c_str(), value.c_str());
VLOG(1) << "Test " << test_case_file_name
<< " took " << (base::Time::Now() - start).InMilliseconds() << "ms";
}
bool UILayoutTest::ReadExpectedResult(const FilePath& result_dir_path,
const std::string test_case_file_name,
std::string* expected_result_value) {
FilePath expected_result_path(result_dir_path);
expected_result_path = expected_result_path.AppendASCII(test_case_file_name);
expected_result_path = expected_result_path.InsertBeforeExtension(
FILE_PATH_LITERAL("-expected"));
expected_result_path =
expected_result_path.ReplaceExtension(FILE_PATH_LITERAL("txt"));
return file_util::ReadFileToString(expected_result_path,
expected_result_value);
}
<commit_msg>Make ui_layout_test probe in third_party/WebKit/ prior to chrome/test/data_layout_tests<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_layout_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/test/test_file_util.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
#if defined(OS_WIN)
static const char kPlatformName[] = "chromium-win";
#elif defined(OS_MACOSX)
static const char kPlatformName[] = "chromium-mac";
#elif defined(OS_LINUX)
static const char kPlatformName[] = "chromium-linux";
#else
#error No known OS defined
#endif
static const char kTestCompleteCookie[] = "status";
UILayoutTest::UILayoutTest()
: initialized_for_layout_test_(false),
test_count_(0) {
}
UILayoutTest::~UILayoutTest() {
if (!temp_test_dir_.empty()) {
// The deletion might fail because HTTP server process might not been
// completely shut down yet and is still holding certain handle to it.
// To work around this problem, we try to repeat the deletion several
// times.
EXPECT_TRUE(file_util::DieFileDie(temp_test_dir_, true));
}
}
// Gets layout tests root. For the current git workflow, this is
// third_party/WebKit/LayoutTests
// On svn workflow (including build machines) and older git workflow, this is
// chrome/test/data/layout_tests/LayoutTests
// This function probes for the first and then fallbacks to the second.
static FilePath GetLayoutTestRoot() {
FilePath src_root;
PathService::Get(base::DIR_SOURCE_ROOT, &src_root);
FilePath webkit_layout_tests = src_root;
webkit_layout_tests = webkit_layout_tests.AppendASCII("third_party");
webkit_layout_tests = webkit_layout_tests.AppendASCII("WebKit");
webkit_layout_tests = webkit_layout_tests.AppendASCII("LayoutTests");
if (file_util::DirectoryExists(webkit_layout_tests))
return webkit_layout_tests;
FilePath chrome_layout_tests = src_root;
chrome_layout_tests = chrome_layout_tests.AppendASCII("chrome");
chrome_layout_tests = chrome_layout_tests.AppendASCII("test");
chrome_layout_tests = chrome_layout_tests.AppendASCII("data");
chrome_layout_tests = chrome_layout_tests.AppendASCII("layout_tests");
chrome_layout_tests = chrome_layout_tests.AppendASCII("LayoutTests");
return chrome_layout_tests;
}
void UILayoutTest::InitializeForLayoutTest(const FilePath& test_parent_dir,
const FilePath& test_case_dir,
int port) {
FilePath src_dir = GetLayoutTestRoot();
layout_test_dir_ = src_dir.Append(test_parent_dir);
layout_test_dir_ = layout_test_dir_.Append(test_case_dir);
ASSERT_TRUE(file_util::DirectoryExists(layout_test_dir_));
// Gets the file path to rebased expected result directory for the current
// platform.
// $LayoutTestRoot/platform/chromium_***/...
rebase_result_dir_ = src_dir.AppendASCII("platform");
rebase_result_dir_ = rebase_result_dir_.AppendASCII(kPlatformName);
rebase_result_dir_ = rebase_result_dir_.Append(test_parent_dir);
rebase_result_dir_ = rebase_result_dir_.Append(test_case_dir);
// Generic chromium expected results. Not OS-specific. For example,
// v8-specific differences go here.
// chrome/test/data/layout_tests/LayoutTests/platform/chromium/...
rebase_result_chromium_dir_ = src_dir.AppendASCII("platform")
.AppendASCII("chromium")
.Append(test_parent_dir)
.Append(test_case_dir);
// Gets the file path to rebased expected result directory under the
// win32 platform. This is used by other non-win32 platform to use the same
// rebased expected results.
#if !defined(OS_WIN)
rebase_result_win_dir_ = src_dir.AppendASCII("platform")
.AppendASCII("chromium-win")
.Append(test_parent_dir)
.Append(test_case_dir);
#endif
// Creates the temporary directory.
ASSERT_TRUE(file_util::CreateNewTempDirectory(
FILE_PATH_LITERAL("chrome_ui_layout_tests_"), &temp_test_dir_));
// Creates the new layout test subdirectory under the temp directory.
// Note that we have to mimic the same layout test directory structure,
// like .../LayoutTests/fast/workers/.... Otherwise those layout tests
// dealing with location property, like worker-location.html, could fail.
new_layout_test_dir_ = temp_test_dir_;
new_layout_test_dir_ = new_layout_test_dir_.AppendASCII("LayoutTests");
new_layout_test_dir_ = new_layout_test_dir_.Append(test_parent_dir);
if (port == kHttpPort) {
new_http_root_dir_ = new_layout_test_dir_;
test_case_dir_ = test_case_dir;
}
new_layout_test_dir_ = new_layout_test_dir_.Append(test_case_dir);
ASSERT_TRUE(file_util::CreateDirectory(new_layout_test_dir_));
// Copy the resource subdirectory if it exists.
FilePath layout_test_resource_path(layout_test_dir_);
layout_test_resource_path =
layout_test_resource_path.AppendASCII("resources");
FilePath new_layout_test_resource_path(new_layout_test_dir_);
new_layout_test_resource_path =
new_layout_test_resource_path.AppendASCII("resources");
file_util::CopyDirectory(layout_test_resource_path,
new_layout_test_resource_path, true);
// Copies the parent resource subdirectory. This is needed in order to run
// http layout tests.
if (port == kHttpPort) {
FilePath parent_resource_path(layout_test_dir_.DirName());
parent_resource_path = parent_resource_path.AppendASCII("resources");
FilePath new_parent_resource_path(new_layout_test_dir_.DirName());
new_parent_resource_path =
new_parent_resource_path.AppendASCII("resources");
ASSERT_TRUE(file_util::CopyDirectory(
parent_resource_path, new_parent_resource_path, true));
}
// Reads the layout test controller simulation script.
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.AppendASCII("layout_tests");
path = path.AppendASCII("layout_test_controller.html");
ASSERT_TRUE(file_util::ReadFileToString(path, &layout_test_controller_));
}
void UILayoutTest::AddResourceForLayoutTest(const FilePath& parent_dir,
const FilePath& resource_name) {
FilePath source = GetLayoutTestRoot();
source = source.Append(parent_dir);
source = source.Append(resource_name);
ASSERT_TRUE(file_util::PathExists(source));
FilePath dest_parent_dir = temp_test_dir_.
AppendASCII("LayoutTests").Append(parent_dir);
ASSERT_TRUE(file_util::CreateDirectory(dest_parent_dir));
FilePath dest = dest_parent_dir.Append(resource_name);
if (file_util::DirectoryExists(source)) {
ASSERT_TRUE(file_util::CopyDirectory(source, dest, true));
} else {
ASSERT_TRUE(file_util::CopyFile(source, dest));
}
}
static size_t FindInsertPosition(const std::string& html) {
size_t tag_start = html.find("<html");
if (tag_start == std::string::npos)
return 0;
size_t tag_end = html.find(">", tag_start);
if (tag_end == std::string::npos)
return 0;
return tag_end + 1;
}
void UILayoutTest::RunLayoutTest(const std::string& test_case_file_name,
int port) {
base::Time start = base::Time::Now();
SCOPED_TRACE(test_case_file_name.c_str());
ASSERT_TRUE(!layout_test_controller_.empty());
// Creates a new cookie name. We will have to use a new cookie because
// this function could be called multiple times.
std::string status_cookie(kTestCompleteCookie);
status_cookie += base::IntToString(test_count_);
test_count_++;
// Reads the layout test HTML file.
FilePath test_file_path(layout_test_dir_);
test_file_path = test_file_path.AppendASCII(test_case_file_name);
std::string test_html;
ASSERT_TRUE(file_util::ReadFileToString(test_file_path, &test_html));
// Injects the layout test controller into the test HTML.
size_t insertion_position = FindInsertPosition(test_html);
test_html.insert(insertion_position, layout_test_controller_);
ReplaceFirstSubstringAfterOffset(
&test_html, insertion_position, "%COOKIE%", status_cookie.c_str());
// Creates the new layout test HTML file.
FilePath new_test_file_path(new_layout_test_dir_);
new_test_file_path = new_test_file_path.AppendASCII(test_case_file_name);
ASSERT_TRUE(file_util::WriteFile(new_test_file_path,
&test_html.at(0),
static_cast<int>(test_html.size())));
// We expect the test case dir to be ASCII. It might be empty, so we
// can't test whether MaybeAsASCII succeeded, but the tests will fail
// loudly in that case anyway.
std::string url_path = test_case_dir_.MaybeAsASCII();
scoped_ptr<GURL> new_test_url;
if (port != kNoHttpPort)
new_test_url.reset(new GURL(
StringPrintf("http://127.0.0.1:%d/", port) +
url_path + "/" + test_case_file_name));
else
new_test_url.reset(new GURL(net::FilePathToFileURL(new_test_file_path)));
// Runs the new layout test.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(*new_test_url.get()));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), *new_test_url.get(),
status_cookie.c_str(), TestTimeouts::action_max_timeout_ms());
// Unescapes and normalizes the actual result.
std::string value = net::UnescapeURLComponent(escaped_value,
UnescapeRule::NORMAL | UnescapeRule::SPACES |
UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS);
value += "\n";
ReplaceSubstringsAfterOffset(&value, 0, "\r", "");
// Reads the expected result. First try to read from rebase directory.
// If failed, read from original directory.
std::string expected_result_value;
if (!ReadExpectedResult(rebase_result_dir_,
test_case_file_name,
&expected_result_value) &&
!ReadExpectedResult(rebase_result_chromium_dir_,
test_case_file_name,
&expected_result_value)) {
if (rebase_result_win_dir_.empty() ||
!ReadExpectedResult(rebase_result_win_dir_,
test_case_file_name,
&expected_result_value))
ReadExpectedResult(layout_test_dir_,
test_case_file_name,
&expected_result_value);
}
ASSERT_TRUE(!expected_result_value.empty());
// Normalizes the expected result.
ReplaceSubstringsAfterOffset(&expected_result_value, 0, "\r", "");
// Compares the results.
EXPECT_STREQ(expected_result_value.c_str(), value.c_str());
VLOG(1) << "Test " << test_case_file_name
<< " took " << (base::Time::Now() - start).InMilliseconds() << "ms";
}
bool UILayoutTest::ReadExpectedResult(const FilePath& result_dir_path,
const std::string test_case_file_name,
std::string* expected_result_value) {
FilePath expected_result_path(result_dir_path);
expected_result_path = expected_result_path.AppendASCII(test_case_file_name);
expected_result_path = expected_result_path.InsertBeforeExtension(
FILE_PATH_LITERAL("-expected"));
expected_result_path =
expected_result_path.ReplaceExtension(FILE_PATH_LITERAL("txt"));
return file_util::ReadFileToString(expected_result_path,
expected_result_value);
}
<|endoftext|> |
<commit_before>/*
Copyright 2002-2014 CEA LIST
This file is part of LIMA.
LIMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/************************************************************************
*
* @file SemanticRoleLabelingLoader.cpp
* @author Clémence Filmont <clemence.filmont@cea.fr>
* @date 2014--
* copyright Copyright (C) 2014 by CEA LIST
* Project mm_linguisticprocessing
*
*
***********************************************************************/
#include "SemanticRoleLabelingLoader.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
#include "common/Data/strwstrtools.h"
#include "linguisticProcessing/core/Automaton/recognizerData.h"
#include "common/MediaticData/mediaticData.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationData.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationGraph.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/LinguisticGraph.h"
#include "linguisticProcessing/core/LinguisticProcessors/LinguisticMetaData.h"
#include "linguisticProcessing/LinguisticProcessingCommon.h"
#include <utility>
#include <iostream>
#include<fstream>
using namespace std;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::LinguisticProcessing::ApplyRecognizer;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima::Common::AnnotationGraphs;
using namespace Lima::LinguisticProcessing::SemanticAnalysis;
using namespace Lima::Common::AnnotationGraphs;
namespace Lima {
namespace LinguisticProcessing {
namespace SemanticAnalysis {
SimpleFactory<MediaProcessUnit,SemanticRoleLabelingLoader> SemanticRoleLabelingFactory(SEMANTICROLELABELINGLOADER_CLASSID);
//***********************************************************************
SemanticRoleLabelingLoader::SemanticRoleLabelingLoader():
m_language(0),
m_graph("PosGraph"),
m_suffix(".conll")
{}
SemanticRoleLabelingLoader::~SemanticRoleLabelingLoader()
{
}
//***********************************************************************
void SemanticRoleLabelingLoader::init(Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, Manager* manager){
SEMANTICANALYSISLOGINIT;
m_language=manager->getInitializationParameters().media;
AnalysisLoader::init(unitConfiguration,manager);
try
{
m_graph=unitConfiguration.getParamsValueAtKey("graph");
}
catch (NoSuchParam& ) {} // keep default value
try
{
m_suffix=unitConfiguration.getParamsValueAtKey("inputSuffix");
}
catch (NoSuchParam& ) {} // keep default value
AnalysisLoader::init(unitConfiguration,manager);
}
LimaStatusCode SemanticRoleLabelingLoader::process(AnalysisContent& analysis) const{
SEMANTICANALYSISLOGINIT;
AnalysisGraph* tokenList=static_cast<AnalysisGraph*>(analysis.getData(m_graph));
if (tokenList==0) {
LERROR << "graph " << m_graph << " has not been produced: check pipeline" << LENDL;
return MISSING_DATA;
}
LinguisticGraph* resultGraph=tokenList->getGraph();
AnnotationData* annotationData = static_cast<AnnotationData*>(analysis.getData("AnnotationData"));
LimaConllTokenIdMapping* limaConllMapping= static_cast<LimaConllTokenIdMapping*>(analysis.getData("LimaConllTokenIdMapping"));
LinguisticMetaData* metadata=static_cast<LinguisticMetaData*>(analysis.getData("LinguisticMetaData"));
if (metadata == 0) {
LERROR << "no LinguisticMetaData ! abort";
return MISSING_DATA;
}
QFile file(QString::fromUtf8((metadata->getMetaData("FileName")+m_suffix).c_str()));
if (!file.open(QIODevice::ReadOnly))
qDebug() << "cannot open file" << endl;
int sentenceNb=1;
std::map <int, QString> sentences;
while (!file.atEnd()) {
QByteArray text=file.readLine();
QString textString = QString::fromUtf8(text.constData());
//One assume that the input file does not start with a blank line
if (textString.size()<3){
sentenceNb++;
}else {
QString becomingSentence=sentences[sentenceNb]+textString;
sentences[sentenceNb]= becomingSentence;
}
}
SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, analysis, tokenList);
const LimaString predicateTypeAnnotation="Predicate";
const LimaString roleTypeAnnotation="SemanticRole";
for (std::map<int,QString>::iterator it=sentences.begin(); it!=sentences.end(); ++it){
int sentenceIndex=it->first;
QString sentence=it->second;
if(cHandler.extractSemanticInformation(sentenceIndex, limaConllMapping,sentence)){
LDEBUG << "SemanticRoleLabelingLoader::process there is/are " << cHandler.m_verbalClassNb << "verbal class(es) for this sentence " << LENDL;
for (int vClassIndex=0;vClassIndex<cHandler.m_verbalClassNb;vClassIndex++){
LinguisticGraphVertex posGraphPredicateVertex=cHandler.m_verbalClasses[vClassIndex].first;
LimaString verbalClass=cHandler.m_verbalClasses[vClassIndex].second;
AnnotationGraphVertex annotPredicateVertex=annotationData->createAnnotationVertex();
annotationData->addMatching("PosGraph", posGraphPredicateVertex, "annot", annotPredicateVertex);
annotationData->annotate(annotPredicateVertex, Common::Misc::utf8stdstring2limastring(predicateTypeAnnotation.toStdString()), verbalClass);
LDEBUG << "SemanticRoleLabelingLoader::process A vertex was created for the verbal class "<< annotationData->stringAnnotation(annotPredicateVertex, "Predicate")<< LENDL;
std::vector <pair<LinguisticGraphVertex,QString>>::iterator semRoleIt;
for (semRoleIt=cHandler.m_semanticRoles[vClassIndex].begin(); semRoleIt!=cHandler.m_semanticRoles[vClassIndex].end();semRoleIt++){
LinguisticGraphVertex posGraphRoleVertex=(*semRoleIt).first;
LimaString semanticRole=(*semRoleIt).second;
AnnotationGraphVertex annotRoleVertex=annotationData->createAnnotationVertex();
annotationData->addMatching("PosGraph", posGraphRoleVertex, "annot", annotRoleVertex);
AnnotationGraphEdge roleEdge=annotationData->createAnnotationEdge(annotPredicateVertex, annotRoleVertex);
annotationData->annotate(roleEdge, Common::Misc::utf8stdstring2limastring(roleTypeAnnotation.toStdString()),semanticRole);
LDEBUG << "SemanticRoleLabelingLoader::process An edge annotated " << annotationData->stringAnnotation(roleEdge, roleTypeAnnotation)<< "was created between " << verbalClass << " and the Lima vertex " << posGraphRoleVertex << LENDL;
}
}
}
}
return SUCCESS_ID;
}
SemanticRoleLabelingLoader::ConllHandler::ConllHandler(MediaId language, AnalysisContent& analysis, LinguisticAnalysisStructure::AnalysisGraph* graph):
m_language(language),
m_analysis(analysis),
m_graph(graph),
m_descriptorSeparator("\t+"),
m_tokenSeparator("\n+"),
m_verbalClasses(),
m_semanticRoles(),
m_verbalClassNb()
{
}
SemanticRoleLabelingLoader::ConllHandler::~ConllHandler(){
delete [] m_semanticRoles;
delete [] m_verbalClasses;
}
// designed to be repeated on each sentence
bool SemanticRoleLabelingLoader::ConllHandler::extractSemanticInformation(int sentenceI, LimaConllTokenIdMapping* limaConllMapping, const QString & sent){
SEMANTICANALYSISLOGINIT;
SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, m_analysis, m_graph);
QStringList sentenceTokens=cHandler.splitSegment(sent, m_tokenSeparator);
QStringList::const_iterator tokensIterator;
QString firstSentenceToken=(*sentenceTokens.constBegin());
int descriptorsNb=cHandler.splitSegment(firstSentenceToken, m_descriptorSeparator).size();
m_verbalClassNb=descriptorsNb-11;
if (m_verbalClassNb!=0){
LDEBUG << sentenceI << " : \n" << sent << LENDL;
int classIndex=0;
m_verbalClasses=new std::pair<LinguisticGraphVertex, QString>[m_verbalClassNb];
m_semanticRoles=new std::vector<std::pair<LinguisticGraphVertex,QString>>[m_verbalClassNb];
//repeated on each token of the sentence, that is on each line
for (tokensIterator = sentenceTokens.constBegin(); tokensIterator != sentenceTokens.constEnd();
++tokensIterator){
int roleNumbers=0;
QStringList descriptors=cHandler.splitSegment((*tokensIterator),m_descriptorSeparator);
if (descriptors.size()>=10){
int conllTokenId=descriptors[0].toInt();
QString conllToken=descriptors[1];
if(descriptors[10]!="-"){
QString verbalClass=descriptors[10];
QString vClass=descriptors[10];
LinguisticGraphVertex limaTokenId=cHandler.getLimaTokenId(conllTokenId, sentenceI, limaConllMapping);
m_verbalClasses[classIndex]=make_pair(limaTokenId, vClass);
classIndex++;
}
for (int roleTargetFieldIndex=0; roleTargetFieldIndex<m_verbalClassNb;roleTargetFieldIndex++){
if (descriptors[11+roleTargetFieldIndex]!="-"){
QString semanticRoleLabel=descriptors[11+roleTargetFieldIndex];
LinguisticGraphVertex limaTokenId=cHandler.getLimaTokenId(conllTokenId, sentenceI, limaConllMapping);
LDEBUG << "The Lima token id matching the conll token id " << conllTokenId << " is " << limaTokenId<< LENDL;
std::vector<std::pair<LinguisticGraphVertex,QString>> sRoles;
m_semanticRoles[roleTargetFieldIndex].push_back(make_pair(limaTokenId,semanticRoleLabel));
roleNumbers++;
}
}
}
}
return classIndex;
}
}
QStringList SemanticRoleLabelingLoader::ConllHandler::splitSegment(const QString & segment, QRegExp separator){
QStringList segmentsSplited;
segmentsSplited =segment.split(QRegExp(separator),QString::SkipEmptyParts);
return segmentsSplited;
}
LinguisticGraphVertex SemanticRoleLabelingLoader::ConllHandler::getLimaTokenId(int conllTokenId, int sentenceI, LimaConllTokenIdMapping* limaConllMapping){
SEMANTICANALYSISLOGINIT;
std::map< int,std::map< int,LinguisticGraphVertex>>::iterator limaConllMappingIt;
limaConllMappingIt=limaConllMapping->find(sentenceI);
if (limaConllMappingIt == limaConllMapping->end()) {
LERROR << "Sentence " << sentenceI << " not found";
// TODO exit or raise an exception
}
std::map< int,LinguisticGraphVertex> limaConllId=(*limaConllMappingIt).second;
std::map< int,LinguisticGraphVertex>::iterator limaConllIdIt=limaConllId.find(conllTokenId);
if (limaConllIdIt==limaConllId.end()) {
LERROR << "Conll token id " << conllTokenId << " not found";
// TODO exit or raise an exception
}
LinguisticGraphVertex limaTokenId=limaConllIdIt->second;
return limaTokenId;
}
}
}
} // end namespace
<commit_msg>Handle the case where no lima token id match the conll one from input file<commit_after>/*
Copyright 2002-2014 CEA LIST
This file is part of LIMA.
LIMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/************************************************************************
*
* @file SemanticRoleLabelingLoader.cpp
* @author Clémence Filmont <clemence.filmont@cea.fr>
* @date 2014--
* copyright Copyright (C) 2014 by CEA LIST
* Project mm_linguisticprocessing
*
*
***********************************************************************/
#include "SemanticRoleLabelingLoader.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
#include "common/Data/strwstrtools.h"
#include "linguisticProcessing/core/Automaton/recognizerData.h"
#include "common/MediaticData/mediaticData.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationData.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationGraph.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/LinguisticGraph.h"
#include "linguisticProcessing/core/LinguisticProcessors/LinguisticMetaData.h"
#include "linguisticProcessing/LinguisticProcessingCommon.h"
#include <utility>
#include <iostream>
#include<fstream>
using namespace std;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::LinguisticProcessing::ApplyRecognizer;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima::Common::AnnotationGraphs;
using namespace Lima::LinguisticProcessing::SemanticAnalysis;
using namespace Lima::Common::AnnotationGraphs;
namespace Lima {
namespace LinguisticProcessing {
namespace SemanticAnalysis {
SimpleFactory<MediaProcessUnit,SemanticRoleLabelingLoader> SemanticRoleLabelingFactory(SEMANTICROLELABELINGLOADER_CLASSID);
//***********************************************************************
SemanticRoleLabelingLoader::SemanticRoleLabelingLoader():
m_language(0),
m_graph("PosGraph"),
m_suffix(".conll")
{}
SemanticRoleLabelingLoader::~SemanticRoleLabelingLoader()
{
}
//***********************************************************************
void SemanticRoleLabelingLoader::init(Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration, Manager* manager){
SEMANTICANALYSISLOGINIT;
m_language=manager->getInitializationParameters().media;
AnalysisLoader::init(unitConfiguration,manager);
try
{
m_graph=unitConfiguration.getParamsValueAtKey("graph");
}
catch (NoSuchParam& ) {} // keep default value
try
{
m_suffix=unitConfiguration.getParamsValueAtKey("inputSuffix");
}
catch (NoSuchParam& ) {} // keep default value
AnalysisLoader::init(unitConfiguration,manager);
}
LimaStatusCode SemanticRoleLabelingLoader::process(AnalysisContent& analysis) const{
SEMANTICANALYSISLOGINIT;
AnalysisGraph* tokenList=static_cast<AnalysisGraph*>(analysis.getData(m_graph));
if (tokenList==0) {
LERROR << "graph " << m_graph << " has not been produced: check pipeline" << LENDL;
return MISSING_DATA;
}
LinguisticGraph* resultGraph=tokenList->getGraph();
AnnotationData* annotationData = static_cast<AnnotationData*>(analysis.getData("AnnotationData"));
LimaConllTokenIdMapping* limaConllMapping= static_cast<LimaConllTokenIdMapping*>(analysis.getData("LimaConllTokenIdMapping"));
LinguisticMetaData* metadata=static_cast<LinguisticMetaData*>(analysis.getData("LinguisticMetaData"));
if (metadata == 0) {
LERROR << "no LinguisticMetaData ! abort";
return MISSING_DATA;
}
QFile file(QString::fromUtf8((metadata->getMetaData("FileName")+m_suffix).c_str()));
if (!file.open(QIODevice::ReadOnly))
qDebug() << "cannot open file" << endl;
int sentenceNb=1;
std::map <int, QString> sentences;
while (!file.atEnd()) {
QByteArray text=file.readLine();
QString textString = QString::fromUtf8(text.constData());
//One assume that the input file does not start with a blank line
if (textString.size()<3){
sentenceNb++;
}else {
QString becomingSentence=sentences[sentenceNb]+textString;
sentences[sentenceNb]= becomingSentence;
}
}
SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, analysis, tokenList);
const LimaString predicateTypeAnnotation="Predicate";
const LimaString roleTypeAnnotation="SemanticRole";
for (std::map<int,QString>::iterator it=sentences.begin(); it!=sentences.end(); ++it){
int sentenceIndex=it->first;
QString sentence=it->second;
if(cHandler.extractSemanticInformation(sentenceIndex, limaConllMapping,sentence)){
LDEBUG << "SemanticRoleLabelingLoader::process there is/are " << cHandler.m_verbalClassNb << "verbal class(es) for this sentence " << LENDL;
for (int vClassIndex=0;vClassIndex<cHandler.m_verbalClassNb;vClassIndex++){
LinguisticGraphVertex posGraphPredicateVertex=cHandler.m_verbalClasses[vClassIndex].first;
LimaString verbalClass=cHandler.m_verbalClasses[vClassIndex].second;
AnnotationGraphVertex annotPredicateVertex=annotationData->createAnnotationVertex();
annotationData->addMatching("PosGraph", posGraphPredicateVertex, "annot", annotPredicateVertex);
annotationData->annotate(annotPredicateVertex, Common::Misc::utf8stdstring2limastring(predicateTypeAnnotation.toStdString()), verbalClass);
LDEBUG << "SemanticRoleLabelingLoader::process A vertex was created for the verbal class "<< annotationData->stringAnnotation(annotPredicateVertex, "Predicate")<< LENDL;
std::vector <pair<LinguisticGraphVertex,QString>>::iterator semRoleIt;
for (semRoleIt=cHandler.m_semanticRoles[vClassIndex].begin(); semRoleIt!=cHandler.m_semanticRoles[vClassIndex].end();semRoleIt++){
LinguisticGraphVertex posGraphRoleVertex=(*semRoleIt).first;
LimaString semanticRole=(*semRoleIt).second;
AnnotationGraphVertex annotRoleVertex=annotationData->createAnnotationVertex();
annotationData->addMatching("PosGraph", posGraphRoleVertex, "annot", annotRoleVertex);
AnnotationGraphEdge roleEdge=annotationData->createAnnotationEdge(annotPredicateVertex, annotRoleVertex);
annotationData->annotate(roleEdge, Common::Misc::utf8stdstring2limastring(roleTypeAnnotation.toStdString()),semanticRole);
LDEBUG << "SemanticRoleLabelingLoader::process An edge annotated " << annotationData->stringAnnotation(roleEdge, roleTypeAnnotation)<< "was created between " << verbalClass << " and the Lima vertex " << posGraphRoleVertex << LENDL;
}
}
}
}
return SUCCESS_ID;
}
SemanticRoleLabelingLoader::ConllHandler::ConllHandler(MediaId language, AnalysisContent& analysis, LinguisticAnalysisStructure::AnalysisGraph* graph):
m_language(language),
m_analysis(analysis),
m_graph(graph),
m_descriptorSeparator("\t+"),
m_tokenSeparator("\n+"),
m_verbalClasses(),
m_semanticRoles(),
m_verbalClassNb()
{
}
SemanticRoleLabelingLoader::ConllHandler::~ConllHandler(){
delete [] m_semanticRoles;
delete [] m_verbalClasses;
}
// designed to be repeated on each sentence
bool SemanticRoleLabelingLoader::ConllHandler::extractSemanticInformation(int sentenceI, LimaConllTokenIdMapping* limaConllMapping, const QString & sent){
SEMANTICANALYSISLOGINIT;
SemanticRoleLabelingLoader::ConllHandler cHandler(m_language, m_analysis, m_graph);
QStringList sentenceTokens=cHandler.splitSegment(sent, m_tokenSeparator);
QStringList::const_iterator tokensIterator;
QString firstSentenceToken=(*sentenceTokens.constBegin());
int descriptorsNb=cHandler.splitSegment(firstSentenceToken, m_descriptorSeparator).size();
m_verbalClassNb=descriptorsNb-11;
if (m_verbalClassNb!=0){
LDEBUG << sentenceI << " : \n" << sent << LENDL;
int classIndex=0;
m_verbalClasses=new std::pair<LinguisticGraphVertex, QString>[m_verbalClassNb];
m_semanticRoles=new std::vector<std::pair<LinguisticGraphVertex,QString>>[m_verbalClassNb];
//repeated on each token of the sentence, that is on each line
for (tokensIterator = sentenceTokens.constBegin(); tokensIterator != sentenceTokens.constEnd();
++tokensIterator){
int roleNumbers=0;
QStringList descriptors=cHandler.splitSegment((*tokensIterator),m_descriptorSeparator);
if (descriptors.size()>=10){
int conllTokenId=descriptors[0].toInt();
QString conllToken=descriptors[1];
if(descriptors[10]!="-"){
QString verbalClass=descriptors[10];
QString vClass=descriptors[10];
LinguisticGraphVertex limaTokenId=cHandler.getLimaTokenId(conllTokenId, sentenceI, limaConllMapping);
m_verbalClasses[classIndex]=make_pair(limaTokenId, vClass);
classIndex++;
}
for (int roleTargetFieldIndex=0; roleTargetFieldIndex<m_verbalClassNb;roleTargetFieldIndex++){
if (descriptors[11+roleTargetFieldIndex]!="-"){
QString semanticRoleLabel=descriptors[11+roleTargetFieldIndex];
LinguisticGraphVertex limaTokenId=cHandler.getLimaTokenId(conllTokenId, sentenceI, limaConllMapping);
if(limaTokenId!=0){
LDEBUG << "SemanticRoleLabelingLoader::ConllHandler The Lima token id matching the conll token id " << conllTokenId << " is " << limaTokenId<< LENDL;
std::vector<std::pair<LinguisticGraphVertex,QString>> sRoles;
m_semanticRoles[roleTargetFieldIndex].push_back(make_pair(limaTokenId,semanticRoleLabel));
}
roleNumbers++;
}
}
}
}
return classIndex;
}
}
QStringList SemanticRoleLabelingLoader::ConllHandler::splitSegment(const QString & segment, QRegExp separator){
QStringList segmentsSplited;
segmentsSplited =segment.split(QRegExp(separator),QString::SkipEmptyParts);
return segmentsSplited;
}
LinguisticGraphVertex SemanticRoleLabelingLoader::ConllHandler::getLimaTokenId(int conllTokenId, int sentenceI, LimaConllTokenIdMapping* limaConllMapping){
SEMANTICANALYSISLOGINIT;
std::map< int,std::map< int,LinguisticGraphVertex>>::iterator limaConllMappingIt;
limaConllMappingIt=limaConllMapping->find(sentenceI);
if (limaConllMappingIt == limaConllMapping->end()) {
LERROR << "Sentence " << sentenceI << " not found";
return 0;
}
std::map< int,LinguisticGraphVertex> limaConllId=(*limaConllMappingIt).second;
std::map< int,LinguisticGraphVertex>::iterator limaConllIdIt=limaConllId.find(conllTokenId);
if (limaConllIdIt==limaConllId.end()) {
LERROR << "Conll token id " << conllTokenId << " not found";
return 0;
}
LinguisticGraphVertex limaTokenId=limaConllIdIt->second;
return limaTokenId;
}
}
}
} // end namespace
<|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2017 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* 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 "d3d11_device.h"
#include "d3d11_context.h"
#include "d3d11_renderstate.h"
#include "d3d11_resources.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////
// ID3D11Device1 interface
void WrappedID3D11Device::GetImmediateContext1(ID3D11DeviceContext1 **ppImmediateContext)
{
if(m_pDevice1 == NULL)
return;
if(ppImmediateContext)
{
m_pImmediateContext->AddRef();
*ppImmediateContext = (ID3D11DeviceContext1 *)m_pImmediateContext;
}
}
HRESULT WrappedID3D11Device::CreateDeferredContext1(UINT ContextFlags,
ID3D11DeviceContext1 **ppDeferredContext)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
if(ppDeferredContext == NULL)
return m_pDevice1->CreateDeferredContext1(ContextFlags, NULL);
ID3D11DeviceContext *defCtx = NULL;
HRESULT ret = CreateDeferredContext(ContextFlags, &defCtx);
if(SUCCEEDED(ret))
{
WrappedID3D11DeviceContext *wrapped = (WrappedID3D11DeviceContext *)defCtx;
*ppDeferredContext = (ID3D11DeviceContext1 *)wrapped;
}
else
{
SAFE_RELEASE(defCtx);
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateBlendState1(const D3D11_BLEND_DESC1 *pBlendStateDesc,
ID3D11BlendState1 **ppBlendState)
{
SERIALISE_ELEMENT_PTR(D3D11_BLEND_DESC1, Descriptor, pBlendStateDesc);
SERIALISE_ELEMENT(ResourceId, State, GetIDForResource(*ppBlendState));
if(m_State == READING)
{
ID3D11BlendState1 *ret = NULL;
HRESULT hr = E_NOINTERFACE;
if(m_pDevice1)
hr = m_pDevice1->CreateBlendState1(&Descriptor, &ret);
else
RDCERR("Replaying a D3D11.1 device without D3D11.1 available");
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: %s", ToStr(hr).c_str());
}
else
{
if(GetResourceManager()->HasWrapper(ret))
{
ret->Release();
ret = (ID3D11BlendState1 *)GetResourceManager()->GetWrapper(ret);
ret->AddRef();
GetResourceManager()->AddLiveResource(State, ret);
}
else
{
ret = new WrappedID3D11BlendState1(ret, this);
GetResourceManager()->AddLiveResource(State, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateBlendState1(const D3D11_BLEND_DESC1 *pBlendStateDesc,
ID3D11BlendState1 **ppBlendState)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
if(ppBlendState == NULL)
return m_pDevice1->CreateBlendState1(pBlendStateDesc, NULL);
ID3D11BlendState1 *real = NULL;
HRESULT ret = m_pDevice1->CreateBlendState1(pBlendStateDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
// duplicate states can be returned, if Create is called with a previous descriptor
if(GetResourceManager()->HasWrapper(real))
{
real->Release();
*ppBlendState = (ID3D11BlendState1 *)GetResourceManager()->GetWrapper(real);
(*ppBlendState)->AddRef();
return ret;
}
ID3D11BlendState1 *wrapped = new WrappedID3D11BlendState1(real, this);
CachedObjectsGarbageCollect();
{
RDCASSERT(m_CachedStateObjects.find(wrapped) == m_CachedStateObjects.end());
wrapped->AddRef();
InternalRef();
m_CachedStateObjects.insert(wrapped);
}
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_BLEND_STATE1);
Serialise_CreateBlendState1(pBlendStateDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppBlendState = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateRasterizerState1(
const D3D11_RASTERIZER_DESC1 *pRasterizerDesc, ID3D11RasterizerState1 **ppRasterizerState)
{
SERIALISE_ELEMENT_PTR(D3D11_RASTERIZER_DESC1, Descriptor, pRasterizerDesc);
SERIALISE_ELEMENT(ResourceId, State, GetIDForResource(*ppRasterizerState));
if(m_State == READING)
{
ID3D11RasterizerState1 *ret = NULL;
HRESULT hr = E_NOINTERFACE;
if(m_pDevice1)
hr = m_pDevice1->CreateRasterizerState1(&Descriptor, &ret);
else
RDCERR("Replaying a D3D11.1 device without D3D11.1 available");
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: %s", ToStr(hr).c_str());
}
else
{
if(GetResourceManager()->HasWrapper(ret))
{
ret->Release();
ret = (ID3D11RasterizerState1 *)GetResourceManager()->GetWrapper(ret);
ret->AddRef();
GetResourceManager()->AddLiveResource(State, ret);
}
else
{
ret = new WrappedID3D11RasterizerState2(ret, this);
GetResourceManager()->AddLiveResource(State, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateRasterizerState1(const D3D11_RASTERIZER_DESC1 *pRasterizerDesc,
ID3D11RasterizerState1 **ppRasterizerState)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
if(ppRasterizerState == NULL)
return m_pDevice1->CreateRasterizerState1(pRasterizerDesc, NULL);
ID3D11RasterizerState1 *real = NULL;
HRESULT ret = m_pDevice1->CreateRasterizerState1(pRasterizerDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
// duplicate states can be returned, if Create is called with a previous descriptor
if(GetResourceManager()->HasWrapper(real))
{
real->Release();
*ppRasterizerState = (ID3D11RasterizerState1 *)GetResourceManager()->GetWrapper(real);
(*ppRasterizerState)->AddRef();
return ret;
}
ID3D11RasterizerState1 *wrapped = new WrappedID3D11RasterizerState2(real, this);
CachedObjectsGarbageCollect();
{
RDCASSERT(m_CachedStateObjects.find(wrapped) == m_CachedStateObjects.end());
wrapped->AddRef();
InternalRef();
m_CachedStateObjects.insert(wrapped);
}
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_RASTER_STATE1);
Serialise_CreateRasterizerState1(pRasterizerDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppRasterizerState = wrapped;
}
return ret;
}
HRESULT WrappedID3D11Device::CreateDeviceContextState(UINT Flags,
const D3D_FEATURE_LEVEL *pFeatureLevels,
UINT FeatureLevels, UINT SDKVersion,
REFIID EmulatedInterface,
D3D_FEATURE_LEVEL *pChosenFeatureLevel,
ID3DDeviceContextState **ppContextState)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
if(ppContextState == NULL)
return m_pDevice1->CreateDeviceContextState(Flags, pFeatureLevels, FeatureLevels, SDKVersion,
EmulatedInterface, pChosenFeatureLevel, NULL);
ID3DDeviceContextState *real = NULL;
HRESULT ret = m_pDevice1->CreateDeviceContextState(Flags, pFeatureLevels, FeatureLevels, SDKVersion,
EmulatedInterface, pChosenFeatureLevel, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
WrappedID3DDeviceContextState *wrapped = new WrappedID3DDeviceContextState(real, this);
wrapped->state->CopyState(*m_pImmediateContext->GetCurrentPipelineState());
*ppContextState = wrapped;
}
return ret;
}
HRESULT WrappedID3D11Device::OpenSharedResource1(HANDLE hResource, REFIID returnedInterface,
void **ppResource)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
RDCUNIMPLEMENTED("Not wrapping OpenSharedResource1");
return m_pDevice1->OpenSharedResource1(hResource, returnedInterface, ppResource);
}
HRESULT WrappedID3D11Device::OpenSharedResourceByName(LPCWSTR lpName, DWORD dwDesiredAccess,
REFIID returnedInterface, void **ppResource)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
RDCUNIMPLEMENTED("Not wrapping OpenSharedResourceByName");
return m_pDevice1->OpenSharedResourceByName(lpName, dwDesiredAccess, returnedInterface, ppResource);
}
#undef IMPLEMENT_FUNCTION_SERIALISED
#define IMPLEMENT_FUNCTION_SERIALISED(ret, func, ...) \
template bool WrappedID3D11Device::CONCAT(Serialise_, func(ReadSerialiser &ser, __VA_ARGS__)); \
template bool WrappedID3D11Device::CONCAT(Serialise_, func(WriteSerialiser &ser, __VA_ARGS__));
SERIALISED_ID3D11DEVICE1_FUNCTIONS();<commit_msg>Change D3D11.1 device wrapping to new serialisation system<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2017 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* 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 "d3d11_device.h"
#include "d3d11_context.h"
#include "d3d11_renderstate.h"
#include "d3d11_resources.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////
// ID3D11Device1 interface
void WrappedID3D11Device::GetImmediateContext1(ID3D11DeviceContext1 **ppImmediateContext)
{
if(m_pDevice1 == NULL)
return;
if(ppImmediateContext)
{
m_pImmediateContext->AddRef();
*ppImmediateContext = (ID3D11DeviceContext1 *)m_pImmediateContext;
}
}
HRESULT WrappedID3D11Device::CreateDeferredContext1(UINT ContextFlags,
ID3D11DeviceContext1 **ppDeferredContext)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
if(ppDeferredContext == NULL)
return m_pDevice1->CreateDeferredContext1(ContextFlags, NULL);
ID3D11DeviceContext *defCtx = NULL;
HRESULT ret = CreateDeferredContext(ContextFlags, &defCtx);
if(SUCCEEDED(ret))
{
WrappedID3D11DeviceContext *wrapped = (WrappedID3D11DeviceContext *)defCtx;
*ppDeferredContext = (ID3D11DeviceContext1 *)wrapped;
}
else
{
SAFE_RELEASE(defCtx);
}
return ret;
}
template <typename SerialiserType>
bool WrappedID3D11Device::Serialise_CreateBlendState1(SerialiserType &ser,
const D3D11_BLEND_DESC1 *pBlendStateDesc,
ID3D11BlendState1 **ppBlendState)
{
SERIALISE_ELEMENT_LOCAL(Descriptor, *pBlendStateDesc);
SERIALISE_ELEMENT_LOCAL(pState, GetIDForResource(*ppBlendState));
if(IsReplayingAndReading())
{
ID3D11BlendState1 *ret = NULL;
HRESULT hr = E_NOINTERFACE;
if(m_pDevice1)
hr = m_pDevice1->CreateBlendState1(&Descriptor, &ret);
else
RDCERR("Replaying a D3D11.1 device without D3D11.1 available");
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: %s", ToStr(hr).c_str());
}
else
{
if(GetResourceManager()->HasWrapper(ret))
{
ret->Release();
ret = (ID3D11BlendState1 *)GetResourceManager()->GetWrapper(ret);
ret->AddRef();
GetResourceManager()->AddLiveResource(pState, ret);
}
else
{
ret = new WrappedID3D11BlendState1(ret, this);
GetResourceManager()->AddLiveResource(pState, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateBlendState1(const D3D11_BLEND_DESC1 *pBlendStateDesc,
ID3D11BlendState1 **ppBlendState)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
if(ppBlendState == NULL)
return m_pDevice1->CreateBlendState1(pBlendStateDesc, NULL);
ID3D11BlendState1 *real = NULL;
HRESULT ret = m_pDevice1->CreateBlendState1(pBlendStateDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
// duplicate states can be returned, if Create is called with a previous descriptor
if(GetResourceManager()->HasWrapper(real))
{
real->Release();
*ppBlendState = (ID3D11BlendState1 *)GetResourceManager()->GetWrapper(real);
(*ppBlendState)->AddRef();
return ret;
}
ID3D11BlendState1 *wrapped = new WrappedID3D11BlendState1(real, this);
CachedObjectsGarbageCollect();
{
RDCASSERT(m_CachedStateObjects.find(wrapped) == m_CachedStateObjects.end());
wrapped->AddRef();
InternalRef();
m_CachedStateObjects.insert(wrapped);
}
if(IsCaptureMode(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(D3D11Chunk::CreateBlendState1);
Serialise_CreateBlendState1(GET_SERIALISER, pBlendStateDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppBlendState = wrapped;
}
return ret;
}
template <typename SerialiserType>
bool WrappedID3D11Device::Serialise_CreateRasterizerState1(
SerialiserType &ser, const D3D11_RASTERIZER_DESC1 *pRasterizerDesc,
ID3D11RasterizerState1 **ppRasterizerState)
{
SERIALISE_ELEMENT_LOCAL(Descriptor, *pRasterizerDesc);
SERIALISE_ELEMENT_LOCAL(pState, GetIDForResource(*ppRasterizerState));
if(IsReplayingAndReading())
{
ID3D11RasterizerState1 *ret = NULL;
HRESULT hr = E_NOINTERFACE;
if(m_pDevice1)
hr = m_pDevice1->CreateRasterizerState1(&Descriptor, &ret);
else
RDCERR("Replaying a D3D11.1 device without D3D11.1 available");
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: %s", ToStr(hr).c_str());
}
else
{
if(GetResourceManager()->HasWrapper(ret))
{
ret->Release();
ret = (ID3D11RasterizerState1 *)GetResourceManager()->GetWrapper(ret);
ret->AddRef();
GetResourceManager()->AddLiveResource(pState, ret);
}
else
{
ret = new WrappedID3D11RasterizerState2(ret, this);
GetResourceManager()->AddLiveResource(pState, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateRasterizerState1(const D3D11_RASTERIZER_DESC1 *pRasterizerDesc,
ID3D11RasterizerState1 **ppRasterizerState)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
if(ppRasterizerState == NULL)
return m_pDevice1->CreateRasterizerState1(pRasterizerDesc, NULL);
ID3D11RasterizerState1 *real = NULL;
HRESULT ret = m_pDevice1->CreateRasterizerState1(pRasterizerDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
// duplicate states can be returned, if Create is called with a previous descriptor
if(GetResourceManager()->HasWrapper(real))
{
real->Release();
*ppRasterizerState = (ID3D11RasterizerState1 *)GetResourceManager()->GetWrapper(real);
(*ppRasterizerState)->AddRef();
return ret;
}
ID3D11RasterizerState1 *wrapped = new WrappedID3D11RasterizerState2(real, this);
CachedObjectsGarbageCollect();
{
RDCASSERT(m_CachedStateObjects.find(wrapped) == m_CachedStateObjects.end());
wrapped->AddRef();
InternalRef();
m_CachedStateObjects.insert(wrapped);
}
if(IsCaptureMode(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(D3D11Chunk::CreateRasterizerState1);
Serialise_CreateRasterizerState1(GET_SERIALISER, pRasterizerDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppRasterizerState = wrapped;
}
return ret;
}
HRESULT WrappedID3D11Device::CreateDeviceContextState(UINT Flags,
const D3D_FEATURE_LEVEL *pFeatureLevels,
UINT FeatureLevels, UINT SDKVersion,
REFIID EmulatedInterface,
D3D_FEATURE_LEVEL *pChosenFeatureLevel,
ID3DDeviceContextState **ppContextState)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
if(ppContextState == NULL)
return m_pDevice1->CreateDeviceContextState(Flags, pFeatureLevels, FeatureLevels, SDKVersion,
EmulatedInterface, pChosenFeatureLevel, NULL);
ID3DDeviceContextState *real = NULL;
HRESULT ret = m_pDevice1->CreateDeviceContextState(Flags, pFeatureLevels, FeatureLevels, SDKVersion,
EmulatedInterface, pChosenFeatureLevel, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
WrappedID3DDeviceContextState *wrapped = new WrappedID3DDeviceContextState(real, this);
wrapped->state->CopyState(*m_pImmediateContext->GetCurrentPipelineState());
*ppContextState = wrapped;
}
return ret;
}
HRESULT WrappedID3D11Device::OpenSharedResource1(HANDLE hResource, REFIID returnedInterface,
void **ppResource)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
RDCUNIMPLEMENTED("Not wrapping OpenSharedResource1");
return m_pDevice1->OpenSharedResource1(hResource, returnedInterface, ppResource);
}
HRESULT WrappedID3D11Device::OpenSharedResourceByName(LPCWSTR lpName, DWORD dwDesiredAccess,
REFIID returnedInterface, void **ppResource)
{
if(m_pDevice1 == NULL)
return E_NOINTERFACE;
RDCUNIMPLEMENTED("Not wrapping OpenSharedResourceByName");
return m_pDevice1->OpenSharedResourceByName(lpName, dwDesiredAccess, returnedInterface, ppResource);
}
#undef IMPLEMENT_FUNCTION_SERIALISED
#define IMPLEMENT_FUNCTION_SERIALISED(ret, func, ...) \
template bool WrappedID3D11Device::CONCAT(Serialise_, func(ReadSerialiser &ser, __VA_ARGS__)); \
template bool WrappedID3D11Device::CONCAT(Serialise_, func(WriteSerialiser &ser, __VA_ARGS__));
SERIALISED_ID3D11DEVICE1_FUNCTIONS();<|endoftext|> |
<commit_before>//
// Created by Per Lange Laursen on 12/04/16.
//
#include <iostream>
#include "Clause.h"
Clause::Clause() {
}
Clause::~Clause() {
//delete cameFrom;
}
void Clause::updateTotalDistance() {
totalDistance = distanceFromStart + heuristic_distance;
}
void Clause::addLiteralToClause(Literal &literal) {
symbols.push_back(literal);
}
void Clause::calcHeuristicDistance() {
heuristic_distance = boost::lexical_cast<double>(symbols.size());
}
std::string Clause::toString() const {
std::string out("");
for(const Literal& literal : symbols) {
out += literal.toString();
out += " || ";
}
out = (out.compare("") == 0) ? "Ø" : out.substr(0, out.length() - 4);
if (symbols.size() > 1) out = "(" + out +")";
return out;
}
bool Clause::operator()(const Clause &lhs, const Clause &rhs) const {
return lhs.totalDistance < rhs.totalDistance;
}
bool Clause::operator<(const Clause &rhs) const {
return totalDistance < rhs.totalDistance;
}
bool Clause::operator==(const Clause &rhs) const {
bool isEqual = (rhs.symbols.size() == symbols.size());
for(Literal symbol : rhs.symbols) {
if(std::find(symbols.begin(), symbols.end(), symbol) == symbols.end())
isEqual = false;
}
return isEqual;
}
bool Clause::operator!=(const Clause &rhs) const {
bool isNotEqual = (rhs.symbols.size() != symbols.size());
for(Literal symbol : rhs.symbols) {
if(!(std::find(symbols.begin(), symbols.end(), symbol) == symbols.end()))
isNotEqual = false;
}
return isNotEqual;
}
void Clause::operator=(const Clause &rhs) {
symbols = rhs.symbols;
resolutedClauses = rhs.resolutedClauses;
distanceFromStart = rhs.distanceFromStart;
heuristic_distance = rhs.heuristic_distance;
totalDistance = rhs.totalDistance;
visited = rhs.visited;
cameFrom = rhs.cameFrom;
}
std::ostream &operator<<(std::ostream &os, const Clause &clause) {
os << clause.toString();
return os;
}
std::vector<neighbor> &Clause::getResolutedClauses() {
return resolutedClauses;
}
void Clause::addNeighbor(int neighbor, std::string clause) {
resolutedClauses.push_back(std::make_pair(neighbor, clause));
}
<commit_msg>Testing in progress. Currently pointer error<commit_after>//
// Created by Per Lange Laursen on 12/04/16.
//
#include <iostream>
#include "Clause.h"
Clause::Clause() {
}
Clause::~Clause() {
//delete cameFrom;
}
void Clause::updateTotalDistance() {
totalDistance = distanceFromStart + heuristic_distance;
}
void Clause::addLiteralToClause(Literal &literal) {
symbols.push_back(literal);
}
void Clause::calcHeuristicDistance() {
heuristic_distance = boost::lexical_cast<double>(symbols.size());
}
std::string Clause::toString() const {
std::string out("");
for(const Literal& literal : symbols) {
out += literal.toString();
out += " || ";
}
out = (out.compare("") == 0) ? "Ø" : out.substr(0, out.length() - 4);
if (symbols.size() > 1) out = "(" + out +")";
return out;
}
bool Clause::operator()(const Clause &lhs, const Clause &rhs) const {
return lhs.totalDistance < rhs.totalDistance;
}
bool Clause::operator<(const Clause &rhs) const {
return totalDistance < rhs.totalDistance;
}
bool Clause::operator==(const Clause &rhs) const {
bool isEqual = (rhs.symbols.size() == symbols.size());
for(Literal symbol : rhs.symbols) {
if(std::find(symbols.begin(), symbols.end(), symbol) == symbols.end())
isEqual = false;
}
return isEqual;
}
bool Clause::operator!=(const Clause &rhs) const {
bool isNotEqual = (rhs.symbols.size() != symbols.size());
for(Literal symbol : rhs.symbols) {
if(!(std::find(symbols.begin(), symbols.end(), symbol) == symbols.end()))
isNotEqual = false;
}
return isNotEqual;
}
void Clause::operator=(const Clause &rhs) {
symbols = rhs.symbols;
neighbors = rhs.neighbors;
distanceFromStart = rhs.distanceFromStart;
heuristic_distance = rhs.heuristic_distance;
totalDistance = rhs.totalDistance;
visited = rhs.visited;
cameFrom = rhs.cameFrom;
}
std::ostream &operator<<(std::ostream &os, const Clause &clause) {
os << clause.toString();
return os;
}
void Clause::addNeighbor(int neighbor, std::string clause) {
neighbors.push_back(std::make_pair(neighbor, clause));
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Mario Alviano (mario@alviano.net)
*
* 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 "FairSatSolver.h"
#include <core/Dimacs.h>
Glucose::EnumOption option_fairsat_alg("FAIRSAT", "fairsat-alg", "Set search algorithm.", "bb|binary|progression");
Glucose::BoolOption option_fairsat_printmodel("FAIRSAT", "fairsat-print-model", "Print optimal model if found.", true);
namespace aspino {
template<class B, class Solver>
static void readObjFunc(B& in, Solver& S, vec<Lit>& lits, vec<int64_t>& coeffs) {
int parsed_lit, var;
lits.clear();
coeffs.clear();
int size = parseInt(in);
for(int i = 0; i < size; i++) {
parsed_lit = parseInt(in);
if (parsed_lit == 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
var = abs(parsed_lit)-1;
while (var >= S.nVars()) S.newVar();
lits.push( (parsed_lit > 0) ? mkLit(var) : ~mkLit(var) );
}
for(int i = 0; i < size; i++) {
coeffs.push(parseLong(in));
if (coeffs.last() == 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
}
parsed_lit = parseInt(in);
if (parsed_lit != 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
}
void ObjectFunction::init(vec<Lit>& lits_, vec<int64_t>& coeffs_) {
assert(lits_.size() == coeffs_.size());
lits_.moveTo(lits);
coeffs_.moveTo(coeffs);
}
FairSatSolver::FairSatSolver() : PseudoBooleanSolver() {
if(strcmp(option_fairsat_alg, "bb") == 0) search_alg = &FairSatSolver::search_alg_bb;
else if(strcmp(option_fairsat_alg, "binary") == 0) search_alg = &FairSatSolver::search_alg_binary;
else if(strcmp(option_fairsat_alg, "progression") == 0) search_alg = &FairSatSolver::search_alg_progression;
else assert(0);
}
FairSatSolver::~FairSatSolver() {
for(int i = 0; i < objectFunctions.size(); i++) delete objectFunctions[i];
objectFunctions.clear();
}
void FairSatSolver::parse(gzFile in_) {
Glucose::StreamBuffer in(in_);
int64_t objFuncs = -1;
vec<Lit> lits;
vec<int64_t> coeffs;
int vars = 0;
int count = 0;
inClauses = 0;
for(;;) {
if(inClauses > 0 && count == inClauses) break;
skipWhitespace(in);
if(*in == EOF) break;
if(*in == 'p') {
++in;
if(*in != ' ') cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
++in;
if(eagerMatch(in, "fcnf")) {
vars = parseInt(in);
inClauses = parseInt(in);
objFuncs = parseLong(in);
nInVars(vars);
while(nVars() < nInVars()) newVar();
}
else {
cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
}
}
else if(*in == 'c')
skipLine(in);
else {
count++;
readClause(in, *this, lits);
addClause_(lits);
}
}
if(count != inClauses)
cerr << "WARNING! DIMACS header mismatch: wrong number of clauses." << endl, exit(3);
count = 0;
for(;;) {
skipWhitespace(in);
if(*in == EOF) break;
if(*in == 'c')
skipLine(in);
else {
count++;
readObjFunc(in, *this, lits, coeffs);
addObjectFunction(lits, coeffs);
}
}
if(count != objFuncs)
cerr << "WARNING! DIMACS header mismatch: wrong number of object functions." << endl, exit(3);
upperbound = processObjectFunctions();
assert(upperbound >= 0);
freeze();
}
void FairSatSolver::addObjectFunction(vec<Lit>& lits, vec<int64_t>& coeffs) {
ObjectFunction* objF = new ObjectFunction;
objF->init(lits, coeffs);
objectFunctions.push(objF);
}
int64_t FairSatSolver::processObjectFunctions() {
int64_t min = INT64_MAX;
for(int idx = 0; idx < objectFunctions.size(); idx++) {
ObjectFunction& objF = *objectFunctions[idx];
WeightConstraint wc;
objF.lits.copyTo(wc.lits);
objF.coeffs.copyTo(wc.coeffs);
for(int i = 0; i < objF.coeffs.size(); i++) wc.bound += objF.coeffs[i];
objF.sumOfInCoeffs = wc.bound;
if(wc.bound < min) min = wc.bound;
int64_t n = ceil(log2(wc.bound));
for(int64_t i = 0, w = 1; i < n; i++, w *= 2) {
newVar();
wc.lits.push(~mkLit(nVars()-1));
wc.coeffs.push(w);
objF.selectorVars.push(nVars()-1);
}
addConstraint(wc);
}
return min;
}
void FairSatSolver::setMinObjectFunction(int64_t min) {
assumptions.clear();
for(int i = 0; i < objectFunctions.size(); i++) {
int64_t mask = objectFunctions[i]->sumOfInCoeffs - min;
assert(mask >= 0);
for(int j = 0; j < objectFunctions[i]->selectorVars.size(); j++) {
assumptions.push(mkLit(objectFunctions[i]->selectorVars[j], (1ll << j) & mask));
}
}
}
void FairSatSolver::updateLowerBound() {
copyModel();
int64_t min = INT64_MAX;
for(int i = 0; i < objectFunctions.size(); i++) {
ObjectFunction& objF = *objectFunctions[i];
objF.modelValue = 0;
for(int j = 0; j < objF.lits.size(); j++) {
if(value(objF.lits[j]) != l_False) objF.modelValue += objF.coeffs[j];
}
if(objF.modelValue < min) min = objF.modelValue;
}
assert_msg(min > lowerbound, "min = " << min << "; lowerbound = " << lowerbound);
lowerbound = min;
}
lbool FairSatSolver::solve() {
lowerbound = -1;
cout << "c searching in [" << lowerbound << ".." << upperbound << "]" << endl;
(this->*search_alg)();
if(lowerbound == -1)
cout << "s UNSATISFIABLE" << endl;
else {
cout << "s OPTIMUM FOUND" << endl;
if(option_fairsat_printmodel) printModel();
}
return status;
}
void FairSatSolver::search_alg_bb() {
for(;;) {
setMinObjectFunction(lowerbound + 1);
PseudoBooleanSolver::solve();
if(status == l_False) break;
if(status == l_True) {
updateLowerBound();
cout << "o " << lowerbound << endl;
// cout << "c object function values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue;
// cout << endl;
// cout << "c unsatisfied values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue);
// cout << endl;
}
if(lowerbound == upperbound) break;
}
}
void FairSatSolver::search_alg_binary() {
for(;;) {
assert(lowerbound < upperbound);
int64_t mid = (lowerbound + upperbound) / 2;
if(mid == lowerbound) mid++;
setMinObjectFunction(mid);
PseudoBooleanSolver::solve();
if(status == l_False) {
upperbound = mid-1;
cout << "c ub " << upperbound << endl;
}
else if(status == l_True) {
updateLowerBound();
cout << "o " << lowerbound << endl;
// cout << "c object function values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue;
// cout << endl;
// cout << "c unsatisfied values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue);
// cout << endl;
}
if(lowerbound == upperbound) break;
}
}
void FairSatSolver::search_alg_progression() {
int64_t progression = 1;
for(;;) {
assert(lowerbound < upperbound);
if(lowerbound + progression > upperbound) progression = 1;
setMinObjectFunction(lowerbound + progression);
// cout << progression << endl;
setConfBudget(100);
PseudoBooleanSolver::solve();
budgetOff();
if(status == l_False) {
upperbound = lowerbound + progression - 1;
cout << "c ub " << upperbound << endl;
}
else if(status == l_True) {
updateLowerBound();
cout << "o " << lowerbound << endl;
// cout << "c object function values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue;
// cout << endl;
// cout << "c unsatisfied values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue);
// cout << endl;
}
else { progression = 1; continue; }
if(lowerbound == upperbound) break;
progression *= 2;
}
}
} // namespace aspino
<commit_msg>Fix bug with weight functions whose weights sum up to a power of 2.<commit_after>/*
* Copyright (C) 2015 Mario Alviano (mario@alviano.net)
*
* 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 "FairSatSolver.h"
#include <core/Dimacs.h>
Glucose::EnumOption option_fairsat_alg("FAIRSAT", "fairsat-alg", "Set search algorithm.", "bb|binary|progression");
Glucose::BoolOption option_fairsat_printmodel("FAIRSAT", "fairsat-print-model", "Print optimal model if found.", true);
namespace aspino {
template<class B, class Solver>
static void readObjFunc(B& in, Solver& S, vec<Lit>& lits, vec<int64_t>& coeffs) {
int parsed_lit, var;
lits.clear();
coeffs.clear();
int size = parseInt(in);
for(int i = 0; i < size; i++) {
parsed_lit = parseInt(in);
if (parsed_lit == 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
var = abs(parsed_lit)-1;
while (var >= S.nVars()) S.newVar();
lits.push( (parsed_lit > 0) ? mkLit(var) : ~mkLit(var) );
}
for(int i = 0; i < size; i++) {
coeffs.push(parseLong(in));
if (coeffs.last() == 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
}
parsed_lit = parseInt(in);
if (parsed_lit != 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
}
void ObjectFunction::init(vec<Lit>& lits_, vec<int64_t>& coeffs_) {
assert(lits_.size() == coeffs_.size());
lits_.moveTo(lits);
coeffs_.moveTo(coeffs);
}
FairSatSolver::FairSatSolver() : PseudoBooleanSolver() {
if(strcmp(option_fairsat_alg, "bb") == 0) search_alg = &FairSatSolver::search_alg_bb;
else if(strcmp(option_fairsat_alg, "binary") == 0) search_alg = &FairSatSolver::search_alg_binary;
else if(strcmp(option_fairsat_alg, "progression") == 0) search_alg = &FairSatSolver::search_alg_progression;
else assert(0);
}
FairSatSolver::~FairSatSolver() {
for(int i = 0; i < objectFunctions.size(); i++) delete objectFunctions[i];
objectFunctions.clear();
}
void FairSatSolver::parse(gzFile in_) {
Glucose::StreamBuffer in(in_);
int64_t objFuncs = -1;
vec<Lit> lits;
vec<int64_t> coeffs;
int vars = 0;
int count = 0;
inClauses = 0;
for(;;) {
if(inClauses > 0 && count == inClauses) break;
skipWhitespace(in);
if(*in == EOF) break;
if(*in == 'p') {
++in;
if(*in != ' ') cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
++in;
if(eagerMatch(in, "fcnf")) {
vars = parseInt(in);
inClauses = parseInt(in);
objFuncs = parseLong(in);
nInVars(vars);
while(nVars() < nInVars()) newVar();
}
else {
cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3);
}
}
else if(*in == 'c')
skipLine(in);
else {
count++;
readClause(in, *this, lits);
addClause_(lits);
}
}
if(count != inClauses)
cerr << "WARNING! DIMACS header mismatch: wrong number of clauses." << endl, exit(3);
count = 0;
for(;;) {
skipWhitespace(in);
if(*in == EOF) break;
if(*in == 'c')
skipLine(in);
else {
count++;
readObjFunc(in, *this, lits, coeffs);
addObjectFunction(lits, coeffs);
}
}
if(count != objFuncs)
cerr << "WARNING! DIMACS header mismatch: wrong number of object functions." << endl, exit(3);
upperbound = processObjectFunctions();
assert(upperbound >= 0);
freeze();
}
void FairSatSolver::addObjectFunction(vec<Lit>& lits, vec<int64_t>& coeffs) {
ObjectFunction* objF = new ObjectFunction;
objF->init(lits, coeffs);
objectFunctions.push(objF);
}
int64_t FairSatSolver::processObjectFunctions() {
int64_t min = INT64_MAX;
for(int idx = 0; idx < objectFunctions.size(); idx++) {
ObjectFunction& objF = *objectFunctions[idx];
WeightConstraint wc;
objF.lits.copyTo(wc.lits);
objF.coeffs.copyTo(wc.coeffs);
for(int i = 0; i < objF.coeffs.size(); i++) wc.bound += objF.coeffs[i];
objF.sumOfInCoeffs = wc.bound;
if(wc.bound < min) min = wc.bound;
int64_t n = floor(log2(wc.bound));
for(int64_t i = 0, w = 1; i <= n; i++, w *= 2) {
newVar();
wc.lits.push(~mkLit(nVars()-1));
wc.coeffs.push(w);
objF.selectorVars.push(nVars()-1);
}
addConstraint(wc);
}
return min;
}
void FairSatSolver::setMinObjectFunction(int64_t min) {
assumptions.clear();
for(int i = 0; i < objectFunctions.size(); i++) {
int64_t mask = objectFunctions[i]->sumOfInCoeffs - min;
assert(mask >= 0);
for(int j = 0; j < objectFunctions[i]->selectorVars.size(); j++) {
assumptions.push(mkLit(objectFunctions[i]->selectorVars[j], (1ll << j) & mask));
}
}
}
void FairSatSolver::updateLowerBound() {
copyModel();
int64_t min = INT64_MAX;
for(int i = 0; i < objectFunctions.size(); i++) {
ObjectFunction& objF = *objectFunctions[i];
objF.modelValue = 0;
for(int j = 0; j < objF.lits.size(); j++) {
if(value(objF.lits[j]) != l_False) objF.modelValue += objF.coeffs[j];
}
if(objF.modelValue < min) min = objF.modelValue;
}
assert_msg(min > lowerbound, "min = " << min << "; lowerbound = " << lowerbound);
lowerbound = min;
}
lbool FairSatSolver::solve() {
lowerbound = -1;
cout << "c searching in [" << lowerbound << ".." << upperbound << "]" << endl;
(this->*search_alg)();
if(lowerbound == -1)
cout << "s UNSATISFIABLE" << endl;
else {
cout << "s OPTIMUM FOUND" << endl;
if(option_fairsat_printmodel) printModel();
}
return status;
}
void FairSatSolver::search_alg_bb() {
for(;;) {
setMinObjectFunction(lowerbound + 1);
PseudoBooleanSolver::solve();
if(status == l_False) break;
if(status == l_True) {
updateLowerBound();
cout << "o " << lowerbound << endl;
// cout << "c object function values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue;
// cout << endl;
// cout << "c unsatisfied values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue);
// cout << endl;
}
if(lowerbound == upperbound) break;
}
}
void FairSatSolver::search_alg_binary() {
for(;;) {
assert(lowerbound < upperbound);
int64_t mid = (lowerbound + upperbound) / 2;
if(mid == lowerbound) mid++;
setMinObjectFunction(mid);
PseudoBooleanSolver::solve();
if(status == l_False) {
upperbound = mid-1;
cout << "c ub " << upperbound << endl;
}
else if(status == l_True) {
updateLowerBound();
cout << "o " << lowerbound << endl;
// cout << "c object function values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue;
// cout << endl;
// cout << "c unsatisfied values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue);
// cout << endl;
}
if(lowerbound == upperbound) break;
}
}
void FairSatSolver::search_alg_progression() {
int64_t progression = 1;
for(;;) {
assert(lowerbound < upperbound);
if(lowerbound + progression > upperbound) progression = 1;
setMinObjectFunction(lowerbound + progression);
// cout << progression << endl;
// setConfBudget(100);
PseudoBooleanSolver::solve();
// budgetOff();
if(status == l_False) {
upperbound = lowerbound + progression - 1;
cout << "c ub " << upperbound << endl;
}
else if(status == l_True) {
updateLowerBound();
cout << "o " << lowerbound << endl;
// cout << "c object function values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue;
// cout << endl;
// cout << "c unsatisfied values:";
// for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue);
// cout << endl;
}
// else { progression = 1; continue; }
if(lowerbound == upperbound) break;
progression *= 2;
}
}
} // namespace aspino
<|endoftext|> |
<commit_before>#include "BoundingBox.hpp"
#include "Exceptions.hpp"
#include "clipper/clipper.hpp"
#include "builders/TerraBuilder.hpp"
#include "entities/ElementVisitor.hpp"
#include "meshing/Polygon.hpp"
#include "meshing/MeshBuilder.hpp"
#include "meshing/LineGridSplitter.hpp"
#include "index/GeoUtils.hpp"
#include "utils/CompatibilityUtils.hpp"
#include "utils/MapCssUtils.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <iterator>
#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::index;
using namespace utymap::heightmap;
using namespace utymap::mapcss;
using namespace utymap::meshing;
const uint64_t Scale = 1E7; // max precision for Lat/Lon: seven decimal positions
const double Tolerance = 10; // Tolerance for splitting algorithm
const double AreaTolerance = 100; // Tolerance for meshing
// Properties of terrain region union.
struct Properties
{
std::string gradientKey;
float eleNoiseFreq;
float colorNoiseFreq;
float maxArea;
float heightOffset;
Properties() : gradientKey(), eleNoiseFreq(0), colorNoiseFreq(0),
heightOffset(0), maxArea(0)
{
}
};
// Represents terrain region points.
struct Region
{
bool isLayer;
Properties properties;
Paths points;
};
typedef std::vector<Point> Points;
typedef std::vector<Region> Regions;
typedef std::unordered_map<std::string, Regions> Layers;
// mapcss specific keys
const static std::string TerrainLayerKey = "terrain-layer";
const static std::string ColorNoiseFreqKey = "color-noise-freq";
const static std::string EleNoiseFreqKey = "ele-noise-freq";
const static std::string GradientKey= "color";
const static std::string MaxAreaKey = "max-area";
const static std::string WidthKey = "width";
const static std::string LayerPriorityKey = "layer-priority";
class TerraBuilder::TerraBuilderImpl : public ElementVisitor
{
public:
TerraBuilderImpl(StringTable& stringTable, const StyleProvider& styleProvider,
ElevationProvider& eleProvider, std::function<void(const Mesh&)> callback) :
stringTable_(stringTable), styleProvider_(styleProvider), meshBuilder_(eleProvider),
callback_(callback), quadKey_(),splitter_()
{
}
inline void setQuadKey(const QuadKey& quadKey)
{
quadKey_ = quadKey;
}
void visitNode(const utymap::entities::Node& node)
{
}
void visitWay(const utymap::entities::Way& way)
{
Style style = styleProvider_.forElement(way, quadKey_.levelOfDetail);
Region region = createRegion(style, way.coordinates);
// make polygon from line by offsetting it using width specified
float width = utymap::utils::getFloat(WidthKey, stringTable_, style);
Paths offsetSolution;
offset_.AddPaths(region.points, jtMiter, etOpenSquare);
offset_.Execute(offsetSolution, width * Scale);
offset_.Clear();
region.points = offsetSolution;
std::string type = region.isLayer ? utymap::utils::getString(TerrainLayerKey, stringTable_, style) : "";
layers_[type].push_back(region);
}
void visitArea(const utymap::entities::Area& area)
{
Style style = styleProvider_.forElement(area, quadKey_.levelOfDetail);
Region region = createRegion(style, area.coordinates);
std::string type = region.isLayer
? utymap::utils::getString(TerrainLayerKey, stringTable_, style)
: "";
layers_[type].push_back(region);
}
void visitRelation(const utymap::entities::Relation& relation)
{
Region region;
struct RelationVisitor : public ElementVisitor
{
const Relation& relation;
TerraBuilder::TerraBuilderImpl& builder;
Region& region;
RelationVisitor(TerraBuilder::TerraBuilderImpl& builder, const Relation& relation, Region& region) :
builder(builder), relation(relation), region(region) {}
void visitNode(const utymap::entities::Node& node) { node.accept(builder); }
void visitWay(const utymap::entities::Way& way) { way.accept(builder); }
void visitArea(const utymap::entities::Area& area)
{
Path path;
path.reserve(area.coordinates.size());
for (const GeoCoordinate& c : area.coordinates) {
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
}
region.points.push_back(path);
}
void visitRelation(const utymap::entities::Relation& relation) { relation.accept(builder); }
} visitor(*this, relation, region);
for (const auto& element : relation.elements) {
// if there are no tags, then this element is result of clipping
if (element->tags.empty())
element->tags = relation.tags;
element->accept(visitor);
}
if (!region.points.empty()) {
Style style = styleProvider_.forElement(relation, quadKey_.levelOfDetail);
region.isLayer = style.has(stringTable_.getId(TerrainLayerKey));
if (!region.isLayer) {
region.properties = createRegionProperties(style, "");
}
std::string type = region.isLayer ? utymap::utils::getString(TerrainLayerKey, stringTable_, style) : "";
layers_[type].push_back(region);
}
}
// builds tile mesh using data provided.
void build()
{
configureSplitter(quadKey_.levelOfDetail);
Style style = styleProvider_.forCanvas(quadKey_.levelOfDetail);
buildLayers(style);
buildBackground(style);
callback_(mesh_);
}
private:
void configureSplitter(int levelOfDetails)
{
// TODO
switch (levelOfDetails)
{
case 1: splitter_.setParams(Scale, 3, Tolerance); break;
default: throw std::domain_error("Unknown Level of details:" + std::to_string(levelOfDetails));
};
}
Region createRegion(const Style& style, const std::vector<GeoCoordinate>& coordinates)
{
Region region;
Path path;
path.reserve(coordinates.size());
for (const GeoCoordinate& c : coordinates) {
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
}
region.points.push_back(path);
region.isLayer = style.has(stringTable_.getId(TerrainLayerKey));
if (!region.isLayer)
region.properties = createRegionProperties(style, "");
return std::move(region);
}
Properties createRegionProperties(const Style& style, const std::string& prefix)
{
Properties properties;
properties.eleNoiseFreq = utymap::utils::getFloat(prefix + EleNoiseFreqKey, stringTable_, style);
properties.colorNoiseFreq = utymap::utils::getFloat(prefix + ColorNoiseFreqKey, stringTable_, style);
properties.gradientKey = utymap::utils::getString(prefix + GradientKey, stringTable_, style);
properties.maxArea = utymap::utils::getFloat(prefix + MaxAreaKey, stringTable_, style);
return std::move(properties);
}
void buildFromRegions(const Regions& regions, const Properties& properties)
{
// merge all regions together
Clipper clipper;
for (const Region& region : regions) {
clipper.AddPaths(region.points, ptSubject, true);
}
Paths result;
clipper.Execute(ctUnion, result, pftPositive, pftPositive);
buildFromPaths(result, properties);
}
void buildFromPaths(Paths& path, const Properties& properties)
{
clipper_.AddPaths(path, ptSubject, true);
path.clear();
clipper_.Execute(ctDifference, path, pftPositive, pftPositive);
clipper_.moveSubjectToClip();
populateMesh(properties, path);
}
// process all found layers.
void buildLayers(const Style& style)
{
// 1. process layers: regions with shared properties.
std::stringstream ss(utymap::utils::getString(LayerPriorityKey, stringTable_, style));
while (ss.good())
{
std::string name;
getline(ss, name, ',');
auto layer = layers_.find(name);
if (layer != layers_.end()) {
Properties properties = createRegionProperties(style, name + "-");
buildFromRegions(layer->second, properties);
layers_.erase(layer);
}
}
// 2. Process the rest: each region has aready its own properties.
for (auto& layer : layers_) {
for (auto& region : layer.second) {
buildFromPaths(region.points, region.properties);
}
}
}
// process the rest area.
void buildBackground(const Style& style)
{
BoundingBox bbox = utymap::index::GeoUtils::quadKeyToBoundingBox(quadKey_);
Path tileRect;
tileRect.push_back(IntPoint(bbox.minPoint.longitude*Scale, bbox.minPoint.latitude *Scale));
tileRect.push_back(IntPoint(bbox.maxPoint.longitude *Scale, bbox.minPoint.latitude *Scale));
tileRect.push_back(IntPoint(bbox.maxPoint.longitude *Scale, bbox.maxPoint.latitude*Scale));
tileRect.push_back(IntPoint(bbox.minPoint.longitude*Scale, bbox.maxPoint.latitude*Scale));
clipper_.AddPath(tileRect, ptSubject, true);
Paths background;
clipper_.Execute(ctDifference, background, pftPositive, pftPositive);
clipper_.Clear();
if (!background.empty())
populateMesh(createRegionProperties(style, ""), background);
}
void populateMesh(const Properties& properties, Paths& paths)
{
ClipperLib::SimplifyPolygons(paths);
ClipperLib::CleanPolygons(paths);
bool hasHeightOffset = properties.heightOffset > 0;
// calculate approximate size of overall points
auto size = 0;
for (auto i = 0; i < paths.size(); ++i) {
size += paths[i].size() * 1.5;
}
Polygon polygon(size);
for (const Path& path : paths) {
double area = ClipperLib::Area(path);
if (std::abs(area) < AreaTolerance) continue;
Points points = restorePoints(path);
if (area < 0)
polygon.addHole(points);
else
polygon.addContour(points);
}
if (!polygon.points.empty())
fillMesh(properties, polygon);
}
// restores mesh points from clipper points and injects new ones according to grid.
Points restorePoints(const Path& path)
{
int lastItemIndex = path.size() - 1;
Points points;
points.reserve(path.size());
for (int i = 0; i <= lastItemIndex; i++) {
splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);
}
return std::move(points);
}
void processHeightOffset(const std::vector<Points>& contours)
{
// TODO
}
void fillMesh(const Properties& properties, Polygon& polygon)
{
Mesh regionMesh = meshBuilder_.build(polygon, MeshBuilder::Options
{
/* area=*/ properties.maxArea,
/* elevation noise frequency*/ properties.eleNoiseFreq,
/* color noise frequency. */ properties.colorNoiseFreq,
styleProvider_.getGradient(properties.gradientKey),
/* segmentSplit=*/ 0
});
auto startVertIndex = mesh_.vertices.size() / 3;
mesh_.vertices.insert(mesh_.vertices.end(),
regionMesh.vertices.begin(),
regionMesh.vertices.end());
for (const auto& tri : regionMesh.triangles) {
mesh_.triangles.push_back(startVertIndex + tri);
}
mesh_.colors.insert(mesh_.colors.end(),
regionMesh.colors.begin(),
regionMesh.colors.end());
}
const StyleProvider& styleProvider_;
StringTable& stringTable_;
std::function<void(const Mesh&)> callback_;
ClipperEx clipper_;
ClipperOffset offset_;
LineGridSplitter splitter_;
MeshBuilder meshBuilder_;
QuadKey quadKey_;
Layers layers_;
Mesh mesh_;
};
void TerraBuilder::visitNode(const utymap::entities::Node& node) { pimpl_->visitNode(node); }
void TerraBuilder::visitWay(const utymap::entities::Way& way) { pimpl_->visitWay(way); }
void TerraBuilder::visitArea(const utymap::entities::Area& area) { pimpl_->visitArea(area); }
void TerraBuilder::visitRelation(const utymap::entities::Relation& relation) { pimpl_->visitRelation(relation); }
void TerraBuilder::prepare(const utymap::QuadKey& quadKey) { pimpl_->setQuadKey(quadKey); }
void TerraBuilder::complete() { pimpl_->build(); }
TerraBuilder::~TerraBuilder() { }
TerraBuilder::TerraBuilder(StringTable& stringTable, const StyleProvider& styleProvider, ElevationProvider& eleProvider,
std::function<void(const Mesh&)> callback) :
pimpl_(std::unique_ptr<TerraBuilder::TerraBuilderImpl>(new TerraBuilder::TerraBuilderImpl(stringTable, styleProvider, eleProvider, callback)))
{
}
<commit_msg>refactoring: remove new line<commit_after>#include "BoundingBox.hpp"
#include "Exceptions.hpp"
#include "clipper/clipper.hpp"
#include "builders/TerraBuilder.hpp"
#include "entities/ElementVisitor.hpp"
#include "meshing/Polygon.hpp"
#include "meshing/MeshBuilder.hpp"
#include "meshing/LineGridSplitter.hpp"
#include "index/GeoUtils.hpp"
#include "utils/CompatibilityUtils.hpp"
#include "utils/MapCssUtils.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <iterator>
#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::index;
using namespace utymap::heightmap;
using namespace utymap::mapcss;
using namespace utymap::meshing;
const uint64_t Scale = 1E7; // max precision for Lat/Lon: seven decimal positions
const double Tolerance = 10; // Tolerance for splitting algorithm
const double AreaTolerance = 100; // Tolerance for meshing
// Properties of terrain region union.
struct Properties
{
std::string gradientKey;
float eleNoiseFreq;
float colorNoiseFreq;
float maxArea;
float heightOffset;
Properties() : gradientKey(), eleNoiseFreq(0), colorNoiseFreq(0),
heightOffset(0), maxArea(0)
{
}
};
// Represents terrain region points.
struct Region
{
bool isLayer;
Properties properties;
Paths points;
};
typedef std::vector<Point> Points;
typedef std::vector<Region> Regions;
typedef std::unordered_map<std::string, Regions> Layers;
// mapcss specific keys
const static std::string TerrainLayerKey = "terrain-layer";
const static std::string ColorNoiseFreqKey = "color-noise-freq";
const static std::string EleNoiseFreqKey = "ele-noise-freq";
const static std::string GradientKey= "color";
const static std::string MaxAreaKey = "max-area";
const static std::string WidthKey = "width";
const static std::string LayerPriorityKey = "layer-priority";
class TerraBuilder::TerraBuilderImpl : public ElementVisitor
{
public:
TerraBuilderImpl(StringTable& stringTable, const StyleProvider& styleProvider,
ElevationProvider& eleProvider, std::function<void(const Mesh&)> callback) :
stringTable_(stringTable), styleProvider_(styleProvider), meshBuilder_(eleProvider),
callback_(callback), quadKey_(),splitter_()
{
}
inline void setQuadKey(const QuadKey& quadKey)
{
quadKey_ = quadKey;
}
void visitNode(const utymap::entities::Node& node)
{
}
void visitWay(const utymap::entities::Way& way)
{
Style style = styleProvider_.forElement(way, quadKey_.levelOfDetail);
Region region = createRegion(style, way.coordinates);
// make polygon from line by offsetting it using width specified
float width = utymap::utils::getFloat(WidthKey, stringTable_, style);
Paths offsetSolution;
offset_.AddPaths(region.points, jtMiter, etOpenSquare);
offset_.Execute(offsetSolution, width * Scale);
offset_.Clear();
region.points = offsetSolution;
std::string type = region.isLayer ? utymap::utils::getString(TerrainLayerKey, stringTable_, style) : "";
layers_[type].push_back(region);
}
void visitArea(const utymap::entities::Area& area)
{
Style style = styleProvider_.forElement(area, quadKey_.levelOfDetail);
Region region = createRegion(style, area.coordinates);
std::string type = region.isLayer
? utymap::utils::getString(TerrainLayerKey, stringTable_, style)
: "";
layers_[type].push_back(region);
}
void visitRelation(const utymap::entities::Relation& relation)
{
Region region;
struct RelationVisitor : public ElementVisitor
{
const Relation& relation;
TerraBuilder::TerraBuilderImpl& builder;
Region& region;
RelationVisitor(TerraBuilder::TerraBuilderImpl& builder, const Relation& relation, Region& region) :
builder(builder), relation(relation), region(region) {}
void visitNode(const utymap::entities::Node& node) { node.accept(builder); }
void visitWay(const utymap::entities::Way& way) { way.accept(builder); }
void visitArea(const utymap::entities::Area& area)
{
Path path;
path.reserve(area.coordinates.size());
for (const GeoCoordinate& c : area.coordinates) {
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
}
region.points.push_back(path);
}
void visitRelation(const utymap::entities::Relation& relation) { relation.accept(builder); }
} visitor(*this, relation, region);
for (const auto& element : relation.elements) {
// if there are no tags, then this element is result of clipping
if (element->tags.empty())
element->tags = relation.tags;
element->accept(visitor);
}
if (!region.points.empty()) {
Style style = styleProvider_.forElement(relation, quadKey_.levelOfDetail);
region.isLayer = style.has(stringTable_.getId(TerrainLayerKey));
if (!region.isLayer) {
region.properties = createRegionProperties(style, "");
}
std::string type = region.isLayer ? utymap::utils::getString(TerrainLayerKey, stringTable_, style) : "";
layers_[type].push_back(region);
}
}
// builds tile mesh using data provided.
void build()
{
configureSplitter(quadKey_.levelOfDetail);
Style style = styleProvider_.forCanvas(quadKey_.levelOfDetail);
buildLayers(style);
buildBackground(style);
callback_(mesh_);
}
private:
void configureSplitter(int levelOfDetails)
{
// TODO
switch (levelOfDetails)
{
case 1: splitter_.setParams(Scale, 3, Tolerance); break;
default: throw std::domain_error("Unknown Level of details:" + std::to_string(levelOfDetails));
};
}
Region createRegion(const Style& style, const std::vector<GeoCoordinate>& coordinates)
{
Region region;
Path path;
path.reserve(coordinates.size());
for (const GeoCoordinate& c : coordinates) {
path.push_back(IntPoint(c.longitude * Scale, c.latitude * Scale));
}
region.points.push_back(path);
region.isLayer = style.has(stringTable_.getId(TerrainLayerKey));
if (!region.isLayer)
region.properties = createRegionProperties(style, "");
return std::move(region);
}
Properties createRegionProperties(const Style& style, const std::string& prefix)
{
Properties properties;
properties.eleNoiseFreq = utymap::utils::getFloat(prefix + EleNoiseFreqKey, stringTable_, style);
properties.colorNoiseFreq = utymap::utils::getFloat(prefix + ColorNoiseFreqKey, stringTable_, style);
properties.gradientKey = utymap::utils::getString(prefix + GradientKey, stringTable_, style);
properties.maxArea = utymap::utils::getFloat(prefix + MaxAreaKey, stringTable_, style);
return std::move(properties);
}
void buildFromRegions(const Regions& regions, const Properties& properties)
{
// merge all regions together
Clipper clipper;
for (const Region& region : regions) {
clipper.AddPaths(region.points, ptSubject, true);
}
Paths result;
clipper.Execute(ctUnion, result, pftPositive, pftPositive);
buildFromPaths(result, properties);
}
void buildFromPaths(Paths& path, const Properties& properties)
{
clipper_.AddPaths(path, ptSubject, true);
path.clear();
clipper_.Execute(ctDifference, path, pftPositive, pftPositive);
clipper_.moveSubjectToClip();
populateMesh(properties, path);
}
// process all found layers.
void buildLayers(const Style& style)
{
// 1. process layers: regions with shared properties.
std::stringstream ss(utymap::utils::getString(LayerPriorityKey, stringTable_, style));
while (ss.good())
{
std::string name;
getline(ss, name, ',');
auto layer = layers_.find(name);
if (layer != layers_.end()) {
Properties properties = createRegionProperties(style, name + "-");
buildFromRegions(layer->second, properties);
layers_.erase(layer);
}
}
// 2. Process the rest: each region has aready its own properties.
for (auto& layer : layers_) {
for (auto& region : layer.second) {
buildFromPaths(region.points, region.properties);
}
}
}
// process the rest area.
void buildBackground(const Style& style)
{
BoundingBox bbox = utymap::index::GeoUtils::quadKeyToBoundingBox(quadKey_);
Path tileRect;
tileRect.push_back(IntPoint(bbox.minPoint.longitude*Scale, bbox.minPoint.latitude *Scale));
tileRect.push_back(IntPoint(bbox.maxPoint.longitude *Scale, bbox.minPoint.latitude *Scale));
tileRect.push_back(IntPoint(bbox.maxPoint.longitude *Scale, bbox.maxPoint.latitude*Scale));
tileRect.push_back(IntPoint(bbox.minPoint.longitude*Scale, bbox.maxPoint.latitude*Scale));
clipper_.AddPath(tileRect, ptSubject, true);
Paths background;
clipper_.Execute(ctDifference, background, pftPositive, pftPositive);
clipper_.Clear();
if (!background.empty())
populateMesh(createRegionProperties(style, ""), background);
}
void populateMesh(const Properties& properties, Paths& paths)
{
ClipperLib::SimplifyPolygons(paths);
ClipperLib::CleanPolygons(paths);
bool hasHeightOffset = properties.heightOffset > 0;
// calculate approximate size of overall points
auto size = 0;
for (auto i = 0; i < paths.size(); ++i) {
size += paths[i].size() * 1.5;
}
Polygon polygon(size);
for (const Path& path : paths) {
double area = ClipperLib::Area(path);
if (std::abs(area) < AreaTolerance) continue;
Points points = restorePoints(path);
if (area < 0)
polygon.addHole(points);
else
polygon.addContour(points);
}
if (!polygon.points.empty())
fillMesh(properties, polygon);
}
// restores mesh points from clipper points and injects new ones according to grid.
Points restorePoints(const Path& path)
{
int lastItemIndex = path.size() - 1;
Points points;
points.reserve(path.size());
for (int i = 0; i <= lastItemIndex; i++) {
splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);
}
return std::move(points);
}
void processHeightOffset(const std::vector<Points>& contours)
{
// TODO
}
void fillMesh(const Properties& properties, Polygon& polygon)
{
Mesh regionMesh = meshBuilder_.build(polygon, MeshBuilder::Options
{
/* area=*/ properties.maxArea,
/* elevation noise frequency*/ properties.eleNoiseFreq,
/* color noise frequency. */ properties.colorNoiseFreq,
styleProvider_.getGradient(properties.gradientKey),
/* segmentSplit=*/ 0
});
auto startVertIndex = mesh_.vertices.size() / 3;
mesh_.vertices.insert(mesh_.vertices.end(),
regionMesh.vertices.begin(),
regionMesh.vertices.end());
for (const auto& tri : regionMesh.triangles) {
mesh_.triangles.push_back(startVertIndex + tri);
}
mesh_.colors.insert(mesh_.colors.end(),
regionMesh.colors.begin(),
regionMesh.colors.end());
}
const StyleProvider& styleProvider_;
StringTable& stringTable_;
std::function<void(const Mesh&)> callback_;
ClipperEx clipper_;
ClipperOffset offset_;
LineGridSplitter splitter_;
MeshBuilder meshBuilder_;
QuadKey quadKey_;
Layers layers_;
Mesh mesh_;
};
void TerraBuilder::visitNode(const utymap::entities::Node& node) { pimpl_->visitNode(node); }
void TerraBuilder::visitWay(const utymap::entities::Way& way) { pimpl_->visitWay(way); }
void TerraBuilder::visitArea(const utymap::entities::Area& area) { pimpl_->visitArea(area); }
void TerraBuilder::visitRelation(const utymap::entities::Relation& relation) { pimpl_->visitRelation(relation); }
void TerraBuilder::prepare(const utymap::QuadKey& quadKey) { pimpl_->setQuadKey(quadKey); }
void TerraBuilder::complete() { pimpl_->build(); }
TerraBuilder::~TerraBuilder() { }
TerraBuilder::TerraBuilder(StringTable& stringTable, const StyleProvider& styleProvider, ElevationProvider& eleProvider,
std::function<void(const Mesh&)> callback) :
pimpl_(std::unique_ptr<TerraBuilder::TerraBuilderImpl>(new TerraBuilder::TerraBuilderImpl(stringTable, styleProvider, eleProvider, callback)))
{
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786)
#endif
#ifdef HAVE_CMATH
# include <cmath>
#else
# include <math.h>
#endif
#include <iostream>
#include <sstream>
#include "BZAdminClient.h"
#include "StateDatabase.h"
#include "TextUtils.h"
#include "version.h"
BZAdminClient::BZAdminClient(std::string callsign, std::string host,
int port, BZAdminUI* bzInterface)
: myTeam(ObserverTeam), sLink(Address(host), port), valid(false),
ui(bzInterface) {
if (sLink.getState() != ServerLink::Okay) {
std::cerr<<"Could not connect to "<<host<<':'<<port<<'.'<<std::endl;
return;
}
sLink.sendEnter(TankPlayer, myTeam, callsign.c_str(), "");
if (sLink.getState() != ServerLink::Okay) {
std::cerr<<"Rejected."<<std::endl;
return;
}
valid = true;
// tell BZDB to shut up, we can't have debug data printed to stdout
BZDB.setDebug(false);
// set a default message mask
showMessageType(MsgAddPlayer);
showMessageType(MsgKilled);
showMessageType(MsgMessage);
showMessageType(MsgNewRabbit);
showMessageType(MsgPause);
showMessageType(MsgRemovePlayer);
showMessageType(MsgSuperKill);
// initialise the colormap
colorMap[NoTeam] = Yellow;
colorMap[RogueTeam] = Yellow;
colorMap[RedTeam] = Red;
colorMap[GreenTeam] = Green;
colorMap[BlueTeam] = Blue;
colorMap[PurpleTeam] = Purple;
colorMap[ObserverTeam] = Cyan;
// initialise the msg type map
msgTypeMap["chat"] = MsgMessage;
msgTypeMap["join"] = MsgAddPlayer;
msgTypeMap["kill"] = MsgKilled;
msgTypeMap["leave"] = MsgRemovePlayer;
msgTypeMap["pause"] = MsgPause;
msgTypeMap["ping"] = MsgLagPing;
msgTypeMap["rabbit"] = MsgNewRabbit;
msgTypeMap["spawn"] = MsgAlive;
}
PlayerId BZAdminClient::getMyId() {
return sLink.getId();
}
BZAdminClient::ServerCode
BZAdminClient::getServerString(std::string& str, ColorCode& colorCode) {
uint16_t code, len;
char inbuf[MaxPacketLen];
std::string dstName, srcName;
int i;
PlayerIdMap::iterator iter;
std::string returnString = "";
/* read until we have a package that we want, or until there are no more
packages for 100 ms */
while (sLink.read(code, len, inbuf, 100) == 1) {
colorCode = Default;
void* vbuf = inbuf;
PlayerId p;
PlayerIdMap::const_iterator it;
std::string victimName, killerName;
switch (code) {
case MsgNewRabbit:
vbuf = nboUnpackUByte(vbuf, p);
returnString = "*** '" + players[p].name + "' is now the rabbit.";
break;
case MsgPause:
uint8_t paused;
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUByte(vbuf, paused);
returnString = "*** '" + players[p].name + "': " +
(paused ? "paused" : "resumed") + ".";
break;
case MsgAlive:
vbuf = nboUnpackUByte(vbuf, p);
returnString = "*** '" + players[p].name + "' has respawned.";
break;
case MsgLagPing:
returnString = "*** Received lag ping from server.";
break;
case MsgSetVar:
// code stolen from playing.cxx
uint16_t numVars;
uint8_t nameLen, valueLen;
char name[MaxPacketLen];
char value[MaxPacketLen];
vbuf = nboUnpackUShort(vbuf, numVars);
for (i = 0; i < numVars; i++) {
vbuf = nboUnpackUByte(vbuf, nameLen);
vbuf = nboUnpackString(vbuf, name, nameLen);
name[nameLen] = '\0';
vbuf = nboUnpackUByte(vbuf, valueLen);
vbuf = nboUnpackString(vbuf, value, valueLen);
value[valueLen] = '\0';
BZDB.set(name, value);
BZDB.setPersistent(name, false);
BZDB.setPermission(name, StateDatabase::Locked);
}
return NoMessage;
case MsgAddPlayer:
uint16_t team, type, wins, losses, tks;
char callsign[CallSignLen];
char email[EmailLen];
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUShort(vbuf, type);
vbuf = nboUnpackUShort(vbuf, team);
vbuf = nboUnpackUShort(vbuf, wins);
vbuf = nboUnpackUShort(vbuf, losses);
vbuf = nboUnpackUShort(vbuf, tks);
vbuf = nboUnpackString(vbuf, callsign, CallSignLen);
vbuf = nboUnpackString(vbuf, email, EmailLen);
players[p].name.resize(0);
players[p].name.append(callsign);
players[p].team = TeamColor(team);
players[p].wins = wins;
players[p].losses = losses;
players[p].tks = tks;
if (ui != NULL)
ui->addedPlayer(p);
returnString = returnString + "*** '" + callsign + "' joined the game.";
break;
case MsgRemovePlayer:
vbuf = nboUnpackUByte(vbuf, p);
returnString = returnString + "*** '" + players[p].name +
"' left the game.";
if (ui != NULL)
ui->removingPlayer(p);
players.erase(p);
break;
case MsgKilled:
PlayerId victim, killer;
int16_t shotId, reason;
vbuf = nboUnpackUByte(vbuf, victim);
vbuf = nboUnpackUByte(vbuf, killer);
vbuf = nboUnpackShort(vbuf, reason);
vbuf = nboUnpackShort(vbuf, shotId);
// find the player names and build a kill message string
it = players.find(victim);
victimName = (it != players.end() ? it->second.name : "<unknown>");
it = players.find(killer);
killerName = (it != players.end() ? it->second.name : "<unknown>");
returnString = "*** ";
returnString = returnString + "'" + victimName + "' ";
if (killer == victim)
returnString += "blew myself up.";
else
returnString = returnString + "destroyed by '" + killerName + "'.";
break;
case MsgSuperKill:
return Superkilled;
case MsgScore: {
uint8_t numScores;
vbuf = nboUnpackUByte(vbuf, numScores);
for (uint8_t i = 0; i < numScores; i++) {
uint16_t wins, losses, tks;
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUShort(vbuf, wins);
vbuf = nboUnpackUShort(vbuf, losses);
vbuf = nboUnpackUShort(vbuf, tks);
if ((iter = players.find(p)) != players.end()) {
iter->second.wins = wins;
iter->second.losses = losses;
iter->second.tks = tks;
}
}
return NoMessage;
}
case MsgMessage:
// unpack the message header
PlayerId src;
PlayerId dst;
PlayerId me = sLink.getId();
vbuf = nboUnpackUByte(vbuf, src);
vbuf = nboUnpackUByte(vbuf, dst);
returnString = std::string((char*)vbuf);
// parse playerlist
std::istringstream iss(returnString);
char c, d;
int pt;
if (iss >> c >> pt >> d) {
PlayerIdMap::iterator iter;
if (c == '[' && (iter = players.find(pt)) != players.end() && d == ']') {
std::vector<std::string> tokens = string_util::tokenize(returnString, " ");
if (!tokens.empty()) {
if (*tokens.rbegin() == "udp" || *tokens.rbegin() == "udp+")
tokens.pop_back();
if (tokens.size() >= 2) {
std::string callsign = *(++tokens.rbegin());
if (*callsign.rbegin() == ':') {
iter->second.ip = *tokens.rbegin();
}
}
}
}
}
// is the message for me?
TeamColor dstTeam = (dst >= 244 && dst <= 250 ?
TeamColor(250 - dst) : NoTeam);
if (dst == AllPlayers || src == me || dst == me || dstTeam == myTeam) {
if (returnString == "CLIENTQUERY") {
sendMessage(std::string("bzadmin ") + getAppVersion(), src);
if (ui != NULL)
ui->outputMessage(" [Sent versioninfo per request]", Default);
return NoMessage;
}
else {
returnString = formatMessage((char*)vbuf, src, dst, dstTeam, me);
PlayerIdMap::const_iterator iter = players.find(src);
colorCode = (iter == players.end() ?
colorMap[NoTeam] : colorMap[iter->second.team]);
}
}
break;
}
if (messageMask[code]) {
str = returnString;
return GotMessage;
}
}
if (sLink.getState() != ServerLink::Okay) {
str = returnString;
return CommError;
}
return NoMessage;
}
BZAdminClient::ServerCode
BZAdminClient::getServerString(std::string& str) {
ColorCode cc;
return getServerString(str, cc);
}
PlayerIdMap& BZAdminClient::getPlayers() {
return players;
}
bool BZAdminClient::isValid() const {
return valid;
}
void BZAdminClient::runLoop() {
std::string str;
ColorCode color;
ServerCode what(NoMessage);
while (true) {
while ((what = getServerString(str, color)) == GotMessage) {
if (ui != NULL)
ui->outputMessage(str, color);
}
if (what == Superkilled || what == CommError)
break;
if (ui != NULL && ui->checkCommand(str)) {
if (str == "/quit")
break;
sendMessage(str, ui->getTarget());
}
}
// why did we leave the loop?
switch (what) {
case Superkilled:
if (ui != NULL)
ui->outputMessage("--- ERROR: Server forced disconnect", Red);
break;
case CommError:
if (ui != NULL)
ui->outputMessage("--- ERROR: Connection to server lost", Red);
break;
default:
waitForServer();
}
}
void BZAdminClient::sendMessage(const std::string& msg,
PlayerId target) {
// local commands:
// /set lists all BZDB variables
if (msg == "/set") {
if (ui != NULL)
BZDB.iterate(listSetVars, this);
return;
}
char buffer[MessageLen];
char buffer2[1 + MessageLen];
void* buf = buffer2;
buf = nboPackUByte(buf, target);
memset(buffer, 0, MessageLen);
strncpy(buffer, msg.c_str(), MessageLen - 1);
nboPackString(buffer2 + 1, buffer, MessageLen);
sLink.send(MsgMessage, sizeof(buffer2), buffer2);
}
std::string BZAdminClient::formatMessage(const std::string& msg, PlayerId src,
PlayerId dst, TeamColor dstTeam,
PlayerId me) {
std::string formatted = " ";
// get sender and receiver
const std::string srcName = (src == ServerPlayer ? "SERVER" :
(players.count(src) ? players[src].name :
"(UNKNOWN)"));
const std::string dstName = (players.count(dst) ? players[dst].name :
"(UNKNOWN)");
// direct message to or from me
if (dst == me || players.count(dst)) {
if (!(src == me && dst == me)) {
formatted += "[";
if (src == me) {
formatted += "->";
formatted += dstName;
}
else {
formatted += srcName;
formatted += "->";
}
formatted += "] ";
}
formatted += msg;
}
// public or team message
else {
if (dstTeam != NoTeam)
formatted += "[Team] ";
formatted += srcName;
formatted += ": ";
formatted += msg;
}
return formatted;
}
void BZAdminClient::setUI(BZAdminUI* bzInterface) {
ui = bzInterface;
}
void BZAdminClient::waitForServer() {
// we need to know that the server has processed all our messages
// send a private message to ourself and wait for it to come back
// this assumes that the order of messages isn't changed along the way
bool tmp = messageMask[MsgMessage];
messageMask[MsgMessage] = true;
PlayerId me = sLink.getId();
if (sLink.getState() == ServerLink::Okay) {
sendMessage("bzadminping", me);
std::string expected = formatMessage("bzadminping", me, me, NoTeam, me);
std::string str;
do {
getServerString(str);
} while (str != expected);
}
messageMask[MsgMessage] = tmp;
}
void BZAdminClient::ignoreMessageType(uint16_t type) {
messageMask[type] = false;
}
void BZAdminClient::showMessageType(uint16_t type) {
messageMask[type] = true;
}
void BZAdminClient::ignoreMessageType(std::string type) {
ignoreMessageType(msgTypeMap[type]);
}
void BZAdminClient::showMessageType(std::string type) {
showMessageType(msgTypeMap[type]);
}
void BZAdminClient::listSetVars(const std::string& name, void* thisObject) {
char message[MessageLen];
if (BZDB.getPermission(name) == StateDatabase::Locked) {
sprintf(message, "/set %s %f", name.c_str(), BZDB.eval(name));
((BZAdminClient*)thisObject)->ui->outputMessage(message, Default);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Don't let bzadmin send empty lines<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786)
#endif
#ifdef HAVE_CMATH
# include <cmath>
#else
# include <math.h>
#endif
#include <iostream>
#include <sstream>
#include "BZAdminClient.h"
#include "StateDatabase.h"
#include "TextUtils.h"
#include "version.h"
BZAdminClient::BZAdminClient(std::string callsign, std::string host,
int port, BZAdminUI* bzInterface)
: myTeam(ObserverTeam), sLink(Address(host), port), valid(false),
ui(bzInterface) {
if (sLink.getState() != ServerLink::Okay) {
std::cerr<<"Could not connect to "<<host<<':'<<port<<'.'<<std::endl;
return;
}
sLink.sendEnter(TankPlayer, myTeam, callsign.c_str(), "");
if (sLink.getState() != ServerLink::Okay) {
std::cerr<<"Rejected."<<std::endl;
return;
}
valid = true;
// tell BZDB to shut up, we can't have debug data printed to stdout
BZDB.setDebug(false);
// set a default message mask
showMessageType(MsgAddPlayer);
showMessageType(MsgKilled);
showMessageType(MsgMessage);
showMessageType(MsgNewRabbit);
showMessageType(MsgPause);
showMessageType(MsgRemovePlayer);
showMessageType(MsgSuperKill);
// initialise the colormap
colorMap[NoTeam] = Yellow;
colorMap[RogueTeam] = Yellow;
colorMap[RedTeam] = Red;
colorMap[GreenTeam] = Green;
colorMap[BlueTeam] = Blue;
colorMap[PurpleTeam] = Purple;
colorMap[ObserverTeam] = Cyan;
// initialise the msg type map
msgTypeMap["chat"] = MsgMessage;
msgTypeMap["join"] = MsgAddPlayer;
msgTypeMap["kill"] = MsgKilled;
msgTypeMap["leave"] = MsgRemovePlayer;
msgTypeMap["pause"] = MsgPause;
msgTypeMap["ping"] = MsgLagPing;
msgTypeMap["rabbit"] = MsgNewRabbit;
msgTypeMap["spawn"] = MsgAlive;
}
PlayerId BZAdminClient::getMyId() {
return sLink.getId();
}
BZAdminClient::ServerCode
BZAdminClient::getServerString(std::string& str, ColorCode& colorCode) {
uint16_t code, len;
char inbuf[MaxPacketLen];
std::string dstName, srcName;
int i;
PlayerIdMap::iterator iter;
std::string returnString = "";
/* read until we have a package that we want, or until there are no more
packages for 100 ms */
while (sLink.read(code, len, inbuf, 100) == 1) {
colorCode = Default;
void* vbuf = inbuf;
PlayerId p;
PlayerIdMap::const_iterator it;
std::string victimName, killerName;
switch (code) {
case MsgNewRabbit:
vbuf = nboUnpackUByte(vbuf, p);
returnString = "*** '" + players[p].name + "' is now the rabbit.";
break;
case MsgPause:
uint8_t paused;
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUByte(vbuf, paused);
returnString = "*** '" + players[p].name + "': " +
(paused ? "paused" : "resumed") + ".";
break;
case MsgAlive:
vbuf = nboUnpackUByte(vbuf, p);
returnString = "*** '" + players[p].name + "' has respawned.";
break;
case MsgLagPing:
returnString = "*** Received lag ping from server.";
break;
case MsgSetVar:
// code stolen from playing.cxx
uint16_t numVars;
uint8_t nameLen, valueLen;
char name[MaxPacketLen];
char value[MaxPacketLen];
vbuf = nboUnpackUShort(vbuf, numVars);
for (i = 0; i < numVars; i++) {
vbuf = nboUnpackUByte(vbuf, nameLen);
vbuf = nboUnpackString(vbuf, name, nameLen);
name[nameLen] = '\0';
vbuf = nboUnpackUByte(vbuf, valueLen);
vbuf = nboUnpackString(vbuf, value, valueLen);
value[valueLen] = '\0';
BZDB.set(name, value);
BZDB.setPersistent(name, false);
BZDB.setPermission(name, StateDatabase::Locked);
}
return NoMessage;
case MsgAddPlayer:
uint16_t team, type, wins, losses, tks;
char callsign[CallSignLen];
char email[EmailLen];
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUShort(vbuf, type);
vbuf = nboUnpackUShort(vbuf, team);
vbuf = nboUnpackUShort(vbuf, wins);
vbuf = nboUnpackUShort(vbuf, losses);
vbuf = nboUnpackUShort(vbuf, tks);
vbuf = nboUnpackString(vbuf, callsign, CallSignLen);
vbuf = nboUnpackString(vbuf, email, EmailLen);
players[p].name.resize(0);
players[p].name.append(callsign);
players[p].team = TeamColor(team);
players[p].wins = wins;
players[p].losses = losses;
players[p].tks = tks;
if (ui != NULL)
ui->addedPlayer(p);
returnString = returnString + "*** '" + callsign + "' joined the game.";
break;
case MsgRemovePlayer:
vbuf = nboUnpackUByte(vbuf, p);
returnString = returnString + "*** '" + players[p].name +
"' left the game.";
if (ui != NULL)
ui->removingPlayer(p);
players.erase(p);
break;
case MsgKilled:
PlayerId victim, killer;
int16_t shotId, reason;
vbuf = nboUnpackUByte(vbuf, victim);
vbuf = nboUnpackUByte(vbuf, killer);
vbuf = nboUnpackShort(vbuf, reason);
vbuf = nboUnpackShort(vbuf, shotId);
// find the player names and build a kill message string
it = players.find(victim);
victimName = (it != players.end() ? it->second.name : "<unknown>");
it = players.find(killer);
killerName = (it != players.end() ? it->second.name : "<unknown>");
returnString = "*** ";
returnString = returnString + "'" + victimName + "' ";
if (killer == victim)
returnString += "blew myself up.";
else
returnString = returnString + "destroyed by '" + killerName + "'.";
break;
case MsgSuperKill:
return Superkilled;
case MsgScore: {
uint8_t numScores;
vbuf = nboUnpackUByte(vbuf, numScores);
for (uint8_t i = 0; i < numScores; i++) {
uint16_t wins, losses, tks;
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUShort(vbuf, wins);
vbuf = nboUnpackUShort(vbuf, losses);
vbuf = nboUnpackUShort(vbuf, tks);
if ((iter = players.find(p)) != players.end()) {
iter->second.wins = wins;
iter->second.losses = losses;
iter->second.tks = tks;
}
}
return NoMessage;
}
case MsgMessage:
// unpack the message header
PlayerId src;
PlayerId dst;
PlayerId me = sLink.getId();
vbuf = nboUnpackUByte(vbuf, src);
vbuf = nboUnpackUByte(vbuf, dst);
returnString = std::string((char*)vbuf);
// parse playerlist
std::istringstream iss(returnString);
char c, d;
int pt;
if (iss >> c >> pt >> d) {
PlayerIdMap::iterator iter;
if (c == '[' && (iter = players.find(pt)) != players.end() && d == ']') {
std::vector<std::string> tokens = string_util::tokenize(returnString, " ");
if (!tokens.empty()) {
if (*tokens.rbegin() == "udp" || *tokens.rbegin() == "udp+")
tokens.pop_back();
if (tokens.size() >= 2) {
std::string callsign = *(++tokens.rbegin());
if (*callsign.rbegin() == ':') {
iter->second.ip = *tokens.rbegin();
}
}
}
}
}
// is the message for me?
TeamColor dstTeam = (dst >= 244 && dst <= 250 ?
TeamColor(250 - dst) : NoTeam);
if (dst == AllPlayers || src == me || dst == me || dstTeam == myTeam) {
if (returnString == "CLIENTQUERY") {
sendMessage(std::string("bzadmin ") + getAppVersion(), src);
if (ui != NULL)
ui->outputMessage(" [Sent versioninfo per request]", Default);
return NoMessage;
}
else {
returnString = formatMessage((char*)vbuf, src, dst, dstTeam, me);
PlayerIdMap::const_iterator iter = players.find(src);
colorCode = (iter == players.end() ?
colorMap[NoTeam] : colorMap[iter->second.team]);
}
}
break;
}
if (messageMask[code]) {
str = returnString;
return GotMessage;
}
}
if (sLink.getState() != ServerLink::Okay) {
str = returnString;
return CommError;
}
return NoMessage;
}
BZAdminClient::ServerCode
BZAdminClient::getServerString(std::string& str) {
ColorCode cc;
return getServerString(str, cc);
}
PlayerIdMap& BZAdminClient::getPlayers() {
return players;
}
bool BZAdminClient::isValid() const {
return valid;
}
void BZAdminClient::runLoop() {
std::string str;
ColorCode color;
ServerCode what(NoMessage);
while (true) {
while ((what = getServerString(str, color)) == GotMessage) {
if (ui != NULL)
ui->outputMessage(str, color);
}
if (what == Superkilled || what == CommError)
break;
if (ui != NULL && ui->checkCommand(str)) {
if (str == "/quit")
break;
if (str != "")
sendMessage(str, ui->getTarget());
}
}
// why did we leave the loop?
switch (what) {
case Superkilled:
if (ui != NULL)
ui->outputMessage("--- ERROR: Server forced disconnect", Red);
break;
case CommError:
if (ui != NULL)
ui->outputMessage("--- ERROR: Connection to server lost", Red);
break;
default:
waitForServer();
}
}
void BZAdminClient::sendMessage(const std::string& msg,
PlayerId target) {
// local commands:
// /set lists all BZDB variables
if (msg == "/set") {
if (ui != NULL)
BZDB.iterate(listSetVars, this);
return;
}
char buffer[MessageLen];
char buffer2[1 + MessageLen];
void* buf = buffer2;
buf = nboPackUByte(buf, target);
memset(buffer, 0, MessageLen);
strncpy(buffer, msg.c_str(), MessageLen - 1);
nboPackString(buffer2 + 1, buffer, MessageLen);
sLink.send(MsgMessage, sizeof(buffer2), buffer2);
}
std::string BZAdminClient::formatMessage(const std::string& msg, PlayerId src,
PlayerId dst, TeamColor dstTeam,
PlayerId me) {
std::string formatted = " ";
// get sender and receiver
const std::string srcName = (src == ServerPlayer ? "SERVER" :
(players.count(src) ? players[src].name :
"(UNKNOWN)"));
const std::string dstName = (players.count(dst) ? players[dst].name :
"(UNKNOWN)");
// direct message to or from me
if (dst == me || players.count(dst)) {
if (!(src == me && dst == me)) {
formatted += "[";
if (src == me) {
formatted += "->";
formatted += dstName;
}
else {
formatted += srcName;
formatted += "->";
}
formatted += "] ";
}
formatted += msg;
}
// public or team message
else {
if (dstTeam != NoTeam)
formatted += "[Team] ";
formatted += srcName;
formatted += ": ";
formatted += msg;
}
return formatted;
}
void BZAdminClient::setUI(BZAdminUI* bzInterface) {
ui = bzInterface;
}
void BZAdminClient::waitForServer() {
// we need to know that the server has processed all our messages
// send a private message to ourself and wait for it to come back
// this assumes that the order of messages isn't changed along the way
bool tmp = messageMask[MsgMessage];
messageMask[MsgMessage] = true;
PlayerId me = sLink.getId();
if (sLink.getState() == ServerLink::Okay) {
sendMessage("bzadminping", me);
std::string expected = formatMessage("bzadminping", me, me, NoTeam, me);
std::string str;
do {
getServerString(str);
} while (str != expected);
}
messageMask[MsgMessage] = tmp;
}
void BZAdminClient::ignoreMessageType(uint16_t type) {
messageMask[type] = false;
}
void BZAdminClient::showMessageType(uint16_t type) {
messageMask[type] = true;
}
void BZAdminClient::ignoreMessageType(std::string type) {
ignoreMessageType(msgTypeMap[type]);
}
void BZAdminClient::showMessageType(std::string type) {
showMessageType(msgTypeMap[type]);
}
void BZAdminClient::listSetVars(const std::string& name, void* thisObject) {
char message[MessageLen];
if (BZDB.getPermission(name) == StateDatabase::Locked) {
sprintf(message, "/set %s %f", name.c_str(), BZDB.eval(name));
((BZAdminClient*)thisObject)->ui->outputMessage(message, Default);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786)
#endif
#ifdef HAVE_CMATH
# include <cmath>
#else
# include <math.h>
#endif
#include <iostream>
#include <sstream>
#include "BZAdminClient.h"
#include "BZAdminUI.h"
#include "StateDatabase.h"
#include "TextUtils.h"
#include "version.h"
BZAdminClient::BZAdminClient(std::string callsign, std::string host,
int port, BZAdminUI* bzInterface)
: myTeam(ObserverTeam), sLink(Address(host), port), valid(false),
ui(bzInterface) {
if (sLink.getState() != ServerLink::Okay) {
std::cerr<<"Could not connect to "<<host<<':'<<port<<'.'<<std::endl;
return;
}
sLink.sendEnter(TankPlayer, myTeam, callsign.c_str(), "");
if (sLink.getState() != ServerLink::Okay) {
std::cerr<<"Rejected."<<std::endl;
return;
}
valid = true;
// tell BZDB to shut up, we can't have debug data printed to stdout
BZDB.setDebug(false);
// set a default message mask
showMessageType(MsgAddPlayer);
showMessageType(MsgKilled);
showMessageType(MsgMessage);
showMessageType(MsgNewRabbit);
showMessageType(MsgPause);
showMessageType(MsgRemovePlayer);
showMessageType(MsgSuperKill);
// initialise the colormap
colorMap[NoTeam] = Yellow;
colorMap[RogueTeam] = Yellow;
colorMap[RedTeam] = Red;
colorMap[GreenTeam] = Green;
colorMap[BlueTeam] = Blue;
colorMap[PurpleTeam] = Purple;
colorMap[ObserverTeam] = Cyan;
// initialise the msg type map
msgTypeMap["bzdb"] = MsgSetVar;
msgTypeMap["chat"] = MsgMessage;
msgTypeMap["admin"] = MsgAdminInfo;
msgTypeMap["join"] = MsgAddPlayer;
msgTypeMap["kill"] = MsgKilled;
msgTypeMap["leave"] = MsgRemovePlayer;
msgTypeMap["pause"] = MsgPause;
msgTypeMap["ping"] = MsgLagPing;
msgTypeMap["rabbit"] = MsgNewRabbit;
msgTypeMap["score"] = MsgScore;
msgTypeMap["spawn"] = MsgAlive;
}
PlayerId BZAdminClient::getMyId() {
return sLink.getId();
}
BZAdminClient::ServerCode BZAdminClient::checkMessage() {
uint16_t code, len;
char inbuf[MaxPacketLen];
std::string dstName, srcName;
int i;
PlayerIdMap::iterator iter;
// read until we have a package, or until we have waited 100 ms
if (sLink.read(code, len, inbuf, 100) == 1) {
lastMessage.first = "";
lastMessage.second = Default;
void* vbuf = inbuf;
PlayerId p;
PlayerIdMap::const_iterator it;
std::string victimName, killerName;
Address a;
switch (code) {
case MsgNewRabbit:
if (messageMask[MsgNewRabbit]) {
vbuf = nboUnpackUByte(vbuf, p);
lastMessage.first = std::string("*** '") + players[p].name +
"' is now the rabbit.";
}
break;
case MsgPause:
if (messageMask[MsgPause]) {
uint8_t paused;
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUByte(vbuf, paused);
lastMessage.first = std::string("*** '") + players[p].name + "': " +
(paused ? "paused" : "resumed") + ".";
}
break;
case MsgAlive:
if (messageMask[MsgAlive]) {
vbuf = nboUnpackUByte(vbuf, p);
lastMessage.first = std::string("*** '") + players[p].name +
"' has respawned.";
}
break;
case MsgLagPing:
if (messageMask[MsgLagPing])
lastMessage.first = "*** Received lag ping from server.";
break;
case MsgSetVar:
// code stolen from playing.cxx
uint16_t numVars;
uint8_t nameLen, valueLen;
char name[MaxPacketLen];
char value[MaxPacketLen];
vbuf = nboUnpackUShort(vbuf, numVars);
for (i = 0; i < numVars; i++) {
vbuf = nboUnpackUByte(vbuf, nameLen);
vbuf = nboUnpackString(vbuf, name, nameLen);
name[nameLen] = '\0';
vbuf = nboUnpackUByte(vbuf, valueLen);
vbuf = nboUnpackString(vbuf, value, valueLen);
value[valueLen] = '\0';
BZDB.set(name, value);
BZDB.setPersistent(name, false);
BZDB.setPermission(name, StateDatabase::Locked);
}
if (messageMask[MsgSetVar]) {
lastMessage.first = std::string("*** Received BZDB update, ") +
string_util::format("%d", numVars) + " variable" +
(numVars == 1 ? "" : "s") + " updated.";
}
break;
case MsgAddPlayer:
uint16_t team, type, wins, losses, tks;
char callsign[CallSignLen];
char email[EmailLen];
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUShort(vbuf, type);
vbuf = nboUnpackUShort(vbuf, team);
vbuf = nboUnpackUShort(vbuf, wins);
vbuf = nboUnpackUShort(vbuf, losses);
vbuf = nboUnpackUShort(vbuf, tks);
vbuf = nboUnpackString(vbuf, callsign, CallSignLen);
vbuf = nboUnpackString(vbuf, email, EmailLen);
players[p].name.resize(0);
players[p].name.append(callsign);
players[p].team = TeamColor(team);
players[p].wins = wins;
players[p].losses = losses;
players[p].tks = tks;
if (ui != NULL)
ui->addedPlayer(p);
if (messageMask[MsgAddPlayer]) {
lastMessage.first = std::string("*** '") + callsign +
"' joined the game.";
}
break;
case MsgRemovePlayer:
vbuf = nboUnpackUByte(vbuf, p);
if (ui != NULL)
ui->removingPlayer(p);
players.erase(p);
if (messageMask[MsgRemovePlayer]) {
lastMessage.first = std::string("*** '") + players[p].name +
"' left the game.";
}
break;
case MsgAdminInfo: {
uint8_t numIPs;
uint8_t tmp;
vbuf = nboUnpackUByte(vbuf, numIPs);
for (int i = 0; i < numIPs; ++i) {
vbuf = nboUnpackUByte(vbuf, tmp);
vbuf = nboUnpackUByte(vbuf, p);
// FIXME - actually parse the bitfield
vbuf = nboUnpackUByte(vbuf, tmp);
vbuf = a.unpack(vbuf);
players[p].ip = a.getDotNotation();
}
lastMessage.first = std::string("*** IP update received, ") +
string_util::format("%d", numIPs) + " IP" + (numIPs == 1 ? "" : "s") +
" updated.";
}
break;
case MsgKilled:
if (messageMask[MsgKilled]) {
PlayerId victim, killer;
int16_t shotId, reason;
vbuf = nboUnpackUByte(vbuf, victim);
vbuf = nboUnpackUByte(vbuf, killer);
vbuf = nboUnpackShort(vbuf, reason);
vbuf = nboUnpackShort(vbuf, shotId);
// find the player names and build a kill message string
it = players.find(victim);
victimName = (it != players.end() ? it->second.name : "<unknown>");
it = players.find(killer);
killerName = (it != players.end() ? it->second.name : "<unknown>");
lastMessage.first = std::string("*** ") + "'" + victimName + "' ";
if (killer == victim) {
lastMessage.first = lastMessage.first + "blew myself up.";
}
else {
lastMessage.first = lastMessage.first + "destroyed by '" +
killerName + "'.";
}
}
break;
case MsgSuperKill:
return Superkilled;
case MsgScore: {
uint8_t numScores;
vbuf = nboUnpackUByte(vbuf, numScores);
for (uint8_t i = 0; i < numScores; i++) {
uint16_t wins, losses, tks;
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUShort(vbuf, wins);
vbuf = nboUnpackUShort(vbuf, losses);
vbuf = nboUnpackUShort(vbuf, tks);
if ((iter = players.find(p)) != players.end()) {
iter->second.wins = wins;
iter->second.losses = losses;
iter->second.tks = tks;
}
}
if (messageMask[MsgScore]) {
lastMessage.first =
std::string("*** Received score update, score for ")+
string_util::format("%d", numScores) + " player" +
(numScores == 1 ? "s" : "") + " updated.";
}
break;
}
case MsgMessage:
// unpack the message header
PlayerId src;
PlayerId dst;
PlayerId me = sLink.getId();
vbuf = nboUnpackUByte(vbuf, src);
vbuf = nboUnpackUByte(vbuf, dst);
// is the message for me?
TeamColor dstTeam = (dst >= 244 && dst <= 250 ?
TeamColor(250 - dst) : NoTeam);
if (dst == AllPlayers || src == me || dst == me || dstTeam == myTeam) {
if (strcmp("CLIENTQUERY", (char*)vbuf) == 0) {
sendMessage(std::string("bzadmin ") + getAppVersion(), src);
lastMessage.first = " [Sent versioninfo per request]";
break;
}
else if (messageMask[MsgMessage]) {
lastMessage.first = formatMessage((char*)vbuf, src, dst,dstTeam, me);
PlayerIdMap::const_iterator iter = players.find(src);
lastMessage.second = (iter == players.end() ?
colorMap[NoTeam] :
colorMap[iter->second.team]);
}
}
break;
}
if (ui != NULL)
ui->handleNewPacket(code);
return GotMessage;
}
if (sLink.getState() != ServerLink::Okay) {
if (ui != NULL)
ui->outputMessage("--- ERROR: Communication error", Red);
return CommError;
}
return NoMessage;
}
std::pair<std::string, ColorCode> BZAdminClient::getLastMessage() const {
return lastMessage;
}
PlayerIdMap& BZAdminClient::getPlayers() {
return players;
}
bool BZAdminClient::isValid() const {
return valid;
}
void BZAdminClient::runLoop() {
std::string cmd;
ServerCode what(NoMessage);
while (true) {
what = checkMessage();
if (what == Superkilled || what == CommError)
break;
if (ui != NULL && ui->checkCommand(cmd)) {
if (cmd == "/quit")
break;
if (cmd != "")
sendMessage(cmd, ui->getTarget());
}
}
// why did we leave the loop?
switch (what) {
case Superkilled:
lastMessage.first = "--- ERROR: Server forced disconnect";
lastMessage.second = Red;
break;
case CommError:
lastMessage.first = "--- ERROR: Connection to server lost";
lastMessage.second = Red;
break;
default:
waitForServer();
}
}
void BZAdminClient::sendMessage(const std::string& msg,
PlayerId target) {
// local commands:
// /set lists all BZDB variables
if (msg == "/set") {
if (ui != NULL)
BZDB.iterate(listSetVars, this);
return;
}
char buffer[MessageLen];
char buffer2[1 + MessageLen];
void* buf = buffer2;
buf = nboPackUByte(buf, target);
memset(buffer, 0, MessageLen);
strncpy(buffer, msg.c_str(), MessageLen - 1);
nboPackString(buffer2 + 1, buffer, MessageLen);
sLink.send(MsgMessage, sizeof(buffer2), buffer2);
}
std::string BZAdminClient::formatMessage(const std::string& msg, PlayerId src,
PlayerId dst, TeamColor dstTeam,
PlayerId me) {
std::string formatted = " ";
// get sender and receiver
const std::string srcName = (src == ServerPlayer ? "SERVER" :
(players.count(src) ? players[src].name :
"(UNKNOWN)"));
const std::string dstName = (players.count(dst) ? players[dst].name :
"(UNKNOWN)");
// direct message to or from me
if (dst == me || players.count(dst)) {
if (!(src == me && dst == me)) {
formatted += "[";
if (src == me) {
formatted += "->";
formatted += dstName;
}
else {
formatted += srcName;
formatted += "->";
}
formatted += "] ";
}
formatted += msg;
}
// public or team message
else {
if (dstTeam != NoTeam)
formatted += "[Team] ";
formatted += srcName;
formatted += ": ";
formatted += msg;
}
return formatted;
}
void BZAdminClient::setUI(BZAdminUI* bzInterface) {
ui = bzInterface;
}
void BZAdminClient::waitForServer() {
// we need to know that the server has processed all our messages
// send a private message to ourself and wait for it to come back
// this assumes that the order of messages isn't changed along the way
bool tmp = messageMask[MsgMessage];
messageMask[MsgMessage] = true;
PlayerId me = sLink.getId();
if (sLink.getState() == ServerLink::Okay) {
sendMessage("bzadminping", me);
std::string expected = formatMessage("bzadminping", me, me, NoTeam, me);
std::string str;
BZAdminUI* tmpUI = ui;
ui = NULL;
do {
checkMessage();
} while (lastMessage.first != expected);
ui = tmpUI;
}
messageMask[MsgMessage] = tmp;
}
void BZAdminClient::ignoreMessageType(uint16_t type) {
messageMask[type] = false;
}
void BZAdminClient::showMessageType(uint16_t type) {
messageMask[type] = true;
}
void BZAdminClient::ignoreMessageType(std::string type) {
ignoreMessageType(msgTypeMap[type]);
}
void BZAdminClient::showMessageType(std::string type) {
showMessageType(msgTypeMap[type]);
}
void BZAdminClient::listSetVars(const std::string& name, void* thisObject) {
char message[MessageLen];
if (BZDB.getPermission(name) == StateDatabase::Locked) {
sprintf(message, "/set %s %f", name.c_str(), BZDB.eval(name));
((BZAdminClient*)thisObject)->ui->outputMessage(message, Default);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>allow 'left' messages to use the player's name<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786)
#endif
#ifdef HAVE_CMATH
# include <cmath>
#else
# include <math.h>
#endif
#include <iostream>
#include <sstream>
#include "BZAdminClient.h"
#include "BZAdminUI.h"
#include "StateDatabase.h"
#include "TextUtils.h"
#include "version.h"
BZAdminClient::BZAdminClient(std::string callsign, std::string host,
int port, BZAdminUI* bzInterface)
: myTeam(ObserverTeam), sLink(Address(host), port), valid(false),
ui(bzInterface) {
if (sLink.getState() != ServerLink::Okay) {
std::cerr<<"Could not connect to "<<host<<':'<<port<<'.'<<std::endl;
return;
}
sLink.sendEnter(TankPlayer, myTeam, callsign.c_str(), "");
if (sLink.getState() != ServerLink::Okay) {
std::cerr<<"Rejected."<<std::endl;
return;
}
valid = true;
// tell BZDB to shut up, we can't have debug data printed to stdout
BZDB.setDebug(false);
// set a default message mask
showMessageType(MsgAddPlayer);
showMessageType(MsgKilled);
showMessageType(MsgMessage);
showMessageType(MsgNewRabbit);
showMessageType(MsgPause);
showMessageType(MsgRemovePlayer);
showMessageType(MsgSuperKill);
// initialise the colormap
colorMap[NoTeam] = Yellow;
colorMap[RogueTeam] = Yellow;
colorMap[RedTeam] = Red;
colorMap[GreenTeam] = Green;
colorMap[BlueTeam] = Blue;
colorMap[PurpleTeam] = Purple;
colorMap[ObserverTeam] = Cyan;
// initialise the msg type map
msgTypeMap["bzdb"] = MsgSetVar;
msgTypeMap["chat"] = MsgMessage;
msgTypeMap["admin"] = MsgAdminInfo;
msgTypeMap["join"] = MsgAddPlayer;
msgTypeMap["kill"] = MsgKilled;
msgTypeMap["leave"] = MsgRemovePlayer;
msgTypeMap["pause"] = MsgPause;
msgTypeMap["ping"] = MsgLagPing;
msgTypeMap["rabbit"] = MsgNewRabbit;
msgTypeMap["score"] = MsgScore;
msgTypeMap["spawn"] = MsgAlive;
}
PlayerId BZAdminClient::getMyId() {
return sLink.getId();
}
BZAdminClient::ServerCode BZAdminClient::checkMessage() {
uint16_t code, len;
char inbuf[MaxPacketLen];
std::string dstName, srcName;
int i;
PlayerIdMap::iterator iter;
// read until we have a package, or until we have waited 100 ms
if (sLink.read(code, len, inbuf, 100) == 1) {
lastMessage.first = "";
lastMessage.second = Default;
void* vbuf = inbuf;
PlayerId p;
PlayerIdMap::const_iterator it;
std::string victimName, killerName;
Address a;
switch (code) {
case MsgNewRabbit:
if (messageMask[MsgNewRabbit]) {
vbuf = nboUnpackUByte(vbuf, p);
lastMessage.first = std::string("*** '") + players[p].name +
"' is now the rabbit.";
}
break;
case MsgPause:
if (messageMask[MsgPause]) {
uint8_t paused;
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUByte(vbuf, paused);
lastMessage.first = std::string("*** '") + players[p].name + "': " +
(paused ? "paused" : "resumed") + ".";
}
break;
case MsgAlive:
if (messageMask[MsgAlive]) {
vbuf = nboUnpackUByte(vbuf, p);
lastMessage.first = std::string("*** '") + players[p].name +
"' has respawned.";
}
break;
case MsgLagPing:
if (messageMask[MsgLagPing])
lastMessage.first = "*** Received lag ping from server.";
break;
case MsgSetVar:
// code stolen from playing.cxx
uint16_t numVars;
uint8_t nameLen, valueLen;
char name[MaxPacketLen];
char value[MaxPacketLen];
vbuf = nboUnpackUShort(vbuf, numVars);
for (i = 0; i < numVars; i++) {
vbuf = nboUnpackUByte(vbuf, nameLen);
vbuf = nboUnpackString(vbuf, name, nameLen);
name[nameLen] = '\0';
vbuf = nboUnpackUByte(vbuf, valueLen);
vbuf = nboUnpackString(vbuf, value, valueLen);
value[valueLen] = '\0';
BZDB.set(name, value);
BZDB.setPersistent(name, false);
BZDB.setPermission(name, StateDatabase::Locked);
}
if (messageMask[MsgSetVar]) {
lastMessage.first = std::string("*** Received BZDB update, ") +
string_util::format("%d", numVars) + " variable" +
(numVars == 1 ? "" : "s") + " updated.";
}
break;
case MsgAddPlayer:
uint16_t team, type, wins, losses, tks;
char callsign[CallSignLen];
char email[EmailLen];
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUShort(vbuf, type);
vbuf = nboUnpackUShort(vbuf, team);
vbuf = nboUnpackUShort(vbuf, wins);
vbuf = nboUnpackUShort(vbuf, losses);
vbuf = nboUnpackUShort(vbuf, tks);
vbuf = nboUnpackString(vbuf, callsign, CallSignLen);
vbuf = nboUnpackString(vbuf, email, EmailLen);
players[p].name.resize(0);
players[p].name.append(callsign);
players[p].team = TeamColor(team);
players[p].wins = wins;
players[p].losses = losses;
players[p].tks = tks;
if (ui != NULL)
ui->addedPlayer(p);
if (messageMask[MsgAddPlayer]) {
lastMessage.first = std::string("*** '") + callsign +
"' joined the game.";
}
break;
case MsgRemovePlayer:
vbuf = nboUnpackUByte(vbuf, p);
if (ui != NULL)
ui->removingPlayer(p);
if (messageMask[MsgRemovePlayer]) {
lastMessage.first = std::string("*** '") + players[p].name +
"' left the game.";
}
players.erase(p);
break;
case MsgAdminInfo: {
uint8_t numIPs;
uint8_t tmp;
vbuf = nboUnpackUByte(vbuf, numIPs);
for (int i = 0; i < numIPs; ++i) {
vbuf = nboUnpackUByte(vbuf, tmp);
vbuf = nboUnpackUByte(vbuf, p);
// FIXME - actually parse the bitfield
vbuf = nboUnpackUByte(vbuf, tmp);
vbuf = a.unpack(vbuf);
players[p].ip = a.getDotNotation();
}
lastMessage.first = std::string("*** IP update received, ") +
string_util::format("%d", numIPs) + " IP" + (numIPs == 1 ? "" : "s") +
" updated.";
}
break;
case MsgKilled:
if (messageMask[MsgKilled]) {
PlayerId victim, killer;
int16_t shotId, reason;
vbuf = nboUnpackUByte(vbuf, victim);
vbuf = nboUnpackUByte(vbuf, killer);
vbuf = nboUnpackShort(vbuf, reason);
vbuf = nboUnpackShort(vbuf, shotId);
// find the player names and build a kill message string
it = players.find(victim);
victimName = (it != players.end() ? it->second.name : "<unknown>");
it = players.find(killer);
killerName = (it != players.end() ? it->second.name : "<unknown>");
lastMessage.first = std::string("*** ") + "'" + victimName + "' ";
if (killer == victim) {
lastMessage.first = lastMessage.first + "blew myself up.";
}
else {
lastMessage.first = lastMessage.first + "destroyed by '" +
killerName + "'.";
}
}
break;
case MsgSuperKill:
return Superkilled;
case MsgScore: {
uint8_t numScores;
vbuf = nboUnpackUByte(vbuf, numScores);
for (uint8_t i = 0; i < numScores; i++) {
uint16_t wins, losses, tks;
vbuf = nboUnpackUByte(vbuf, p);
vbuf = nboUnpackUShort(vbuf, wins);
vbuf = nboUnpackUShort(vbuf, losses);
vbuf = nboUnpackUShort(vbuf, tks);
if ((iter = players.find(p)) != players.end()) {
iter->second.wins = wins;
iter->second.losses = losses;
iter->second.tks = tks;
}
}
if (messageMask[MsgScore]) {
lastMessage.first =
std::string("*** Received score update, score for ")+
string_util::format("%d", numScores) + " player" +
(numScores == 1 ? "s" : "") + " updated.";
}
break;
}
case MsgMessage:
// unpack the message header
PlayerId src;
PlayerId dst;
PlayerId me = sLink.getId();
vbuf = nboUnpackUByte(vbuf, src);
vbuf = nboUnpackUByte(vbuf, dst);
// is the message for me?
TeamColor dstTeam = (dst >= 244 && dst <= 250 ?
TeamColor(250 - dst) : NoTeam);
if (dst == AllPlayers || src == me || dst == me || dstTeam == myTeam) {
if (strcmp("CLIENTQUERY", (char*)vbuf) == 0) {
sendMessage(std::string("bzadmin ") + getAppVersion(), src);
lastMessage.first = " [Sent versioninfo per request]";
break;
}
else if (messageMask[MsgMessage]) {
lastMessage.first = formatMessage((char*)vbuf, src, dst,dstTeam, me);
PlayerIdMap::const_iterator iter = players.find(src);
lastMessage.second = (iter == players.end() ?
colorMap[NoTeam] :
colorMap[iter->second.team]);
}
}
break;
}
if (ui != NULL)
ui->handleNewPacket(code);
return GotMessage;
}
if (sLink.getState() != ServerLink::Okay) {
if (ui != NULL)
ui->outputMessage("--- ERROR: Communication error", Red);
return CommError;
}
return NoMessage;
}
std::pair<std::string, ColorCode> BZAdminClient::getLastMessage() const {
return lastMessage;
}
PlayerIdMap& BZAdminClient::getPlayers() {
return players;
}
bool BZAdminClient::isValid() const {
return valid;
}
void BZAdminClient::runLoop() {
std::string cmd;
ServerCode what(NoMessage);
while (true) {
what = checkMessage();
if (what == Superkilled || what == CommError)
break;
if (ui != NULL && ui->checkCommand(cmd)) {
if (cmd == "/quit")
break;
if (cmd != "")
sendMessage(cmd, ui->getTarget());
}
}
// why did we leave the loop?
switch (what) {
case Superkilled:
lastMessage.first = "--- ERROR: Server forced disconnect";
lastMessage.second = Red;
break;
case CommError:
lastMessage.first = "--- ERROR: Connection to server lost";
lastMessage.second = Red;
break;
default:
waitForServer();
}
}
void BZAdminClient::sendMessage(const std::string& msg,
PlayerId target) {
// local commands:
// /set lists all BZDB variables
if (msg == "/set") {
if (ui != NULL)
BZDB.iterate(listSetVars, this);
return;
}
char buffer[MessageLen];
char buffer2[1 + MessageLen];
void* buf = buffer2;
buf = nboPackUByte(buf, target);
memset(buffer, 0, MessageLen);
strncpy(buffer, msg.c_str(), MessageLen - 1);
nboPackString(buffer2 + 1, buffer, MessageLen);
sLink.send(MsgMessage, sizeof(buffer2), buffer2);
}
std::string BZAdminClient::formatMessage(const std::string& msg, PlayerId src,
PlayerId dst, TeamColor dstTeam,
PlayerId me) {
std::string formatted = " ";
// get sender and receiver
const std::string srcName = (src == ServerPlayer ? "SERVER" :
(players.count(src) ? players[src].name :
"(UNKNOWN)"));
const std::string dstName = (players.count(dst) ? players[dst].name :
"(UNKNOWN)");
// direct message to or from me
if (dst == me || players.count(dst)) {
if (!(src == me && dst == me)) {
formatted += "[";
if (src == me) {
formatted += "->";
formatted += dstName;
}
else {
formatted += srcName;
formatted += "->";
}
formatted += "] ";
}
formatted += msg;
}
// public or team message
else {
if (dstTeam != NoTeam)
formatted += "[Team] ";
formatted += srcName;
formatted += ": ";
formatted += msg;
}
return formatted;
}
void BZAdminClient::setUI(BZAdminUI* bzInterface) {
ui = bzInterface;
}
void BZAdminClient::waitForServer() {
// we need to know that the server has processed all our messages
// send a private message to ourself and wait for it to come back
// this assumes that the order of messages isn't changed along the way
bool tmp = messageMask[MsgMessage];
messageMask[MsgMessage] = true;
PlayerId me = sLink.getId();
if (sLink.getState() == ServerLink::Okay) {
sendMessage("bzadminping", me);
std::string expected = formatMessage("bzadminping", me, me, NoTeam, me);
std::string str;
BZAdminUI* tmpUI = ui;
ui = NULL;
do {
checkMessage();
} while (lastMessage.first != expected);
ui = tmpUI;
}
messageMask[MsgMessage] = tmp;
}
void BZAdminClient::ignoreMessageType(uint16_t type) {
messageMask[type] = false;
}
void BZAdminClient::showMessageType(uint16_t type) {
messageMask[type] = true;
}
void BZAdminClient::ignoreMessageType(std::string type) {
ignoreMessageType(msgTypeMap[type]);
}
void BZAdminClient::showMessageType(std::string type) {
showMessageType(msgTypeMap[type]);
}
void BZAdminClient::listSetVars(const std::string& name, void* thisObject) {
char message[MessageLen];
if (BZDB.getPermission(name) == StateDatabase::Locked) {
sprintf(message, "/set %s %f", name.c_str(), BZDB.eval(name));
((BZAdminClient*)thisObject)->ui->outputMessage(message, Default);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* CUDA global device memory vector
*
* Copyright (C) 2007 Peter Colberg
*
* 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 CUDA_VECTOR_HPP
#define CUDA_VECTOR_HPP
#include <algorithm>
#include <cuda_wrapper/allocator.hpp>
#include <cuda_wrapper/copy.hpp>
#include <vector>
namespace cuda
{
/**
* CUDA global device memory vector
*/
template <typename T>
class vector : private std::vector<T, allocator<T> >
{
public:
typedef allocator<T> _Alloc;
typedef std::vector<T, allocator<T> > _Base;
typedef vector<T> vector_type;
typedef T value_type;
typedef size_t size_type;
public:
vector() : size_(0) {}
/**
* initialize device vector of given size
*/
vector(size_type size) : size_(size)
{
_Base::reserve(size_);
}
/**
* deep copy constructor
*/
vector(vector_type const& v)
{
vector w(v.size());
copy(v, w);
swap(w);
}
/**
* deep assignment operator
*/
vector_type& operator=(vector_type const& v)
{
vector w(v.size());
copy(v, w);
swap(w);
return *this;
}
/**
* swap device memory with another vector
*/
void swap(vector_type& v)
{
std::swap(v.size_, size_);
_Base::swap(v);
}
/**
* returns element count of device vector
*/
size_type size() const
{
return size_;
}
/**
* resize element count of device vector
*/
void resize(size_type size)
{
// size of vector must always be kept at zero to prevent
// initialization of vector elements, so use vector::reserve
// in place of vector::resize
_Base::reserve(size);
size_ = size;
}
/**
* returns capacity
*/
size_type capacity() const
{
return _Base::capacity();
}
/**
* allocate enough memory for specified number of elements
*/
void reserve(size_type n)
{
_Base::reserve(std::max(size_, n));
}
/**
* returns device pointer to allocated device memory
*/
value_type* data()
{
return _Base::data();
}
operator value_type*()
{
return _Base::data();
}
/**
* returns device pointer to allocated device memory
*/
value_type const* data() const
{
return _Base::data();
}
operator value_type const*() const
{
return _Base::data();
}
private:
size_type size_;
};
} // namespace cuda
#endif /* CUDA_VECTOR_HPP */
<commit_msg>Free device memory before reallocation<commit_after>/* CUDA global device memory vector
*
* Copyright (C) 2007 Peter Colberg
*
* 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 CUDA_VECTOR_HPP
#define CUDA_VECTOR_HPP
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>
namespace cuda
{
/**
* CUDA global device memory vector
*/
template <typename T>
class vector
{
public:
typedef vector<T> vector_type;
typedef T value_type;
typedef T* pointer;
typedef T const* const_pointer;
typedef size_t size_type;
private:
struct container : boost::noncopyable
{
/**
* allocate global device memory
*/
container(size_type size) : m_size(size)
{
CUDA_CALL(cudaMalloc(reinterpret_cast<void**>(&m_ptr), m_size * sizeof(value_type)));
}
/**
* free global device memory
*/
~container() throw()
{
cudaFree(reinterpret_cast<void*>(m_ptr));
}
pointer m_ptr;
size_type m_size;
};
public:
/**
* initialize device vector of given size
*/
vector(size_type size) : m_mem(new container(size)), m_size(size) {}
vector() {}
/**
* returns element count of device vector
*/
size_type size() const
{
return m_size;
}
/**
* returns capacity
*/
size_type capacity() const
{
return m_mem->m_size;
}
/**
* resize element count of device vector
*/
void resize(size_type size)
{
if (size != m_size) {
m_mem.reset();
m_mem.reset(new container(size));
m_size = size;
}
}
/**
* allocate enough memory for specified number of elements
*/
void reserve(size_type size)
{
if (size > m_size) {
m_mem.reset();
m_mem.reset(new container(size));
}
}
/**
* swap device memory with vector
*/
void swap(vector_type& v)
{
m_mem.swap(v.m_mem);
std::swap(m_size, v.m_size);
}
/**
* returns device pointer to allocated device memory
*/
pointer data()
{
return m_mem->m_ptr;
}
operator pointer()
{
return m_mem->m_ptr;
}
const_pointer data() const
{
return m_mem->m_ptr;
}
operator const_pointer() const
{
return m_mem->m_ptr;
}
private:
boost::shared_ptr<container> m_mem;
size_type m_size;
};
} // namespace cuda
#endif /* CUDA_VECTOR_HPP */
<|endoftext|> |
<commit_before>#include <io.h>
#include <curl\curl.h>
#include "SSLSocketStream.h"
#include "httprequest.h"
#include "CommonFuncs.h"
#include "ContentHandle.h"
#include "BaseSSLConfig.h"
#include "Parser.h"
#include "BaseHTTPRequestHandler.h"
extern BaseSSLConfig* g_BaseSSLConfig;
//ĬϽյĻص
void __stdcall Default_Request_Callback(PCALLBACK_DATA pcallback_data)
{
#ifdef _DEBUG
//::OutputDebugStringA("Default_Request_Callback\n");
#endif
}
void __stdcall Default_Response_Callback(PCALLBACK_DATA pcallback_data)
{
#ifdef _DEBUG
// ::OutputDebugStringA("Default_Response_Callback\n");
#endif
}
#define HTTP_1_1 "HTTP/1.1"
#define HTTP_1_0 "HTTP/1.0"
#define RELEASE_RECVBUF() { \
if (m_precv_buf != NULL) { \
free(m_precv_buf); \
m_precv_buf = NULL; \
} \
m_len_recvbuf = 0; \
}
BaseHTTPRequestHandler::BaseHTTPRequestHandler(HTTPSERVICE_PARAMS *pHttpService_Params, HttpSession * pHttpSession)
:m_pHttpSession(pHttpSession)
{
m_pBaseSockeStream = NULL;
m_precv_buf = NULL;
m_len_recvbuf = 0;
m_pHttpService_Params = pHttpService_Params;
if (m_pHttpService_Params->request_callback == NULL)
m_pHttpService_Params->request_callback = Default_Request_Callback;
if (m_pHttpService_Params->response_callback == NULL)
m_pHttpService_Params->response_callback = Default_Response_Callback;
//طжǷΪSSH
if (m_pHttpService_Params->bSSH)
{
m_pBaseSockeStream = new SSLSocketStream(&m_precv_buf, &m_len_recvbuf, &m_pHttpSession->m_pSendbuf, &m_pHttpSession->m_SizeofSendbuf);
}
else
m_pBaseSockeStream = new BaseSocketStream(&m_precv_buf, &m_len_recvbuf, &m_pHttpSession->m_pSendbuf, &m_pHttpSession->m_SizeofSendbuf); //ʼSocket
}
BaseHTTPRequestHandler::~BaseHTTPRequestHandler()
{
if (m_pBaseSockeStream != NULL) {
delete m_pBaseSockeStream;
m_pBaseSockeStream = NULL;
}
reset();
RELEASE_RECVBUF();
}
//do_OPTIONS
void BaseHTTPRequestHandler::do_OPTIONS()
{
return;
}
//do_GET
void BaseHTTPRequestHandler::do_GET()
{
int ret = 0;
char *result = NULL;
HttpHeaders response_httpheaders;
HttpContent response_httpcontent;
char *result_phttpheaders = NULL;
char *result_phttpcontent = NULL;
size_t len_httpheaders = 0;
size_t len_httpcontent = 0;
char classname[256] = { 0 };
size_t result_size = 0;
Parser::RequestHttpHeadersParser(&http_items); //httpͷϢ
if (m_pHttpService_Params->bSSH) {
ret = httprequest.https_request(&http_items, &httpcontent, &response_httpheaders, &response_httpcontent);
}
else
{
if (_stricmp("SSLSocketStream", m_pBaseSockeStream->_classname(classname, 256)) == 0) {
http_items.m_port = m_port; //طҪĶ˿ں
ret = httprequest.https_request(&http_items, &httpcontent, &response_httpheaders, &response_httpcontent);
}
else {
ret = httprequest.http_request(&http_items, &httpcontent, &response_httpheaders, &response_httpcontent);
}
}
do {//ش˳ӦŻ
if (ret == HttpRequest::CURLE_OK)
{
if (response_httpheaders.m_response_status == 400) {
m_pHttpSession->m_resultstate = HttpSession::HS_RESULT_SERVER_NOEXIST;
m_pHttpSession->m_bKeepAlive = FALSE;
break;
}
m_pHttpSession->m_resultstate = HttpSession::HS_RESULT_OK;
Parser::ResponseHttpHeadersParser(&response_httpheaders, &http_items); //صhttpͷϢ
result_phttpcontent = response_httpcontent.getbuffer(&len_httpcontent);
result_phttpheaders = response_httpheaders.getbuffer(&len_httpheaders);
result_size = len_httpheaders + len_httpcontent + strlen(response_httpheaders.m_version) + 50;
result = (char*)::malloc(result_size);
memset(result, 0, result_size);
char *descript = HttpHeaders::get_status_code_descript(response_httpheaders.m_response_status);
wsprintfA(result, "%s %d %s\r\n", response_httpheaders.m_version, response_httpheaders.m_response_status, descript);
size_t len_title = strlen(result);
memcpy_s(result + len_title, result_size - len_title, result_phttpheaders, len_httpheaders);
memcpy_s(result + len_httpheaders + len_title, result_size - len_title - len_httpheaders, result_phttpcontent, len_httpcontent);
//ػص
result_size = len_title + len_httpheaders + len_httpcontent;
invokeResponseCallback(&result,&result_size);
m_pBaseSockeStream->write(result, result_size);
}
} while (0);
//
if (result_phttpcontent != NULL) {
free(result_phttpcontent);
result_phttpcontent = NULL;
}
if (result_phttpheaders != NULL) {
free(result_phttpheaders);
result_phttpheaders = NULL;
}
if (result != NULL) {
free(result);
result = NULL;
}
response_httpheaders.release();
response_httpcontent.release();
}
//do_HEADER
void BaseHTTPRequestHandler::do_HEAD()
{
return;
}
//do_POST
void BaseHTTPRequestHandler::do_POST()
{
return;
}
//do_PUT
void BaseHTTPRequestHandler::do_PUT()
{
}
//do_DELETE
void BaseHTTPRequestHandler::do_DELETE()
{
}
//do_TRACE
void BaseHTTPRequestHandler::do_TRACE()
{
return;
}
//do_CONNECT
void BaseHTTPRequestHandler::do_CONNECT()
{
//ж֤ļǷΪ
if (g_BaseSSLConfig!=NULL &&
g_BaseSSLConfig->status()==BaseSSLConfig::STATUS_INITFINAL) {
#if 1
connect_intercept();//жϣȡݺת
#endif
}
else
connect_relay();//ֱת
return;
}
void BaseHTTPRequestHandler::connect_intercept()
{
if (m_pBaseSockeStream != NULL) {
delete m_pBaseSockeStream;
}
//յ
if (_stricmp(http_items.m_version, HTTP_1_1) == 0) {
m_port = http_items.m_port; //˿ں
}
else {
BOOL bFind_Colon = FALSE;
char *pPort = http_items.m_uri;
while (*pPort != '\0') {
if (*pPort == ':') {
bFind_Colon = TRUE;
break;
}
pPort++;
}
if (bFind_Colon) {
if (*(pPort + 1) != '\0') {
pPort++;
m_port = (WORD)strtol(pPort, NULL, 10);
}
}
}
SSLSocketStream::_init_syn();
//
m_pBaseSockeStream = new SSLSocketStream(&m_precv_buf, &m_len_recvbuf, &m_pHttpSession->m_pSendbuf, &m_pHttpSession->m_SizeofSendbuf);
if(!m_pBaseSockeStream->init(http_items.m_host,strlen(http_items.m_host))) //m_uriܲҪǩĵַ
{
return;
}
//ӦCONNECTϢ
char temp[1024] = { 0 };
wsprintfA(temp, "%s %d %s\r\n\r\n", http_items.m_version, 200, "Connection Established");
m_pHttpSession->m_pSendbuf = (char*)malloc(strlen(temp));
memset(m_pHttpSession->m_pSendbuf, 0, strlen(temp));
memcpy_s(m_pHttpSession->m_pSendbuf, strlen(temp), temp, strlen(temp));
m_pHttpSession->m_SizeofSendbuf = strlen(temp);
m_pHttpSession->m_bKeepAlive = TRUE;
m_pHttpSession->m_resultstate = HttpSession::HS_RESULT_OK;
}
/*
ֱת
*/
void BaseHTTPRequestHandler::connect_relay()
{
/*
ʱ֧ת
תҪ˽socketӣʱܼ뵽еiocpУ
汾ĸĽ
*/
}
/*
طմݣظҪķ
*/
void BaseHTTPRequestHandler::handler_request(void *recvbuf, DWORD len, BaseDataHandler_RET * ret)//λ,bufָڴѾû
{
BaseDataHandler_RET* p_ret = NULL;
size_t headersize = 0;
int result = BaseSocketStream::BSS_RET_UNKNOWN;
char * pContent_Length = NULL;
long Content_Length = 0;
ret->dwOpt = RET_UNKNOWN;
result = m_pBaseSockeStream->read(recvbuf, len);
if (result == BaseSocketStream::BSS_RET_RESULT) {
if (m_len_recvbuf > 0 && m_precv_buf != NULL)
{//ȷڲݣ
if ((headersize = find_httpheader(m_precv_buf,m_len_recvbuf)) > 0) {
if (http_items.parse_httpheaders((const char*)m_precv_buf, m_len_recvbuf, HttpHeaders::HTTP_REQUEST)) {
if ((pContent_Length = http_items["Content-Length"]) != NULL) {
//ֳ
Content_Length = strtol(pContent_Length, NULL, 10);
if (headersize + Content_Length <= m_len_recvbuf) {//˵Ѿȫ
//ʼյ
httpcontent.insert(m_precv_buf + headersize, Content_Length);
invokeRequestCallback(&http_items);
invokeMethod(http_items.m_method);
reset();
RELEASE_RECVBUF()
ret->dwOpt = RET_SEND;
}
else {
reset();
ret->dwOpt = RET_RECV;
}
}
else {
invokeRequestCallback(&http_items);
invokeMethod(http_items.m_method);
reset();
RELEASE_RECVBUF()
ret->dwOpt = RET_SEND;
}
}//if (http_items.parse_httpheaders((const char*)m_precv_b........
else {
reset(); //òڴ
RELEASE_RECVBUF()
ret->dwOpt = RET_RECV;
}
}//if ((headersize = find_httpheader(m_precv_buf,m_len_recvbuf)) > 0)
else {
ret->dwOpt = RET_RECV;
}
}//if (m_len_recvbuf > 0 && m_precv_buf == NULL)
}
else if (result == BaseSocketStream::BSS_RET_RECV) {
ret->dwOpt = RET_RECV;
}
else if (result == BaseSocketStream::BSS_RET_SEND) {
RELEASE_RECVBUF()
ret->dwOpt = RET_SEND;
}
return;
}
size_t BaseHTTPRequestHandler::find_httpheader(const char* buf, size_t bufsize) {
size_t httplen = 0;
char *pHttpFlag = NULL;
if (buf != NULL && bufsize>0) {
if (ContentHandle::search_content(buf, bufsize, "^\\S{3,}\\s{1,}\\S{1,}\\s{1,}HTTP\\/[0-9]\\.[0-9]\\s{2}",NULL,NULL))
{
if (ContentHandle::search_content(buf, bufsize, "\r\n\r\n", &pHttpFlag, &httplen))
{
httplen += strlen("\r\n\r\n");
}
}
}
return httplen;
};
/*
öӦĴ
*/
void BaseHTTPRequestHandler::invokeMethod(const char * method) {
if (_stricmp(method, "CONNECT") == 0) {
do_CONNECT();
}
else
do_GET();
}
/*
صǰص
*/
void BaseHTTPRequestHandler::invokeRequestCallback(HttpHeaders *http_headers)
{
CALLBACK_DATA callback_data;
memset(&callback_data, 0, sizeof(CALLBACK_DATA));
callback_data.len = http_headers->get_request_uri(NULL, 0);
if(callback_data.len == 0)
return;
callback_data.buf = (char*)malloc(callback_data.len + 1);
memset(callback_data.buf, 0, callback_data.len + 1);
http_headers->get_request_uri(callback_data.buf, callback_data.len);
m_pHttpService_Params->request_callback(&callback_data);
//֮ڴ
if (callback_data.buf != NULL) {
free(callback_data.buf);
callback_data.buf = NULL;
}
}
/*
غûص
*/
void BaseHTTPRequestHandler::invokeResponseCallback(char **buf, size_t *plen)
{
CALLBACK_DATA callback_data;
if(*buf == NULL || *plen == 0)
return;
memset(&callback_data, 0, sizeof(CALLBACK_DATA));
callback_data.buf = (char*)malloc(*plen);
memset(callback_data.buf, 0, *plen);
memcpy_s(callback_data.buf, *plen, *buf, *plen);
callback_data.len = *plen;
m_pHttpService_Params->response_callback(&callback_data);
if(*buf != NULL){
free(*buf);
*buf = NULL;
}
*buf = (char*) malloc(callback_data.len);
memset(*buf, 0, callback_data.len);
memcpy_s(*buf, callback_data.len, callback_data.buf, callback_data.len);
*plen = callback_data.len;
//֮ڴ
if (callback_data.buf != NULL) {
free(callback_data.buf);
callback_data.buf = NULL;
}
}
/*
ûȫݾҪã֤ݽȷ
*/
void BaseHTTPRequestHandler::reset()
{
http_items.release();
httpcontent.release();
}<commit_msg>解决http协议容错性问题<commit_after>#include <io.h>
#include <curl\curl.h>
#include "SSLSocketStream.h"
#include "httprequest.h"
#include "CommonFuncs.h"
#include "ContentHandle.h"
#include "BaseSSLConfig.h"
#include "Parser.h"
#include "BaseHTTPRequestHandler.h"
extern BaseSSLConfig* g_BaseSSLConfig;
//ĬϽյĻص
void __stdcall Default_Request_Callback(PCALLBACK_DATA pcallback_data)
{
#ifdef _DEBUG
//::OutputDebugStringA("Default_Request_Callback\n");
#endif
}
void __stdcall Default_Response_Callback(PCALLBACK_DATA pcallback_data)
{
#ifdef _DEBUG
// ::OutputDebugStringA("Default_Response_Callback\n");
#endif
}
#define HTTP_1_1 "HTTP/1.1"
#define HTTP_1_0 "HTTP/1.0"
#define RELEASE_RECVBUF() { \
if (m_precv_buf != NULL) { \
free(m_precv_buf); \
m_precv_buf = NULL; \
} \
m_len_recvbuf = 0; \
}
BaseHTTPRequestHandler::BaseHTTPRequestHandler(HTTPSERVICE_PARAMS *pHttpService_Params, HttpSession * pHttpSession)
:m_pHttpSession(pHttpSession)
{
m_pBaseSockeStream = NULL;
m_precv_buf = NULL;
m_len_recvbuf = 0;
m_pHttpService_Params = pHttpService_Params;
if (m_pHttpService_Params->request_callback == NULL)
m_pHttpService_Params->request_callback = Default_Request_Callback;
if (m_pHttpService_Params->response_callback == NULL)
m_pHttpService_Params->response_callback = Default_Response_Callback;
//طжǷΪSSH
if (m_pHttpService_Params->bSSH)
{
m_pBaseSockeStream = new SSLSocketStream(&m_precv_buf, &m_len_recvbuf, &m_pHttpSession->m_pSendbuf, &m_pHttpSession->m_SizeofSendbuf);
}
else
m_pBaseSockeStream = new BaseSocketStream(&m_precv_buf, &m_len_recvbuf, &m_pHttpSession->m_pSendbuf, &m_pHttpSession->m_SizeofSendbuf); //ʼSocket
}
BaseHTTPRequestHandler::~BaseHTTPRequestHandler()
{
if (m_pBaseSockeStream != NULL) {
delete m_pBaseSockeStream;
m_pBaseSockeStream = NULL;
}
reset();
RELEASE_RECVBUF();
}
//do_OPTIONS
void BaseHTTPRequestHandler::do_OPTIONS()
{
return;
}
//do_GET
void BaseHTTPRequestHandler::do_GET()
{
int ret = 0;
char *result = NULL;
HttpHeaders response_httpheaders;
HttpContent response_httpcontent;
char *result_phttpheaders = NULL;
char *result_phttpcontent = NULL;
size_t len_httpheaders = 0;
size_t len_httpcontent = 0;
char classname[256] = { 0 };
size_t result_size = 0;
Parser::RequestHttpHeadersParser(&http_items); //httpͷϢ
if (m_pHttpService_Params->bSSH) {
ret = httprequest.https_request(&http_items, &httpcontent, &response_httpheaders, &response_httpcontent);
}
else
{
if (_stricmp("SSLSocketStream", m_pBaseSockeStream->_classname(classname, 256)) == 0) {
http_items.m_port = m_port; //طҪĶ˿ں
ret = httprequest.https_request(&http_items, &httpcontent, &response_httpheaders, &response_httpcontent);
}
else {
ret = httprequest.http_request(&http_items, &httpcontent, &response_httpheaders, &response_httpcontent);
}
}
do {//ش˳ӦŻ
if (ret == HttpRequest::CURLE_OK)
{
if (response_httpheaders.m_response_status == 400) {
m_pHttpSession->m_resultstate = HttpSession::HS_RESULT_SERVER_NOEXIST;
m_pHttpSession->m_bKeepAlive = FALSE;
break;
}
m_pHttpSession->m_resultstate = HttpSession::HS_RESULT_OK;
Parser::ResponseHttpHeadersParser(&response_httpheaders, &http_items); //صhttpͷϢ
result_phttpcontent = response_httpcontent.getbuffer(&len_httpcontent);
result_phttpheaders = response_httpheaders.getbuffer(&len_httpheaders);
result_size = len_httpheaders + len_httpcontent + strlen(response_httpheaders.m_version) + 50;
result = (char*)::malloc(result_size);
memset(result, 0, result_size);
char *descript = HttpHeaders::get_status_code_descript(response_httpheaders.m_response_status);
wsprintfA(result, "%s %d %s\r\n", response_httpheaders.m_version, response_httpheaders.m_response_status, descript);
size_t len_title = strlen(result);
memcpy_s(result + len_title, result_size - len_title, result_phttpheaders, len_httpheaders);
memcpy_s(result + len_httpheaders + len_title, result_size - len_title - len_httpheaders, result_phttpcontent, len_httpcontent);
//ػص
result_size = len_title + len_httpheaders + len_httpcontent;
invokeResponseCallback(&result,&result_size);
m_pBaseSockeStream->write(result, result_size);
}
} while (0);
//
if (result_phttpcontent != NULL) {
free(result_phttpcontent);
result_phttpcontent = NULL;
}
if (result_phttpheaders != NULL) {
free(result_phttpheaders);
result_phttpheaders = NULL;
}
if (result != NULL) {
free(result);
result = NULL;
}
response_httpheaders.release();
response_httpcontent.release();
}
//do_HEADER
void BaseHTTPRequestHandler::do_HEAD()
{
return;
}
//do_POST
void BaseHTTPRequestHandler::do_POST()
{
return;
}
//do_PUT
void BaseHTTPRequestHandler::do_PUT()
{
}
//do_DELETE
void BaseHTTPRequestHandler::do_DELETE()
{
}
//do_TRACE
void BaseHTTPRequestHandler::do_TRACE()
{
return;
}
//do_CONNECT
void BaseHTTPRequestHandler::do_CONNECT()
{
//ж֤ļǷΪ
if (g_BaseSSLConfig!=NULL &&
g_BaseSSLConfig->status()==BaseSSLConfig::STATUS_INITFINAL) {
#if 1
connect_intercept();//жϣȡݺת
#endif
}
else
connect_relay();//ֱת
return;
}
void BaseHTTPRequestHandler::connect_intercept()
{
if (m_pBaseSockeStream != NULL) {
delete m_pBaseSockeStream;
}
//յ
#if 0
if (_stricmp(http_items.m_version, HTTP_1_1) == 0) {
m_port = http_items.m_port; //˿ں
}
else {
#endif
BOOL bFind_Colon = FALSE;
char *pPort = http_items.m_uri;
while (*pPort != '\0') {
if (*pPort == ':') {
bFind_Colon = TRUE;
break;
}
pPort++;
}
if (bFind_Colon) {
if (*(pPort + 1) != '\0') {
pPort++;
m_port = (WORD)strtol(pPort, NULL, 10);
}
}
#if 0
}
#endif
SSLSocketStream::_init_syn();
//
m_pBaseSockeStream = new SSLSocketStream(&m_precv_buf, &m_len_recvbuf, &m_pHttpSession->m_pSendbuf, &m_pHttpSession->m_SizeofSendbuf);
if(!m_pBaseSockeStream->init(http_items.m_host,strlen(http_items.m_host))) //m_uriܲҪǩĵַ
{
return;
}
//ӦCONNECTϢ
char temp[1024] = { 0 };
wsprintfA(temp, "%s %d %s\r\n\r\n", http_items.m_version, 200, "Connection Established");
m_pHttpSession->m_pSendbuf = (char*)malloc(strlen(temp));
memset(m_pHttpSession->m_pSendbuf, 0, strlen(temp));
memcpy_s(m_pHttpSession->m_pSendbuf, strlen(temp), temp, strlen(temp));
m_pHttpSession->m_SizeofSendbuf = strlen(temp);
m_pHttpSession->m_bKeepAlive = TRUE;
m_pHttpSession->m_resultstate = HttpSession::HS_RESULT_OK;
}
/*
ֱת
*/
void BaseHTTPRequestHandler::connect_relay()
{
/*
ʱ֧ת
תҪ˽socketӣʱܼ뵽еiocpУ
汾ĸĽ
*/
}
/*
طմݣظҪķ
*/
void BaseHTTPRequestHandler::handler_request(void *recvbuf, DWORD len, BaseDataHandler_RET * ret)//λ,bufָڴѾû
{
BaseDataHandler_RET* p_ret = NULL;
size_t headersize = 0;
int result = BaseSocketStream::BSS_RET_UNKNOWN;
char * pContent_Length = NULL;
long Content_Length = 0;
ret->dwOpt = RET_UNKNOWN;
result = m_pBaseSockeStream->read(recvbuf, len);
if (result == BaseSocketStream::BSS_RET_RESULT) {
if (m_len_recvbuf > 0 && m_precv_buf != NULL)
{//ȷڲݣ
if ((headersize = find_httpheader(m_precv_buf,m_len_recvbuf)) > 0) {
if (http_items.parse_httpheaders((const char*)m_precv_buf, m_len_recvbuf, HttpHeaders::HTTP_REQUEST)) {
if ((pContent_Length = http_items["Content-Length"]) != NULL) {
//ֳ
Content_Length = strtol(pContent_Length, NULL, 10);
if (headersize + Content_Length <= m_len_recvbuf) {//˵Ѿȫ
//ʼյ
httpcontent.insert(m_precv_buf + headersize, Content_Length);
invokeRequestCallback(&http_items);
invokeMethod(http_items.m_method);
reset();
RELEASE_RECVBUF()
ret->dwOpt = RET_SEND;
}
else {
reset();
ret->dwOpt = RET_RECV;
}
}
else {
invokeRequestCallback(&http_items);
invokeMethod(http_items.m_method);
reset();
RELEASE_RECVBUF()
ret->dwOpt = RET_SEND;
}
}//if (http_items.parse_httpheaders((const char*)m_precv_b........
else {
reset(); //òڴ
RELEASE_RECVBUF()
ret->dwOpt = RET_RECV;
}
}//if ((headersize = find_httpheader(m_precv_buf,m_len_recvbuf)) > 0)
else {
ret->dwOpt = RET_RECV;
}
}//if (m_len_recvbuf > 0 && m_precv_buf == NULL)
}
else if (result == BaseSocketStream::BSS_RET_RECV) {
ret->dwOpt = RET_RECV;
}
else if (result == BaseSocketStream::BSS_RET_SEND) {
RELEASE_RECVBUF()
ret->dwOpt = RET_SEND;
}
return;
}
size_t BaseHTTPRequestHandler::find_httpheader(const char* buf, size_t bufsize) {
size_t httplen = 0;
char *pHttpFlag = NULL;
if (buf != NULL && bufsize>0) {
if (ContentHandle::search_content(buf, bufsize, "^\\S{3,}\\s{1,}\\S{1,}\\s{1,}HTTP\\/[0-9]\\.[0-9]\\s{2}",NULL,NULL))
{
if (ContentHandle::search_content(buf, bufsize, "\r\n\r\n", &pHttpFlag, &httplen))
{
httplen += strlen("\r\n\r\n");
}
}
}
return httplen;
};
/*
öӦĴ
*/
void BaseHTTPRequestHandler::invokeMethod(const char * method) {
if (_stricmp(method, "CONNECT") == 0) {
do_CONNECT();
}
else
do_GET();
}
/*
صǰص
*/
void BaseHTTPRequestHandler::invokeRequestCallback(HttpHeaders *http_headers)
{
CALLBACK_DATA callback_data;
memset(&callback_data, 0, sizeof(CALLBACK_DATA));
callback_data.len = http_headers->get_request_uri(NULL, 0);
if(callback_data.len == 0)
return;
callback_data.buf = (char*)malloc(callback_data.len + 1);
memset(callback_data.buf, 0, callback_data.len + 1);
http_headers->get_request_uri(callback_data.buf, callback_data.len);
m_pHttpService_Params->request_callback(&callback_data);
//֮ڴ
if (callback_data.buf != NULL) {
free(callback_data.buf);
callback_data.buf = NULL;
}
}
/*
غûص
*/
void BaseHTTPRequestHandler::invokeResponseCallback(char **buf, size_t *plen)
{
CALLBACK_DATA callback_data;
if(*buf == NULL || *plen == 0)
return;
memset(&callback_data, 0, sizeof(CALLBACK_DATA));
callback_data.buf = (char*)malloc(*plen);
memset(callback_data.buf, 0, *plen);
memcpy_s(callback_data.buf, *plen, *buf, *plen);
callback_data.len = *plen;
m_pHttpService_Params->response_callback(&callback_data);
if(*buf != NULL){
free(*buf);
*buf = NULL;
}
*buf = (char*) malloc(callback_data.len);
memset(*buf, 0, callback_data.len);
memcpy_s(*buf, callback_data.len, callback_data.buf, callback_data.len);
*plen = callback_data.len;
//֮ڴ
if (callback_data.buf != NULL) {
free(callback_data.buf);
callback_data.buf = NULL;
}
}
/*
ûȫݾҪã֤ݽȷ
*/
void BaseHTTPRequestHandler::reset()
{
http_items.release();
httpcontent.release();
}<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cstdarg>
#include <cerrno>
#include <vector>
#include <map>
#include <string>
#include "riscv-types.h"
#include "riscv-endian.h"
#include "riscv-regs.h"
#include "riscv-processor.h"
#include "riscv-opcodes.h"
#include "riscv-util.h"
#include "riscv-imm.h"
#include "riscv-decode.h"
#include "riscv-decode-switch.h"
#include "riscv-csr.h"
#include "riscv-compression.h"
#include "riscv-format.h"
#include "riscv-disasm.h"
#include "riscv-elf.h"
#include "riscv-elf-file.h"
#include "riscv-elf-format.h"
void decode_rv64(riscv_ptr start, riscv_ptr end, riscv_ptr pc_offset)
{
riscv_decode dec;
riscv_proc_state proc = { 0 };
proc.p_type = riscv_proc_type_rv64i;
proc.pc = start;
while (proc.pc < end) {
riscv_ptr pc = proc.pc;
riscv_decode_instruction(dec, &proc);
riscv_disasm_instruction(dec, &proc, pc, pc_offset);
}
}
int main(int argc, char *argv[])
{
if (argc != 2) panic("usage: %s <elf_file>", argv[0]);
elf_file elf(argv[1]);
elf_print_info(elf);
for (size_t i = 0; i < elf.shdrs.size(); i++) {
Elf64_Shdr &shdr = elf.shdrs[i];
if (shdr.sh_flags & SHF_EXECINSTR) {
printf("section[%2lu] %s\n\n", i, elf_shdr_name(elf, i));
decode_rv64(elf.buf.data() + shdr.sh_offset,
elf.buf.data() + shdr.sh_offset + shdr.sh_size,
elf.buf.data() + shdr.sh_offset - shdr.sh_addr);
printf("\n");
}
}
return 0;
}
<commit_msg>Use capital letter for Section heading<commit_after>#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cstdarg>
#include <cerrno>
#include <vector>
#include <map>
#include <string>
#include "riscv-types.h"
#include "riscv-endian.h"
#include "riscv-regs.h"
#include "riscv-processor.h"
#include "riscv-opcodes.h"
#include "riscv-util.h"
#include "riscv-imm.h"
#include "riscv-decode.h"
#include "riscv-decode-switch.h"
#include "riscv-csr.h"
#include "riscv-compression.h"
#include "riscv-format.h"
#include "riscv-disasm.h"
#include "riscv-elf.h"
#include "riscv-elf-file.h"
#include "riscv-elf-format.h"
void decode_rv64(riscv_ptr start, riscv_ptr end, riscv_ptr pc_offset)
{
riscv_decode dec;
riscv_proc_state proc = { 0 };
proc.p_type = riscv_proc_type_rv64i;
proc.pc = start;
while (proc.pc < end) {
riscv_ptr pc = proc.pc;
riscv_decode_instruction(dec, &proc);
riscv_disasm_instruction(dec, &proc, pc, pc_offset);
}
}
int main(int argc, char *argv[])
{
if (argc != 2) panic("usage: %s <elf_file>", argv[0]);
elf_file elf(argv[1]);
elf_print_info(elf);
for (size_t i = 0; i < elf.shdrs.size(); i++) {
Elf64_Shdr &shdr = elf.shdrs[i];
if (shdr.sh_flags & SHF_EXECINSTR) {
printf("Section[%2lu] %s\n", i, elf_shdr_name(elf, i));
decode_rv64(elf.buf.data() + shdr.sh_offset,
elf.buf.data() + shdr.sh_offset + shdr.sh_size,
elf.buf.data() + shdr.sh_offset - shdr.sh_addr);
printf("\n");
}
}
return 0;
}
<|endoftext|> |
<commit_before>///
/// @file LoadBalancer.cpp
/// @brief The LoadBalancer assigns work to the individual
/// threads in the computation of the special leaves
/// in the Lagarias-Miller-Odlyzko and
/// Deleglise-Rivat prime counting algorithms.
///
/// Simply parallelizing the computation of the special leaves in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by
/// subdividing the sieve interval by the number of threads into
/// equally sized subintervals does not scale because the distribution
/// of the special leaves is highly skewed and most special leaves are
/// in the first few segments whereas later on there are very few
/// special leaves.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <LoadBalancer.hpp>
#include <primecount-internal.hpp>
#include <S2Status.hpp>
#include <imath.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <calculator.hpp>
#include <json.hpp>
#include <stdint.h>
#include <cmath>
#include <iostream>
#include <iomanip>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace nlohmann;
namespace primecount {
int LoadBalancer::resume_threads() const
{
int threads = 0;
auto j = load_backup();
if (is_resume(j, "S2_hard", x_, y_, z_))
while (j["S2_hard"]["thread" + to_string(threads)].is_object())
threads++;
return threads;
}
void LoadBalancer::backup(int thread_id,
int64_t low,
int64_t segments,
int64_t segment_size) const
{
auto j = load_backup();
double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);
j["S2_hard"]["x"] = to_string(x_);
j["S2_hard"]["y"] = y_;
j["S2_hard"]["z"] = z_;
j["S2_hard"]["low"] = low_;
j["S2_hard"]["segments"] = segments_;
j["S2_hard"]["segment_size"] = segment_size_;
j["S2_hard"]["s2_hard"] = to_string(s2_total_);
j["S2_hard"]["percent"] = percent;
j["S2_hard"]["seconds"] = get_wtime() - time_;
j["S2_hard"]["thread" + to_string(thread_id)]["low"] = low;
j["S2_hard"]["thread" + to_string(thread_id)]["segments"] = segments;
j["S2_hard"]["thread" + to_string(thread_id)]["segment_size"] = segment_size;
store_backup(j);
}
template <typename T>
void print_resume(int thread_id,
T low,
T segments,
T segment_size)
{
if (is_print())
{
if (!print_variables())
cout << endl;
cout << "=== Resuming from primecount.backup ===" << endl;
cout << "thread = " << thread_id << endl;
cout << "low = " << low << endl;
cout << "segments = " << segments << endl;
cout << "segment_size = " << segment_size << endl;
cout << endl;
}
}
template <typename T>
void print_resume(T s2_hard,
double seconds)
{
if (is_print())
{
if (!print_variables())
cout << endl;
cout << "=== Resuming from primecount.backup ===" << endl;
cout << "S2_hard = " << s2_hard << endl;
cout << "Seconds: " << fixed << setprecision(3) << seconds << endl;
cout << endl;
}
}
bool LoadBalancer::resume(int thread_id,
int64_t& low,
int64_t& segments,
int64_t& segment_size)
{
bool resumed = false;
#pragma omp critical (LoadBalancer)
{
auto j = load_backup();
if (is_resume(j, "S2_hard", x_, y_, z_))
{
double seconds = j["S2_hard"]["seconds"];
s2_total_ = calculator::eval<maxint_t>(j["S2_hard"]["s2_hard"]);
low_ = j["S2_hard"]["low"];
segments_ = j["S2_hard"]["segments"];
segment_size_ = j["S2_hard"]["segment_size"];
time_ = get_wtime() - seconds;
low = j["S2_hard"]["thread" + to_string(thread_id)]["low"];
segments = j["S2_hard"]["thread" + to_string(thread_id)]["segments"];
segment_size = j["S2_hard"]["thread" + to_string(thread_id)]["segment_size"];
print_resume(thread_id, low, segments, segment_size);
resumed = true;
}
}
return resumed;
}
bool LoadBalancer::resume(maxint_t& s2_hard, double& time) const
{
auto j = load_backup();
if (is_resume(j, "S2_hard", x_, y_, z_) &&
j["S2_hard"]["low"] >= j["S2_hard"]["z"])
{
double seconds = j["S2_hard"]["seconds"];
s2_hard = calculator::eval<maxint_t>(j["S2_hard"]["s2_hard"]);
time = get_wtime() - seconds;
print_resume(s2_hard, seconds);
return true;
}
return false;
}
void LoadBalancer::finish_resume(int thread_id,
int64_t low,
int64_t segments,
int64_t segment_size,
maxint_t s2,
Runtime& runtime)
{
#pragma omp critical (LoadBalancer)
{
s2_total_ += s2;
update(&low, &segments, runtime);
double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);
auto j = load_backup();
j["S2_hard"]["x"] = to_string(x_);
j["S2_hard"]["y"] = y_;
j["S2_hard"]["z"] = z_;
j["S2_hard"]["low"] = low_;
j["S2_hard"]["segments"] = segments_;
j["S2_hard"]["segment_size"] = segment_size_;
j["S2_hard"]["s2_hard"] = to_string(s2_total_);
j["S2_hard"]["percent"] = percent;
j["S2_hard"]["seconds"] = get_wtime() - time_;
j["S2_hard"].erase("thread" + to_string(thread_id));
store_backup(j);
if (is_print())
status_.print(s2_total_, s2_approx_);
}
}
void LoadBalancer::backup_result() const
{
auto j = load_backup();
if (is_resume(j, "S2_hard", x_, y_, z_))
{
j.erase("S2_hard");
j["S2_hard"]["x"] = to_string(x_);
j["S2_hard"]["y"] = y_;
j["S2_hard"]["z"] = z_;
j["S2_hard"]["low"] = low_;
j["S2_hard"]["s2_hard"] = to_string(s2_total_);
j["S2_hard"]["percent"] = 100;
j["S2_hard"]["seconds"] = get_wtime() - time_;
store_backup(j);
}
}
LoadBalancer::LoadBalancer(maxint_t x,
int64_t y,
int64_t z,
double alpha,
maxint_t s2_approx) :
low_(1),
max_low_(1),
x_(x),
y_(y),
z_(z),
sqrtz_(isqrt(z)),
segments_(1),
s2_total_(0),
s2_approx_(s2_approx),
time_(get_wtime()),
status_(x)
{
init_size();
maxint_t x16 = iroot<6>(x);
smallest_hard_leaf_ = (int64_t) (x / (y * sqrt(alpha) * x16));
}
void LoadBalancer::init_size()
{
int64_t log = ilog(sqrtz_);
log = max(log, 1);
segment_size_ = sqrtz_ / log;
int64_t min = 1 << 9;
segment_size_ = max(segment_size_, min);
segment_size_ = next_power_of_2(segment_size_);
}
maxint_t LoadBalancer::get_result() const
{
return s2_total_;
}
double LoadBalancer::get_time() const
{
return time_;
}
bool LoadBalancer::get_work(int thread_id,
int64_t* low,
int64_t* segments,
int64_t* segment_size,
maxint_t s2,
Runtime& runtime)
{
#pragma omp critical (LoadBalancer)
{
s2_total_ += s2;
update(low, segments, runtime);
*low = low_;
*segments = segments_;
*segment_size = segment_size_;
low_ += segments_ * segment_size_;
backup(thread_id, *low, *segments, *segment_size);
if (is_print())
status_.print(s2_total_, s2_approx_);
}
return *low <= z_;
}
void LoadBalancer::update(int64_t* low,
int64_t* segments,
Runtime& runtime)
{
if (*low > max_low_)
{
max_low_ = *low;
segments_ = *segments;
if (segment_size_ < sqrtz_)
segment_size_ *= 2;
else
{
double next = get_next(runtime);
next = in_between(0.25, next, 2.0);
next *= segments_;
next = max(1.0, next);
segments_ = (int64_t) next;
}
}
auto high = low_ + segments_ * segment_size_;
// Most hard special leaves are located just past
// smallest_hard_leaf_. In order to prevent assigning
// the bulk of work to a single thread we reduce
// the number of segments to a minimum.
//
if (smallest_hard_leaf_ >= low_ &&
smallest_hard_leaf_ <= high)
{
segments_ = 1;
}
}
double LoadBalancer::get_next(Runtime& runtime) const
{
double min_secs = runtime.init * 10;
double run_secs = runtime.secs;
min_secs = max(min_secs, 0.01);
run_secs = max(run_secs, min_secs / 10);
double rem = remaining_secs();
double threshold = rem / 4;
threshold = max(threshold, min_secs);
return threshold / run_secs;
}
/// Remaining seconds till finished
double LoadBalancer::remaining_secs() const
{
double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);
percent = in_between(20, percent, 100);
double total_secs = get_wtime() - time_;
double secs = total_secs * (100 / percent) - total_secs;
return secs;
}
} // namespace
<commit_msg>Refactor<commit_after>///
/// @file LoadBalancer.cpp
/// @brief The LoadBalancer assigns work to the individual
/// threads in the computation of the special leaves
/// in the Lagarias-Miller-Odlyzko and
/// Deleglise-Rivat prime counting algorithms.
///
/// Simply parallelizing the computation of the special leaves in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by
/// subdividing the sieve interval by the number of threads into
/// equally sized subintervals does not scale because the distribution
/// of the special leaves is highly skewed and most special leaves are
/// in the first few segments whereas later on there are very few
/// special leaves.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <LoadBalancer.hpp>
#include <primecount-internal.hpp>
#include <S2Status.hpp>
#include <imath.hpp>
#include <int128_t.hpp>
#include <min.hpp>
#include <calculator.hpp>
#include <json.hpp>
#include <stdint.h>
#include <cmath>
#include <iostream>
#include <iomanip>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace nlohmann;
namespace primecount {
int LoadBalancer::resume_threads() const
{
int threads = 0;
auto j = load_backup();
if (is_resume(j, "S2_hard", x_, y_, z_))
while (j["S2_hard"]["thread" + to_string(threads)].is_object())
threads++;
return threads;
}
void LoadBalancer::backup(int thread_id,
int64_t low,
int64_t segments,
int64_t segment_size) const
{
auto j = load_backup();
double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);
j["S2_hard"]["x"] = to_string(x_);
j["S2_hard"]["y"] = y_;
j["S2_hard"]["z"] = z_;
j["S2_hard"]["low"] = low_;
j["S2_hard"]["segments"] = segments_;
j["S2_hard"]["segment_size"] = segment_size_;
j["S2_hard"]["s2_hard"] = to_string(s2_total_);
j["S2_hard"]["percent"] = percent;
j["S2_hard"]["seconds"] = get_wtime() - time_;
j["S2_hard"]["thread" + to_string(thread_id)]["low"] = low;
j["S2_hard"]["thread" + to_string(thread_id)]["segments"] = segments;
j["S2_hard"]["thread" + to_string(thread_id)]["segment_size"] = segment_size;
store_backup(j);
}
template <typename T>
void print_resume(int thread_id,
T low,
T segments,
T segment_size)
{
if (is_print())
{
if (!print_variables())
cout << endl;
cout << "=== Resuming from primecount.backup ===" << endl;
cout << "thread = " << thread_id << endl;
cout << "low = " << low << endl;
cout << "segments = " << segments << endl;
cout << "segment_size = " << segment_size << endl;
cout << endl;
}
}
template <typename T>
void print_resume(T s2_hard, double seconds)
{
if (is_print())
{
if (!print_variables())
cout << endl;
cout << "=== Resuming from primecount.backup ===" << endl;
cout << "S2_hard = " << s2_hard << endl;
cout << "Seconds: " << fixed << setprecision(3) << seconds << endl;
cout << endl;
}
}
bool LoadBalancer::resume(int thread_id,
int64_t& low,
int64_t& segments,
int64_t& segment_size)
{
bool resumed = false;
#pragma omp critical (LoadBalancer)
{
auto j = load_backup();
if (is_resume(j, "S2_hard", x_, y_, z_))
{
double seconds = j["S2_hard"]["seconds"];
s2_total_ = calculator::eval<maxint_t>(j["S2_hard"]["s2_hard"]);
low_ = j["S2_hard"]["low"];
segments_ = j["S2_hard"]["segments"];
segment_size_ = j["S2_hard"]["segment_size"];
time_ = get_wtime() - seconds;
low = j["S2_hard"]["thread" + to_string(thread_id)]["low"];
segments = j["S2_hard"]["thread" + to_string(thread_id)]["segments"];
segment_size = j["S2_hard"]["thread" + to_string(thread_id)]["segment_size"];
print_resume(thread_id, low, segments, segment_size);
resumed = true;
}
}
return resumed;
}
bool LoadBalancer::resume(maxint_t& s2_hard, double& time) const
{
auto j = load_backup();
if (is_resume(j, "S2_hard", x_, y_, z_) &&
j["S2_hard"]["low"] >= j["S2_hard"]["z"])
{
double seconds = j["S2_hard"]["seconds"];
s2_hard = calculator::eval<maxint_t>(j["S2_hard"]["s2_hard"]);
time = get_wtime() - seconds;
print_resume(s2_hard, seconds);
return true;
}
return false;
}
void LoadBalancer::finish_resume(int thread_id,
int64_t low,
int64_t segments,
int64_t segment_size,
maxint_t s2,
Runtime& runtime)
{
#pragma omp critical (LoadBalancer)
{
s2_total_ += s2;
update(&low, &segments, runtime);
double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);
auto j = load_backup();
j["S2_hard"]["x"] = to_string(x_);
j["S2_hard"]["y"] = y_;
j["S2_hard"]["z"] = z_;
j["S2_hard"]["low"] = low_;
j["S2_hard"]["segments"] = segments_;
j["S2_hard"]["segment_size"] = segment_size_;
j["S2_hard"]["s2_hard"] = to_string(s2_total_);
j["S2_hard"]["percent"] = percent;
j["S2_hard"]["seconds"] = get_wtime() - time_;
j["S2_hard"].erase("thread" + to_string(thread_id));
store_backup(j);
if (is_print())
status_.print(s2_total_, s2_approx_);
}
}
void LoadBalancer::backup_result() const
{
auto j = load_backup();
if (is_resume(j, "S2_hard", x_, y_, z_))
{
j.erase("S2_hard");
j["S2_hard"]["x"] = to_string(x_);
j["S2_hard"]["y"] = y_;
j["S2_hard"]["z"] = z_;
j["S2_hard"]["low"] = low_;
j["S2_hard"]["s2_hard"] = to_string(s2_total_);
j["S2_hard"]["percent"] = 100;
j["S2_hard"]["seconds"] = get_wtime() - time_;
store_backup(j);
}
}
LoadBalancer::LoadBalancer(maxint_t x,
int64_t y,
int64_t z,
double alpha,
maxint_t s2_approx) :
low_(1),
max_low_(1),
x_(x),
y_(y),
z_(z),
sqrtz_(isqrt(z)),
segments_(1),
s2_total_(0),
s2_approx_(s2_approx),
time_(get_wtime()),
status_(x)
{
init_size();
maxint_t x16 = iroot<6>(x);
smallest_hard_leaf_ = (int64_t) (x / (y * sqrt(alpha) * x16));
}
void LoadBalancer::init_size()
{
int64_t log = ilog(sqrtz_);
log = max(log, 1);
segment_size_ = sqrtz_ / log;
int64_t min = 1 << 9;
segment_size_ = max(segment_size_, min);
segment_size_ = next_power_of_2(segment_size_);
}
maxint_t LoadBalancer::get_result() const
{
return s2_total_;
}
double LoadBalancer::get_time() const
{
return time_;
}
bool LoadBalancer::get_work(int thread_id,
int64_t* low,
int64_t* segments,
int64_t* segment_size,
maxint_t s2,
Runtime& runtime)
{
#pragma omp critical (LoadBalancer)
{
s2_total_ += s2;
update(low, segments, runtime);
*low = low_;
*segments = segments_;
*segment_size = segment_size_;
low_ += segments_ * segment_size_;
backup(thread_id, *low, *segments, *segment_size);
if (is_print())
status_.print(s2_total_, s2_approx_);
}
return *low <= z_;
}
void LoadBalancer::update(int64_t* low,
int64_t* segments,
Runtime& runtime)
{
if (*low > max_low_)
{
max_low_ = *low;
segments_ = *segments;
if (segment_size_ < sqrtz_)
segment_size_ *= 2;
else
{
double next = get_next(runtime);
next = in_between(0.25, next, 2.0);
next *= segments_;
next = max(1.0, next);
segments_ = (int64_t) next;
}
}
auto high = low_ + segments_ * segment_size_;
// Most hard special leaves are located just past
// smallest_hard_leaf_. In order to prevent assigning
// the bulk of work to a single thread we reduce
// the number of segments to a minimum.
//
if (smallest_hard_leaf_ >= low_ &&
smallest_hard_leaf_ <= high)
{
segments_ = 1;
}
}
double LoadBalancer::get_next(Runtime& runtime) const
{
double min_secs = runtime.init * 10;
double run_secs = runtime.secs;
min_secs = max(min_secs, 0.01);
run_secs = max(run_secs, min_secs / 10);
double rem = remaining_secs();
double threshold = rem / 4;
threshold = max(threshold, min_secs);
return threshold / run_secs;
}
/// Remaining seconds till finished
double LoadBalancer::remaining_secs() const
{
double percent = status_.getPercent(low_, z_, s2_total_, s2_approx_);
percent = in_between(20, percent, 100);
double total_secs = get_wtime() - time_;
double secs = total_secs * (100 / percent) - total_secs;
return secs;
}
} // namespace
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, 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 <sstream>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "phosphor/trace_event.h"
using phosphor::TraceEvent;
using phosphor::TraceArgument;
/*
* Basic tracepoint_info used in tests
*/
phosphor::tracepoint_info tpi = {
"category",
"name",
{{"arg1", "arg2"}}
};
TEST(TraceEvent, create) {
TraceEvent def;
(void)def;
TraceEvent event(
&tpi,
TraceEvent::Type::Instant,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
}
TEST(TraceEvent, string_check) {
TraceEvent event(
&tpi,
TraceEvent::Type::Instant,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto event_regex = testing::MatchesRegex(
#if GTEST_USES_POSIX_RE
"TraceEvent<[0-9]+d [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{9}, "
"category, name, type=Instant, thread_id=0, "
"arg1=\"Type::is_none\", arg2=\"Type::is_none\">");
#else
"TraceEvent<\\d+d \\d+:\\d+:\\d+.\\d+, "
"category, name, type=Instant, thread_id=0, "
"arg1=\"Type::is_none\", arg2=\"Type::is_none\">");
#endif
// This should probably require linking against GoogleMock
// as well but I think we'll get away with it..
EXPECT_THAT(event.to_string(), event_regex);
std::stringstream s;
s << event;
EXPECT_THAT(s.str(), event_regex);
}
TEST(TraceEvent, typeToString) {
EXPECT_EQ("AsyncStart",
TraceEvent::typeToString(TraceEvent::Type::AsyncStart));
EXPECT_EQ("AsyncEnd", TraceEvent::typeToString(TraceEvent::Type::AsyncEnd));
EXPECT_EQ("SyncStart",
TraceEvent::typeToString(TraceEvent::Type::SyncStart));
EXPECT_EQ("SyncEnd", TraceEvent::typeToString(TraceEvent::Type::SyncEnd));
EXPECT_EQ("Instant", TraceEvent::typeToString(TraceEvent::Type::Instant));
EXPECT_EQ("GlobalInstant",
TraceEvent::typeToString(TraceEvent::Type::GlobalInstant));
EXPECT_THROW(TraceEvent::typeToString(static_cast<TraceEvent::Type>(0xFF)),
std::invalid_argument);
}
TEST(TraceEvent, toJSON) {
TraceEvent event(
&tpi,
TraceEvent::Type::Instant,
0,
{{0, 0}},
{{TraceArgument::Type::is_bool, TraceArgument::Type::is_none}});
auto event_regex = testing::MatchesRegex(
#if GTEST_USES_POSIX_RE
"\\{\"name\":\"name\",\"cat\":\"category\",\"ph\":\"i\",\"s\":\"t\","
"\"ts\":[0-9]+,\"pid\":0,\"tid\":0,"
"\"args\":\\{\"arg1\":false\\}\\}");
#else
"\\{\"name\":\"name\",\"cat\":\"category\",\"ph\":\"i\",\"s\":\"t\","
"\"ts\":\\d+,\"pid\":0,\"tid\":0,"
"\"args\":\\{\"arg1\":false\\}\\}");
#endif
EXPECT_THAT(event.to_json(), event_regex);
}
TEST(TraceEvent, toJSONAlt) {
TraceEvent event(
&tpi,
TraceEvent::Type::SyncEnd,
0,
{{0, 0}},
{{TraceArgument::Type::is_bool, TraceArgument::Type::is_bool}});
auto event_regex = testing::MatchesRegex(
#if GTEST_USES_POSIX_RE
"\\{\"name\":\"name\",\"cat\":\"category\",\"ph\":\"E\","
"\"ts\":[0-9]+,\"pid\":0,\"tid\":0,"
"\"args\":\\{\"arg1\":false,\"arg2\":false\\}\\}");
#else
"\\{\"name\":\"name\",\"cat\":\"category\",\"ph\":\"E\","
"\"ts\":\\d+,\"pid\":0,\"tid\":0,"
"\"args\":\\{\"arg1\":false,\"arg2\":false\\}\\}");
#endif
EXPECT_THAT(event.to_json(), event_regex);
}
class MockTraceEvent : public TraceEvent {
public:
using TraceEvent::typeToJSON;
MockTraceEvent(
const phosphor::tracepoint_info* _tpi,
Type _type,
uint64_t _thread_id,
std::array<TraceArgument, phosphor::arg_count>&& _args,
std::array<TraceArgument::Type, phosphor::arg_count>&& _arg_types)
: TraceEvent(_tpi,
_type,
_thread_id,
std::move(_args),
std::move(_arg_types)) {}
};
TEST(TraceEventTypeToJSON, Instant) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::Instant,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("i", std::string(res.type));
EXPECT_EQ(",\"s\":\"t\"", res.extras);
}
TEST(TraceEventTypeToJSON, SyncStart) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::SyncStart,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("B", std::string(res.type));
EXPECT_EQ("", res.extras);
}
TEST(TraceEventTypeToJSON, SyncEnd) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::SyncEnd,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("E", std::string(res.type));
EXPECT_EQ("", res.extras);
}
TEST(TraceEventTypeToJSON, AsyncStart) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::AsyncStart,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("b", std::string(res.type));
EXPECT_EQ(",\"id\": \"0x0\"", res.extras);
}
TEST(TraceEventTypeToJSON, AsyncEnd) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::AsyncEnd,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("e", std::string(res.type));
EXPECT_EQ(",\"id\": \"0x0\"", res.extras);
}
TEST(TraceEventTypeToJSON, GlobalInstant) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::GlobalInstant,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("i", std::string(res.type));
EXPECT_EQ(",\"s\":\"g\"", res.extras);
}
TEST(TraceEventTypeToJSON, Invalid) {
MockTraceEvent event(
&tpi,
static_cast<TraceEvent::Type>(0xFF),
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
EXPECT_THROW(event.typeToJSON(), std::invalid_argument);
}
TEST(TraceEventTypeToJSON, testProperties) {
using namespace testing;
phosphor::tracepoint_info tpi2 = {
"my_category",
"my_name",
{{"my_arg1", "my_arg2"}}
};
TraceEvent event(
&tpi2,
TraceEvent::Type::Instant,
0,
{{0, 4.5}},
{{TraceArgument::Type::is_int, TraceArgument::Type::is_double}});
EXPECT_STREQ("my_category", event.getCategory());
EXPECT_STREQ("my_name", event.getName());
EXPECT_THAT(event.getArgNames(), testing::ElementsAre(StrEq("my_arg1"),
StrEq("my_arg2")));
EXPECT_EQ(TraceEvent::Type::Instant, event.getType());
EXPECT_EQ(0, event.getArgs()[0].as_int);
EXPECT_EQ(4.5, event.getArgs()[1].as_double);
EXPECT_EQ(TraceArgument::Type::is_int, event.getArgTypes()[0]);
EXPECT_EQ(TraceArgument::Type::is_double, event.getArgTypes()[1]);
}
<commit_msg>Fix string checks in the TraceEvent tests<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, 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 <sstream>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "phosphor/trace_event.h"
using phosphor::TraceEvent;
using phosphor::TraceArgument;
/*
* Basic tracepoint_info used in tests
*/
phosphor::tracepoint_info tpi = {
"category",
"name",
{{"arg1", "arg2"}}
};
TEST(TraceEvent, create) {
TraceEvent def;
(void)def;
TraceEvent event(
&tpi,
TraceEvent::Type::Instant,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
}
TEST(TraceEvent, string_check) {
TraceEvent event(
&tpi,
TraceEvent::Type::Instant,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto event_regex = testing::MatchesRegex(
#if GTEST_USES_POSIX_RE
"TraceEvent<[0-9]+d [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{9}, "
"category, name, type=Instant, thread_id=0, "
"arg1=\"Type::is_none\", arg2=\"Type::is_none\">");
#else
"TraceEvent<\\d+d \\d+:\\d+:\\d+.\\d+, "
"category, name, type=Instant, thread_id=0, "
"arg1=\"Type::is_none\", arg2=\"Type::is_none\">");
#endif
// This should probably require linking against GoogleMock
// as well but I think we'll get away with it..
EXPECT_THAT(event.to_string(), event_regex);
std::stringstream s;
s << event;
EXPECT_THAT(s.str(), event_regex);
}
TEST(TraceEvent, typeToString) {
EXPECT_STREQ("AsyncStart",
TraceEvent::typeToString(TraceEvent::Type::AsyncStart));
EXPECT_STREQ("AsyncEnd", TraceEvent::typeToString(TraceEvent::Type::AsyncEnd));
EXPECT_STREQ("SyncStart",
TraceEvent::typeToString(TraceEvent::Type::SyncStart));
EXPECT_STREQ("SyncEnd", TraceEvent::typeToString(TraceEvent::Type::SyncEnd));
EXPECT_STREQ("Instant", TraceEvent::typeToString(TraceEvent::Type::Instant));
EXPECT_STREQ("GlobalInstant",
TraceEvent::typeToString(TraceEvent::Type::GlobalInstant));
EXPECT_THROW(TraceEvent::typeToString(static_cast<TraceEvent::Type>(0xFF)),
std::invalid_argument);
}
TEST(TraceEvent, toJSON) {
TraceEvent event(
&tpi,
TraceEvent::Type::Instant,
0,
{{0, 0}},
{{TraceArgument::Type::is_bool, TraceArgument::Type::is_none}});
auto event_regex = testing::MatchesRegex(
#if GTEST_USES_POSIX_RE
"\\{\"name\":\"name\",\"cat\":\"category\",\"ph\":\"i\",\"s\":\"t\","
"\"ts\":[0-9]+,\"pid\":0,\"tid\":0,"
"\"args\":\\{\"arg1\":false\\}\\}");
#else
"\\{\"name\":\"name\",\"cat\":\"category\",\"ph\":\"i\",\"s\":\"t\","
"\"ts\":\\d+,\"pid\":0,\"tid\":0,"
"\"args\":\\{\"arg1\":false\\}\\}");
#endif
EXPECT_THAT(event.to_json(), event_regex);
}
TEST(TraceEvent, toJSONAlt) {
TraceEvent event(
&tpi,
TraceEvent::Type::SyncEnd,
0,
{{0, 0}},
{{TraceArgument::Type::is_bool, TraceArgument::Type::is_bool}});
auto event_regex = testing::MatchesRegex(
#if GTEST_USES_POSIX_RE
"\\{\"name\":\"name\",\"cat\":\"category\",\"ph\":\"E\","
"\"ts\":[0-9]+,\"pid\":0,\"tid\":0,"
"\"args\":\\{\"arg1\":false,\"arg2\":false\\}\\}");
#else
"\\{\"name\":\"name\",\"cat\":\"category\",\"ph\":\"E\","
"\"ts\":\\d+,\"pid\":0,\"tid\":0,"
"\"args\":\\{\"arg1\":false,\"arg2\":false\\}\\}");
#endif
EXPECT_THAT(event.to_json(), event_regex);
}
class MockTraceEvent : public TraceEvent {
public:
using TraceEvent::typeToJSON;
MockTraceEvent(
const phosphor::tracepoint_info* _tpi,
Type _type,
uint64_t _thread_id,
std::array<TraceArgument, phosphor::arg_count>&& _args,
std::array<TraceArgument::Type, phosphor::arg_count>&& _arg_types)
: TraceEvent(_tpi,
_type,
_thread_id,
std::move(_args),
std::move(_arg_types)) {}
};
TEST(TraceEventTypeToJSON, Instant) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::Instant,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("i", std::string(res.type));
EXPECT_EQ(",\"s\":\"t\"", res.extras);
}
TEST(TraceEventTypeToJSON, SyncStart) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::SyncStart,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("B", std::string(res.type));
EXPECT_EQ("", res.extras);
}
TEST(TraceEventTypeToJSON, SyncEnd) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::SyncEnd,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("E", std::string(res.type));
EXPECT_EQ("", res.extras);
}
TEST(TraceEventTypeToJSON, AsyncStart) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::AsyncStart,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("b", std::string(res.type));
EXPECT_EQ(",\"id\": \"0x0\"", res.extras);
}
TEST(TraceEventTypeToJSON, AsyncEnd) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::AsyncEnd,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("e", std::string(res.type));
EXPECT_EQ(",\"id\": \"0x0\"", res.extras);
}
TEST(TraceEventTypeToJSON, GlobalInstant) {
MockTraceEvent event(
&tpi,
TraceEvent::Type::GlobalInstant,
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
auto res = event.typeToJSON();
EXPECT_EQ("i", std::string(res.type));
EXPECT_EQ(",\"s\":\"g\"", res.extras);
}
TEST(TraceEventTypeToJSON, Invalid) {
MockTraceEvent event(
&tpi,
static_cast<TraceEvent::Type>(0xFF),
0,
{{0, 0}},
{{TraceArgument::Type::is_none, TraceArgument::Type::is_none}});
EXPECT_THROW(event.typeToJSON(), std::invalid_argument);
}
TEST(TraceEventTypeToJSON, testProperties) {
using namespace testing;
phosphor::tracepoint_info tpi2 = {
"my_category",
"my_name",
{{"my_arg1", "my_arg2"}}
};
TraceEvent event(
&tpi2,
TraceEvent::Type::Instant,
0,
{{0, 4.5}},
{{TraceArgument::Type::is_int, TraceArgument::Type::is_double}});
EXPECT_STREQ("my_category", event.getCategory());
EXPECT_STREQ("my_name", event.getName());
EXPECT_THAT(event.getArgNames(), testing::ElementsAre(StrEq("my_arg1"),
StrEq("my_arg2")));
EXPECT_EQ(TraceEvent::Type::Instant, event.getType());
EXPECT_EQ(0, event.getArgs()[0].as_int);
EXPECT_EQ(4.5, event.getArgs()[1].as_double);
EXPECT_EQ(TraceArgument::Type::is_int, event.getArgTypes()[0]);
EXPECT_EQ(TraceArgument::Type::is_double, event.getArgTypes()[1]);
}
<|endoftext|> |
<commit_before>#include "sshtunneloutconnection.h"
#include "sshtunnelout.h"
#include "sshclient.h"
Q_LOGGING_CATEGORY(logsshtunneloutconnection, "ssh.tunnelout.connection")
Q_LOGGING_CATEGORY(logsshtunneloutconnectiontransfer, "ssh.tunnelout.connection.transfer")
#define DEBUGCH qCDebug(logsshtunneloutconnection) << m_name
#define DEBUGTX qCDebug(logsshtunneloutconnectiontransfer) << m_name
#define SOCKET_WRITE_ERROR (-1001)
SshTunnelOutConnection::SshTunnelOutConnection(const QString &name, SshClient *client)
: SshChannel(name, client)
, m_connector(client, name)
{
QObject::connect(this, &SshTunnelOutConnection::sendEvent, this, &SshTunnelOutConnection::_eventLoop, Qt::QueuedConnection);
QObject::connect(&m_connector, &SshTunnelDataConnector::sendEvent, this, &SshTunnelOutConnection::sendEvent);
DEBUGCH << "Create SshTunnelOutConnection (constructor)";
emit sendEvent();
}
void SshTunnelOutConnection::configure(QTcpServer *server, quint16 remotePort, QString target)
{
m_server = server;
m_port = remotePort;
m_target = target;
}
SshTunnelOutConnection::~SshTunnelOutConnection()
{
DEBUGCH << "Free SshTunnelOutConnection (destructor)";
delete m_sock;
}
void SshTunnelOutConnection::close()
{
DEBUGCH << "Close SshTunnelOutConnection asked";
setChannelState(ChannelState::Close);
emit sendEvent();
}
void SshTunnelOutConnection::sshDataReceived()
{
DEBUGCH << "sshDataReceived: SSH data received";
m_connector.sshDataReceived();
emit sendEvent();
}
void SshTunnelOutConnection::_eventLoop()
{
switch(channelState())
{
case Openning:
{
if ( ! m_sshClient->takeChannelCreationMutex(this) )
{
return;
}
m_sshChannel = libssh2_channel_direct_tcpip(m_sshClient->session(), qPrintable(m_target), m_port);
m_sshClient->releaseChannelCreationMutex(this);
if (m_sshChannel == nullptr)
{
char *emsg;
int size;
int ret = libssh2_session_last_error(m_sshClient->session(), &emsg, &size, 0);
if(ret == LIBSSH2_ERROR_EAGAIN)
{
return;
}
if(!m_error)
{
qCDebug(logsshtunneloutconnection) << "Refuse client socket connection on " << m_server->serverPort() << QString(emsg);
m_error = true;
m_sock = m_server->nextPendingConnection();
if(m_sock)
{
m_sock->close();
}
m_server->close();
}
setChannelState(ChannelState::Error);
qCWarning(logsshtunneloutconnection) << "Channel session open failed";
return;
}
DEBUGCH << "Channel session opened";
setChannelState(ChannelState::Exec);
}
FALLTHROUGH; case Exec:
{
m_sock = m_server->nextPendingConnection();
if(!m_sock)
{
m_server->close();
setChannelState(ChannelState::Error);
qCWarning(logsshtunneloutconnection) << "Fail to get client socket";
setChannelState(ChannelState::Close);
return;
}
QObject::connect(m_sock, &QObject::destroyed, [this](){ DEBUGCH << "Client Socket destroyed";});
m_name = QString(m_name + ":%1").arg(m_sock->localPort());
DEBUGCH << "createConnection: " << m_sock << m_sock->localPort();
m_connector.setChannel(m_sshChannel);
m_connector.setSock(m_sock);
setChannelState(ChannelState::Ready);
/* OK, next step */
}
FALLTHROUGH; case Ready:
{
if(!m_connector.process())
{
setChannelState(ChannelState::Close);
}
return;
}
case Close:
{
DEBUGCH << "closeChannel";
m_connector.close();
setChannelState(ChannelState::WaitClose);
}
FALLTHROUGH; case WaitClose:
{
DEBUGCH << "Wait close channel";
if(m_connector.isClosed())
{
setChannelState(ChannelState::Freeing);
}
else
{
m_connector.process();
return;
}
}
FALLTHROUGH; case Freeing:
{
DEBUGCH << "free Channel";
int ret = libssh2_channel_free(m_sshChannel);
if(ret == LIBSSH2_ERROR_EAGAIN)
{
return;
}
if(ret < 0)
{
if(!m_error)
{
m_error = true;
qCWarning(logsshtunneloutconnection) << "Failed to free channel: " << sshErrorToString(ret);
}
}
if(m_error)
{
setChannelState(ChannelState::Error);
}
else
{
setChannelState(ChannelState::Free);
}
m_sshChannel = nullptr;
QObject::disconnect(m_sshClient, &SshClient::sshDataReceived, this, &SshTunnelOutConnection::sshDataReceived);
return;
}
case Free:
{
qCDebug(logsshtunneloutconnection) << "Channel" << m_name << "is free";
return;
}
case Error:
{
qCDebug(logsshtunneloutconnection) << "Channel" << m_name << "is in error state";
setChannelState(Free);
return;
}
}
}
<commit_msg>tunnelout: Fix issue when connection impossible<commit_after>#include "sshtunneloutconnection.h"
#include "sshtunnelout.h"
#include "sshclient.h"
Q_LOGGING_CATEGORY(logsshtunneloutconnection, "ssh.tunnelout.connection")
Q_LOGGING_CATEGORY(logsshtunneloutconnectiontransfer, "ssh.tunnelout.connection.transfer")
#define DEBUGCH qCDebug(logsshtunneloutconnection) << m_name
#define DEBUGTX qCDebug(logsshtunneloutconnectiontransfer) << m_name
#define SOCKET_WRITE_ERROR (-1001)
SshTunnelOutConnection::SshTunnelOutConnection(const QString &name, SshClient *client)
: SshChannel(name, client)
, m_connector(client, name)
{
QObject::connect(this, &SshTunnelOutConnection::sendEvent, this, &SshTunnelOutConnection::_eventLoop, Qt::QueuedConnection);
QObject::connect(&m_connector, &SshTunnelDataConnector::sendEvent, this, &SshTunnelOutConnection::sendEvent);
DEBUGCH << "Create SshTunnelOutConnection (constructor)";
emit sendEvent();
}
void SshTunnelOutConnection::configure(QTcpServer *server, quint16 remotePort, QString target)
{
m_server = server;
m_port = remotePort;
m_target = target;
}
SshTunnelOutConnection::~SshTunnelOutConnection()
{
DEBUGCH << "Free SshTunnelOutConnection (destructor)";
delete m_sock;
}
void SshTunnelOutConnection::close()
{
DEBUGCH << "Close SshTunnelOutConnection asked";
if(channelState() != ChannelState::Error)
{
setChannelState(ChannelState::Close);
}
emit sendEvent();
}
void SshTunnelOutConnection::sshDataReceived()
{
DEBUGCH << "sshDataReceived: SSH data received";
m_connector.sshDataReceived();
emit sendEvent();
}
void SshTunnelOutConnection::_eventLoop()
{
switch(channelState())
{
case Openning:
{
if ( ! m_sshClient->takeChannelCreationMutex(this) )
{
return;
}
m_sshChannel = libssh2_channel_direct_tcpip(m_sshClient->session(), qPrintable(m_target), m_port);
m_sshClient->releaseChannelCreationMutex(this);
if (m_sshChannel == nullptr)
{
char *emsg;
int size;
int ret = libssh2_session_last_error(m_sshClient->session(), &emsg, &size, 0);
if(ret == LIBSSH2_ERROR_EAGAIN)
{
return;
}
if(!m_error)
{
qCDebug(logsshtunneloutconnection) << "Refuse client socket connection on " << m_server->serverPort() << QString(emsg);
m_error = true;
m_sock = m_server->nextPendingConnection();
if(m_sock)
{
m_sock->close();
}
m_server->close();
}
setChannelState(ChannelState::Error);
qCWarning(logsshtunneloutconnection) << "Channel session open failed";
return;
}
DEBUGCH << "Channel session opened";
setChannelState(ChannelState::Exec);
}
FALLTHROUGH; case Exec:
{
m_sock = m_server->nextPendingConnection();
if(!m_sock)
{
m_server->close();
setChannelState(ChannelState::Error);
qCWarning(logsshtunneloutconnection) << "Fail to get client socket";
setChannelState(ChannelState::Close);
return;
}
QObject::connect(m_sock, &QObject::destroyed, [this](){ DEBUGCH << "Client Socket destroyed";});
m_name = QString(m_name + ":%1").arg(m_sock->localPort());
DEBUGCH << "createConnection: " << m_sock << m_sock->localPort();
m_connector.setChannel(m_sshChannel);
m_connector.setSock(m_sock);
setChannelState(ChannelState::Ready);
/* OK, next step */
}
FALLTHROUGH; case Ready:
{
if(!m_connector.process())
{
setChannelState(ChannelState::Close);
}
return;
}
case Close:
{
DEBUGCH << "closeChannel";
m_connector.close();
setChannelState(ChannelState::WaitClose);
}
FALLTHROUGH; case WaitClose:
{
DEBUGCH << "Wait close channel";
if(m_connector.isClosed())
{
setChannelState(ChannelState::Freeing);
}
else
{
m_connector.process();
return;
}
}
FALLTHROUGH; case Freeing:
{
DEBUGCH << "free Channel";
int ret = libssh2_channel_free(m_sshChannel);
if(ret == LIBSSH2_ERROR_EAGAIN)
{
return;
}
if(ret < 0)
{
if(!m_error)
{
m_error = true;
qCWarning(logsshtunneloutconnection) << "Failed to free channel: " << sshErrorToString(ret);
}
}
if(m_error)
{
setChannelState(ChannelState::Error);
}
else
{
setChannelState(ChannelState::Free);
}
m_sshChannel = nullptr;
QObject::disconnect(m_sshClient, &SshClient::sshDataReceived, this, &SshTunnelOutConnection::sshDataReceived);
return;
}
case Free:
{
qCDebug(logsshtunneloutconnection) << "Channel" << m_name << "is free";
return;
}
case Error:
{
qCDebug(logsshtunneloutconnection) << "Channel" << m_name << "is in error state";
setChannelState(Free);
return;
}
}
}
<|endoftext|> |
<commit_before>#include "LogFormatter.hpp"
#include <algorithm>
#include <ctime>
namespace foo {
std::string LogFormatter::getTimeStamp() {
const auto time = std::time(nullptr);
std::string str = std::string{std::asctime(std::localtime(&time))};
str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
return str;
}
} // namespace foo<commit_msg>Change timestamp format<commit_after>#include "LogFormatter.hpp"
#include <chrono>
#include <iomanip>
#include <sstream>
namespace foo {
std::string LogFormatter::getTimeStamp() {
const auto now = std::chrono::system_clock::now();
const auto nowTime = std::chrono::system_clock::to_time_t(now);
return std::to_string(nowTime);
}
} // namespace foo<|endoftext|> |
<commit_before>/*
* File: PGR_renderer.cpp
* Author: Martin Simon <xsimon14@stud.fit.vutbr.cz>
* Lukas Brzobohaty <xbrzob06@stud.fit.vutbr.cz>
*
* Created on 2013-10-13, 18:20
*/
#include "pgr.h"
#include "PGR_renderer.h"
#include "model.h"
//#include "sphere.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
/* Buffers */
extern GLuint roomVBO, roomEBO;
/* Shaders */
extern GLuint iVS, iFS, iProg;
extern GLuint positionAttrib, colorAttrib, normalAttrib, mvpUniform, laUniform, ldUniform, lightPosUniform;
extern const char * vertexShaderRoom;
extern const char * fragmentShaderRoom;
glm::vec3 light_pos = glm::vec3(0, 2.5, 0);
PGR_renderer::PGR_renderer()
{
}
PGR_renderer::PGR_renderer(int c)
{
this->model = new PGR_model(C_ROOM);
PGR_model * light = new PGR_model(C_LIGHT);
this->model->appendModel(light);
delete light;
this->maxArea = -1.0;
this->divided = true;
this->radiosity = new PGR_radiosity(this->model, c);
}
PGR_renderer::PGR_renderer(const PGR_renderer& orig)
{
}
void PGR_renderer::setResolution(uint w, uint h)
{
this->setWidth(w);
this->setHeight(h);
}
void PGR_renderer::setWidth(uint w)
{
this->width = w;
}
void PGR_renderer::setHeight(uint h)
{
this->height = h;
}
PGR_renderer::~PGR_renderer()
{
delete this->radiosity;
delete this->model;
}
void PGR_renderer::setMaxArea(float area)
{
this->maxArea = area;
this->divided = false;
}
void PGR_renderer::init()
{
/* Create shaders */
iVS = compileShader(GL_VERTEX_SHADER, vertexShaderRoom);
iFS = compileShader(GL_FRAGMENT_SHADER, fragmentShaderRoom);
iProg = linkShader(2, iVS, iFS);
/* Link shader input/output to gl variables */
positionAttrib = glGetAttribLocation(iProg, "position");
normalAttrib = glGetAttribLocation(iProg, "normal");
colorAttrib = glGetAttribLocation(iProg, "color");
mvpUniform = glGetUniformLocation(iProg, "mvp");
laUniform = glGetUniformLocation(iProg, "la");
ldUniform = glGetUniformLocation(iProg, "ld");
lightPosUniform = glGetUniformLocation(iProg, "lightPos");
this->divide();
/* Create buffers */
glGenBuffers(1, &roomVBO);
glGenBuffers(1, &roomEBO);
this->refillBuffers();
}
bool PGR_renderer::divide()
{
if (!this->divided && this->maxArea > 0.0)
{
/* Max area set, need to divide all patches */
this->model->setMaxArea(this->maxArea);
this->model->divide();
this->model->updateArrays();
this->divided = true;
return true;
}
else
return false;
}
void PGR_renderer::printPatches()
{
for (int i = 0; i <this->model->patches.size(); i++)
{
cout << "Patch: " << i << endl;
cout << "\t[" << this->model->patches[i]->vertices[0].position[0] << "," << this->model->patches[i]->vertices[0].position[1] << "," << this->model->patches[i]->vertices[0].position[2] << "]" << endl;
cout << "\t[" << this->model->patches[i]->vertices[1].position[0] << "," << this->model->patches[i]->vertices[1].position[1] << "," << this->model->patches[i]->vertices[1].position[2] << "]" << endl;
cout << "\t[" << this->model->patches[i]->vertices[2].position[0] << "," << this->model->patches[i]->vertices[2].position[1] << "," << this->model->patches[i]->vertices[2].position[2] << "]" << endl;
cout << "\t[" << this->model->patches[i]->vertices[3].position[0] << "," << this->model->patches[i]->vertices[3].position[1] << "," << this->model->patches[i]->vertices[3].position[2] << "]" << endl;
}
}
void PGR_renderer::refillBuffers()
{
glBindBuffer(GL_ARRAY_BUFFER, roomVBO);
glBufferData(GL_ARRAY_BUFFER, this->model->getVerticesCount() * sizeof (Point), this->model->getVertices(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->model->getIndicesCount() * sizeof (unsigned int), this->model->getIndices(), GL_STATIC_DRAW);
}
/**
* Draw 3D scene using default renderer. This rendering should be real-time and
* used to set view angle light sources. It doesn't need to run on GPU.
*/
void PGR_renderer::drawSceneDefault(glm::mat4 mvp)
{
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
glUseProgram(iProg);
glUniformMatrix4fv(mvpUniform, 1, GL_FALSE, glm::value_ptr(mvp));
glUniform3f(laUniform, 0.5, 0.5, 0.5);
glUniform3f(lightPosUniform, light_pos[0], light_pos[1], light_pos[2]);
glUniform3f(ldUniform, 0.5, 0.5, 0.5);
/* Draw room */
glEnableVertexAttribArray(positionAttrib);
glEnableVertexAttribArray(colorAttrib);
glEnableVertexAttribArray(normalAttrib);
glBindBuffer(GL_ARRAY_BUFFER, roomVBO);
glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, position));
glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, color));
glVertexAttribPointer(normalAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, normal));
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO);
glDrawElements(GL_QUADS, this->model->getIndicesCount(), GL_UNSIGNED_INT, NULL);
glDisableVertexAttribArray(positionAttrib);
glDisableVertexAttribArray(colorAttrib);
glDisableVertexAttribArray(normalAttrib);
}
/**
* Draw 3D scene with radiosity computed using OpenCL. This rendering doesn't
* run real-time and also changing of angle/resizing window is not permitted.
*/
void PGR_renderer::drawSceneRadiosity(glm::mat4 mvp)
{
if (!this->radiosity->isComputed())
{
this->radiosity->compute();
this->refillBuffers();
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glUseProgram(iProg);
glViewport(0, 0, this->width, this->height);
glUniformMatrix4fv(mvpUniform, 1, GL_FALSE, glm::value_ptr(mvp));
glUniform3f(laUniform, 0.2, 0.2, 0.2); //turn off basic shadows
glUniform3f(ldUniform, 0.0, 0.0, 0.0); //turn off basic shadows
/* Draw room */
glEnableVertexAttribArray(positionAttrib);
glEnableVertexAttribArray(colorAttrib);
glBindBuffer(GL_ARRAY_BUFFER, roomVBO);
glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, position));
glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, color));
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO);
glDrawElements(GL_QUADS, this->model->getIndicesCount(), GL_UNSIGNED_INT, NULL);
glDisableVertexAttribArray(positionAttrib);
glDisableVertexAttribArray(colorAttrib);
}
<commit_msg>Turned light on<commit_after>/*
* File: PGR_renderer.cpp
* Author: Martin Simon <xsimon14@stud.fit.vutbr.cz>
* Lukas Brzobohaty <xbrzob06@stud.fit.vutbr.cz>
*
* Created on 2013-10-13, 18:20
*/
#include "pgr.h"
#include "PGR_renderer.h"
#include "model.h"
//#include "sphere.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
/* Buffers */
extern GLuint roomVBO, roomEBO;
/* Shaders */
extern GLuint iVS, iFS, iProg;
extern GLuint positionAttrib, colorAttrib, normalAttrib, mvpUniform, laUniform, ldUniform, lightPosUniform;
extern const char * vertexShaderRoom;
extern const char * fragmentShaderRoom;
glm::vec3 light_pos = glm::vec3(0, 2.5, 0);
PGR_renderer::PGR_renderer()
{
}
PGR_renderer::PGR_renderer(int c)
{
this->model = new PGR_model(C_ROOM);
PGR_model * light = new PGR_model(C_LIGHT);
this->model->appendModel(light);
delete light;
this->maxArea = -1.0;
this->divided = true;
this->radiosity = new PGR_radiosity(this->model, c);
}
PGR_renderer::PGR_renderer(const PGR_renderer& orig)
{
}
void PGR_renderer::setResolution(uint w, uint h)
{
this->setWidth(w);
this->setHeight(h);
}
void PGR_renderer::setWidth(uint w)
{
this->width = w;
}
void PGR_renderer::setHeight(uint h)
{
this->height = h;
}
PGR_renderer::~PGR_renderer()
{
delete this->radiosity;
delete this->model;
}
void PGR_renderer::setMaxArea(float area)
{
this->maxArea = area;
this->divided = false;
}
void PGR_renderer::init()
{
/* Create shaders */
iVS = compileShader(GL_VERTEX_SHADER, vertexShaderRoom);
iFS = compileShader(GL_FRAGMENT_SHADER, fragmentShaderRoom);
iProg = linkShader(2, iVS, iFS);
/* Link shader input/output to gl variables */
positionAttrib = glGetAttribLocation(iProg, "position");
normalAttrib = glGetAttribLocation(iProg, "normal");
colorAttrib = glGetAttribLocation(iProg, "color");
mvpUniform = glGetUniformLocation(iProg, "mvp");
laUniform = glGetUniformLocation(iProg, "la");
ldUniform = glGetUniformLocation(iProg, "ld");
lightPosUniform = glGetUniformLocation(iProg, "lightPos");
this->divide();
/* Create buffers */
glGenBuffers(1, &roomVBO);
glGenBuffers(1, &roomEBO);
this->refillBuffers();
}
bool PGR_renderer::divide()
{
if (!this->divided && this->maxArea > 0.0)
{
/* Max area set, need to divide all patches */
this->model->setMaxArea(this->maxArea);
this->model->divide();
this->model->updateArrays();
this->divided = true;
return true;
}
else
return false;
}
void PGR_renderer::printPatches()
{
for (int i = 0; i <this->model->patches.size(); i++)
{
cout << "Patch: " << i << endl;
cout << "\t[" << this->model->patches[i]->vertices[0].position[0] << "," << this->model->patches[i]->vertices[0].position[1] << "," << this->model->patches[i]->vertices[0].position[2] << "]" << endl;
cout << "\t[" << this->model->patches[i]->vertices[1].position[0] << "," << this->model->patches[i]->vertices[1].position[1] << "," << this->model->patches[i]->vertices[1].position[2] << "]" << endl;
cout << "\t[" << this->model->patches[i]->vertices[2].position[0] << "," << this->model->patches[i]->vertices[2].position[1] << "," << this->model->patches[i]->vertices[2].position[2] << "]" << endl;
cout << "\t[" << this->model->patches[i]->vertices[3].position[0] << "," << this->model->patches[i]->vertices[3].position[1] << "," << this->model->patches[i]->vertices[3].position[2] << "]" << endl;
}
}
void PGR_renderer::refillBuffers()
{
glBindBuffer(GL_ARRAY_BUFFER, roomVBO);
glBufferData(GL_ARRAY_BUFFER, this->model->getVerticesCount() * sizeof (Point), this->model->getVertices(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->model->getIndicesCount() * sizeof (unsigned int), this->model->getIndices(), GL_STATIC_DRAW);
}
/**
* Draw 3D scene using default renderer. This rendering should be real-time and
* used to set view angle light sources. It doesn't need to run on GPU.
*/
void PGR_renderer::drawSceneDefault(glm::mat4 mvp)
{
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
glUseProgram(iProg);
glUniformMatrix4fv(mvpUniform, 1, GL_FALSE, glm::value_ptr(mvp));
glUniform3f(laUniform, 0.5, 0.5, 0.5);
glUniform3f(lightPosUniform, light_pos[0], light_pos[1], light_pos[2]);
glUniform3f(ldUniform, 0.5, 0.5, 0.5);
/* Draw room */
glEnableVertexAttribArray(positionAttrib);
glEnableVertexAttribArray(colorAttrib);
glEnableVertexAttribArray(normalAttrib);
glBindBuffer(GL_ARRAY_BUFFER, roomVBO);
glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, position));
glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, color));
glVertexAttribPointer(normalAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, normal));
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO);
glDrawElements(GL_QUADS, this->model->getIndicesCount(), GL_UNSIGNED_INT, NULL);
glDisableVertexAttribArray(positionAttrib);
glDisableVertexAttribArray(colorAttrib);
glDisableVertexAttribArray(normalAttrib);
}
/**
* Draw 3D scene with radiosity computed using OpenCL. This rendering doesn't
* run real-time and also changing of angle/resizing window is not permitted.
*/
void PGR_renderer::drawSceneRadiosity(glm::mat4 mvp)
{
if (!this->radiosity->isComputed())
{
this->radiosity->compute();
this->refillBuffers();
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glUseProgram(iProg);
glViewport(0, 0, this->width, this->height);
glUniformMatrix4fv(mvpUniform, 1, GL_FALSE, glm::value_ptr(mvp));
glUniform3f(laUniform, 1.0, 1.0, 1.0); //turn off basic shadows
glUniform3f(ldUniform, 0.0, 0.0, 0.0); //turn off basic shadows
/* Draw room */
glEnableVertexAttribArray(positionAttrib);
glEnableVertexAttribArray(colorAttrib);
glBindBuffer(GL_ARRAY_BUFFER, roomVBO);
glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, position));
glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof (Point), (void*) offsetof(Point, color));
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, roomEBO);
glDrawElements(GL_QUADS, this->model->getIndicesCount(), GL_UNSIGNED_INT, NULL);
glDisableVertexAttribArray(positionAttrib);
glDisableVertexAttribArray(colorAttrib);
}
<|endoftext|> |
<commit_before>/* logsh.cpp
*
* cxxtools - general purpose C++-toolbox
* Copyright (C) 2005 Tommi Maekitalo
*
* 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 <cxxtools/log.h>
#include <cxxtools/loginit.h>
#include <cxxtools/arg.h>
#include <iostream>
const char* category = "logsh";
log_define(category)
int main(int argc, char* argv[])
{
try
{
cxxtools::Arg<bool> fatal;
fatal.set(argc, argv, 'f');
fatal.set(argc, argv, "--fatal");
cxxtools::Arg<bool> error;
error.set(argc, argv, 'e');
error.set(argc, argv, "--error");
cxxtools::Arg<bool> warn;
warn.set(argc, argv, 'w');
warn.set(argc, argv, "--warn");
cxxtools::Arg<bool> info;
info.set(argc, argv, 'i');
info.set(argc, argv, "--info");
cxxtools::Arg<bool> debug;
debug.set(argc, argv, 'd');
debug.set(argc, argv, "--debug");
cxxtools::Arg<std::string> properties("log4j.properties");
properties.set(argc, argv, 'p');
properties.set(argc, argv, "--properties");
if (argc <= 2)
{
std::cerr << "usage: " << argv[0] << " [options] category message\n"
"\toptions: -f|--fatal\n"
"\t -e|--error\n"
"\t -w|--warn\n"
"\t -i|--info\n"
"\t -d|--debug\n"
"\t -p|--properties filename" << std::endl;
return -1;
}
log_init(properties.getValue());
category = argv[1];
for (int a = 2; a < argc; ++a)
{
if (fatal)
log_fatal(argv[a]);
else if (error)
log_error(argv[a]);
else if (warn)
log_warn(argv[a]);
else if (debug)
log_debug(argv[a]);
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return -1;
}
}
<commit_msg>info-messages where not printed at all<commit_after>/* logsh.cpp
*
* cxxtools - general purpose C++-toolbox
* Copyright (C) 2005 Tommi Maekitalo
*
* 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 <cxxtools/log.h>
#include <cxxtools/loginit.h>
#include <cxxtools/arg.h>
#include <iostream>
const char* category = "logsh";
log_define(category)
int main(int argc, char* argv[])
{
try
{
cxxtools::Arg<bool> fatal;
fatal.set(argc, argv, 'f');
fatal.set(argc, argv, "--fatal");
cxxtools::Arg<bool> error;
error.set(argc, argv, 'e');
error.set(argc, argv, "--error");
cxxtools::Arg<bool> warn;
warn.set(argc, argv, 'w');
warn.set(argc, argv, "--warn");
cxxtools::Arg<bool> info;
info.set(argc, argv, 'i');
info.set(argc, argv, "--info");
cxxtools::Arg<bool> debug;
debug.set(argc, argv, 'd');
debug.set(argc, argv, "--debug");
cxxtools::Arg<std::string> properties("log4j.properties");
properties.set(argc, argv, 'p');
properties.set(argc, argv, "--properties");
if (argc <= 2)
{
std::cerr << "usage: " << argv[0] << " [options] category message\n"
"\toptions: -f|--fatal\n"
"\t -e|--error\n"
"\t -w|--warn\n"
"\t -i|--info\n"
"\t -d|--debug\n"
"\t -p|--properties filename" << std::endl;
return -1;
}
log_init(properties.getValue());
category = argv[1];
for (int a = 2; a < argc; ++a)
{
if (fatal)
log_fatal(argv[a]);
else if (error)
log_error(argv[a]);
else if (warn)
log_warn(argv[a]);
else if (info)
log_info(argv[a]);
else if (debug)
log_debug(argv[a]);
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return -1;
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
created: Sun Mar 13 2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/XMLParserModules/TinyXML/XMLParser.h"
#include "CEGUI/ResourceProvider.h"
#include "CEGUI/System.h"
#include "CEGUI/XMLHandler.h"
#include "CEGUI/XMLAttributes.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Exceptions.h"
#include <tinyxml.h>
//---------------------------------------------------------------------------//
// These are to support the <=2.5 and >=2.6 API versions
#ifdef CEGUI_TINYXML_HAS_2_6_API
# define CEGUI_TINYXML_ELEMENT TINYXML_ELEMENT
# define CEGUI_TINYXML_TEXT TINYXML_TEXT
#else
# define CEGUI_TINYXML_ELEMENT ELEMENT
# define CEGUI_TINYXML_TEXT TEXT
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
class TinyXMLDocument : public TiXmlDocument
{
public:
TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& schemaName);
~TinyXMLDocument()
{}
protected:
void processElement(const TiXmlElement* element);
private:
XMLHandler* d_handler;
};
TinyXMLDocument::TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& /*schemaName*/)
{
d_handler = &handler;
// Create a buffer with extra bytes for a newline and a terminating null
size_t size = source.getSize();
char* buf = new char[size + 2];
memcpy(buf, source.getDataPtr(), size);
// PDT: The addition of the newline is a kludge to resolve an issue
// whereby parse returns 0 if the xml file has no newline at the end but
// is otherwise well formed.
buf[size] = '\n';
buf[size+1] = 0;
// Parse the document
TiXmlDocument doc;
if (!doc.Parse(static_cast<const char*>(buf)))
{
// error detected, cleanup out buffers
delete[] buf;
// throw exception
throw FileIOException("an error occurred while "
"parsing the XML document - check it for potential errors!.");
}
const TiXmlElement* currElement = doc.RootElement();
if (currElement)
{
try
{
// function called recursively to parse xml data
processElement(currElement);
}
catch (...)
{
delete [] buf;
throw;
}
} // if (currElement)
// Free memory
delete [] buf;
}
void TinyXMLDocument::processElement(const TiXmlElement* element)
{
// build attributes block for the element
XMLAttributes attrs;
const TiXmlAttribute *currAttr = element->FirstAttribute();
while (currAttr)
{
attrs.add(currAttr->Name(), currAttr->Value());
currAttr = currAttr->Next();
}
// start element
d_handler->elementStart(element->Value(), attrs);
// do children
const TiXmlNode* childNode = element->FirstChild();
while (childNode)
{
switch(childNode->Type())
{
case TiXmlNode::CEGUI_TINYXML_ELEMENT:
processElement(childNode->ToElement());
break;
case TiXmlNode::CEGUI_TINYXML_TEXT:
if (childNode->ToText()->Value() != '\0')
d_handler->text(childNode->ToText()->Value());
break;
// Silently ignore unhandled node type
};
childNode = childNode->NextSibling();
}
// end element
d_handler->elementEnd(element->Value());
}
TinyXMLParser::TinyXMLParser(void)
{
// set ID string
d_identifierString = "CEGUI::TinyXMLParser - Official tinyXML based parser module for CEGUI";
}
TinyXMLParser::~TinyXMLParser(void)
{}
void TinyXMLParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName, bool /*allowXmlValidation*/)
{
TinyXMLDocument doc(handler, source, schemaName);
}
bool TinyXMLParser::initialiseImpl(void)
{
// This used to prevent deletion of line ending in the middle of a text.
// WhiteSpace cleaning will be available throught the use of String methods directly
//TiXmlDocument::SetCondenseWhiteSpace(false);
return true;
}
void TinyXMLParser::cleanupImpl(void)
{}
} // End of CEGUI namespace section
<commit_msg>Fixed compile error in TinyXML based parser<commit_after>/***********************************************************************
created: Sun Mar 13 2005
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/XMLParserModules/TinyXML/XMLParser.h"
#include "CEGUI/ResourceProvider.h"
#include "CEGUI/System.h"
#include "CEGUI/XMLHandler.h"
#include "CEGUI/XMLAttributes.h"
#include "CEGUI/Logger.h"
#include "CEGUI/Exceptions.h"
#include <tinyxml.h>
//---------------------------------------------------------------------------//
// These are to support the <=2.5 and >=2.6 API versions
#ifdef CEGUI_TINYXML_HAS_2_6_API
# define CEGUI_TINYXML_ELEMENT TINYXML_ELEMENT
# define CEGUI_TINYXML_TEXT TINYXML_TEXT
#else
# define CEGUI_TINYXML_ELEMENT ELEMENT
# define CEGUI_TINYXML_TEXT TEXT
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
class TinyXMLDocument : public TiXmlDocument
{
public:
TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& schemaName);
~TinyXMLDocument()
{}
protected:
void processElement(const TiXmlElement* element);
private:
XMLHandler* d_handler;
};
TinyXMLDocument::TinyXMLDocument(XMLHandler& handler, const RawDataContainer& source, const String& /*schemaName*/)
{
d_handler = &handler;
// Create a buffer with extra bytes for a newline and a terminating null
size_t size = source.getSize();
char* buf = new char[size + 2];
memcpy(buf, source.getDataPtr(), size);
// PDT: The addition of the newline is a kludge to resolve an issue
// whereby parse returns 0 if the xml file has no newline at the end but
// is otherwise well formed.
buf[size] = '\n';
buf[size+1] = 0;
// Parse the document
TiXmlDocument doc;
if (!doc.Parse(static_cast<const char*>(buf)))
{
// error detected, cleanup out buffers
delete[] buf;
// throw exception
throw FileIOException("an error occurred while "
"parsing the XML document - check it for potential errors!.");
}
const TiXmlElement* currElement = doc.RootElement();
if (currElement)
{
try
{
// function called recursively to parse xml data
processElement(currElement);
}
catch (...)
{
delete [] buf;
throw;
}
} // if (currElement)
// Free memory
delete [] buf;
}
void TinyXMLDocument::processElement(const TiXmlElement* element)
{
// build attributes block for the element
XMLAttributes attrs;
const TiXmlAttribute *currAttr = element->FirstAttribute();
while (currAttr)
{
attrs.add(currAttr->Name(), currAttr->Value());
currAttr = currAttr->Next();
}
// start element
d_handler->elementStart(element->Value(), attrs);
// do children
const TiXmlNode* childNode = element->FirstChild();
while (childNode)
{
switch(childNode->Type())
{
case TiXmlNode::CEGUI_TINYXML_ELEMENT:
processElement(childNode->ToElement());
break;
case TiXmlNode::CEGUI_TINYXML_TEXT:
if (childNode->ToText()->Value() != nullptr)
d_handler->text(childNode->ToText()->Value());
break;
// Silently ignore unhandled node type
};
childNode = childNode->NextSibling();
}
// end element
d_handler->elementEnd(element->Value());
}
TinyXMLParser::TinyXMLParser(void)
{
// set ID string
d_identifierString = "CEGUI::TinyXMLParser - Official tinyXML based parser module for CEGUI";
}
TinyXMLParser::~TinyXMLParser(void)
{}
void TinyXMLParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName, bool /*allowXmlValidation*/)
{
TinyXMLDocument doc(handler, source, schemaName);
}
bool TinyXMLParser::initialiseImpl(void)
{
// This used to prevent deletion of line ending in the middle of a text.
// WhiteSpace cleaning will be available throught the use of String methods directly
//TiXmlDocument::SetCondenseWhiteSpace(false);
return true;
}
void TinyXMLParser::cleanupImpl(void)
{}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005 by Dr. Marc Boris Duerner
* Copyright (C) 2005 Stephan Beal
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 "cxxtools/signal.h"
namespace cxxtools {
SignalBase::Sentry::Sentry(const SignalBase* signal)
: _signal(signal)
{
_signal->_sentry = this;
_signal->_sending = true;
_signal->_dirty = false;
}
SignalBase::Sentry::~Sentry()
{
if( _signal )
this->detach();
}
void SignalBase::Sentry::detach()
{
_signal->_sending = false;
if( _signal->_dirty == false )
{
_signal->_sentry = 0;
_signal = 0;
return;
}
std::list<Connection>::iterator it = _signal->_connections.begin();
while( it != _signal->_connections.end() )
{
if( it->valid() )
{
++it;
}
else
{
it = _signal->_connections.erase(it);
}
}
_signal->_dirty = false;
_signal->_sentry = 0;
_signal = 0;
}
SignalBase::SignalBase()
: _sentry(0)
, _sending(false)
, _dirty(false)
{ }
SignalBase::~SignalBase()
{
if(_sentry)
{
_sentry->detach();
}
}
SignalBase& SignalBase::operator=(const SignalBase& other)
{
this->clear();
std::list<Connection>::const_iterator it = other.connections().begin();
std::list<Connection>::const_iterator end = other.connections().end();
for( ; it != end; ++it)
{
const Connectable& signal = it->sender();
if( &signal == &other)
{
const Slot& slot = it->slot();
Connection connection( *this, slot.clone() );
}
}
return *this;
}
void SignalBase::onConnectionOpen(const Connection& c)
{
Connectable::onConnectionOpen(c);
}
void SignalBase::onConnectionClose(const Connection& c)
{
// if the signal is currently calling its slots, do not
// remove the connection now, but only set the cleanup flag
// Any invalid connection objects will be removed after
// the signal has finished calling its slots by the Sentry.
if( _sending )
{
_dirty = true;
}
else
{
Connectable::onConnectionClose(c);
}
}
void SignalBase::disconnectSlot(const Slot& slot)
{
std::list<Connection>::iterator it = Connectable::connections().begin();
std::list<Connection>::iterator end = Connectable::connections().end();
for(; it != end; ++it)
{
if( it->slot().equals(slot) )
{
it->close();
return;
}
}
}
bool CompareEventTypeInfo::operator()(const std::type_info* t1,
const std::type_info* t2) const
{
if(t2 == 0)
return false;
if(t1 == 0)
return true;
return t1->before(*t2) != 0;
}
Signal<const cxxtools::Event&>::Sentry::Sentry(const Signal* signal)
: _signal(signal)
{
_signal->_sentry = this;
_signal->_sending = true;
_signal->_dirty = false;
}
Signal<const cxxtools::Event&>::Sentry::~Sentry()
{
if( _signal )
this->detach();
}
void Signal<const cxxtools::Event&>::Sentry::detach()
{
_signal->_sending = false;
if( _signal->_dirty == false )
{
_signal->_sentry = 0;
_signal = 0;
return;
}
Signal::RouteMap::iterator it = _signal->_routes.begin();
while( it != _signal->_routes.end() )
{
if( it->second->valid() )
{
++it;
}
else
{
delete it->second;
_signal->_routes.erase(it++);
}
}
_signal->_dirty = false;
_signal->_sentry = 0;
_signal = 0;
}
Signal<const cxxtools::Event&>::Signal()
: _sentry(0)
, _sending(false)
, _dirty(false)
{}
Signal<const cxxtools::Event&>::~Signal()
{
if(_sentry)
_sentry->detach();
while( ! _routes.empty() )
{
IEventRoute* route = _routes.begin()->second;
route->connection().close();
}
}
void Signal<const cxxtools::Event&>::send(const cxxtools::Event& ev) const
{
// The sentry will set the Signal to the sending state and
// reset it to not-sending upon destruction. In the sending
// state, removing connection will leave invalid connections
// in the connection list to keep the iterator valid, but mark
// the Signal dirty. If the Signal is dirty, all invalid
// connections will be removed by the Sentry when it destructs..
Signal::Sentry sentry(this);
RouteMap::iterator it = _routes.begin();
while( true )
{
if( it == _routes.end() )
return;
if(it->first != 0)
break;
// The following scenarios must be considered when the
// slot is called:
// - The slot might get deleted and thus disconnected from
// this signal
// - The slot might delete this signal and we must end
// calling any slots immediately
// - A new Connection might get added to this Signal in
// the slot
IEventRoute* route = it->second;
if( route->valid() )
route->route(ev);
// if this signal gets deleted by the slot, the Sentry
// will be detached. In this case we bail out immediately
if( !sentry )
return;
++it;
}
const std::type_info& ti = ev.typeInfo();
it = _routes.lower_bound( &ti );
while(it != _routes.end() && *(it->first) == ti)
{
IEventRoute* route = it->second;
if(route)
route->route(ev);
++it;
// if this signal gets deleted by the slot, the Sentry
// will be detached. In this case we bail out immediately
if( !sentry )
return;
}
}
void Signal<const cxxtools::Event&>::onConnectionOpen(const Connection& c)
{
const Connectable& sender = c.sender();
if(&sender != this)
{
return Connectable::onConnectionOpen(c);
}
}
void Signal<const cxxtools::Event&>::onConnectionClose(const Connection& c)
{
// if the signal is currently calling its slots, do not
// remove the connection now, but only set the cleanup flag
// Any invalid connection objects will be removed after
// the signal has finished calling its slots by the Sentry.
if( _sending )
{
_dirty = true;
}
else
{
RouteMap::iterator it;
for(it = _routes.begin(); it != _routes.end(); ++it )
{
IEventRoute* route = it->second;
if(route->connection() == c )
{
delete route;
_routes.erase(it++);
return;
}
}
Connectable::onConnectionClose(c);
}
}
void Signal<const cxxtools::Event&>::addRoute(const std::type_info* ti, IEventRoute* route)
{
_routes.insert( std::make_pair(ti, route) );
}
void Signal<const cxxtools::Event&>::removeRoute(const Slot& slot)
{
RouteMap::iterator it = _routes.begin();
while( it != _routes.end() && it->first == 0 )
{
IEventRoute* route = it->second;
if(route->connection().slot().equals(slot) )
{
route->connection().close();
break;
}
}
}
void Signal<const cxxtools::Event&>::removeRoute(const std::type_info* ti, const Slot& slot)
{
RouteMap::iterator it = _routes.lower_bound( ti );
while(it != _routes.end() && *(it->first) == *ti)
{
IEventRoute* route = it->second;
if(route->connection().slot().equals(slot) )
{
route->connection().close();
break;
}
}
}
}
<commit_msg>do not use make_pair since there are incomplete stl implementations, which do not have it<commit_after>/*
* Copyright (C) 2005 by Dr. Marc Boris Duerner
* Copyright (C) 2005 Stephan Beal
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 "cxxtools/signal.h"
namespace cxxtools {
SignalBase::Sentry::Sentry(const SignalBase* signal)
: _signal(signal)
{
_signal->_sentry = this;
_signal->_sending = true;
_signal->_dirty = false;
}
SignalBase::Sentry::~Sentry()
{
if( _signal )
this->detach();
}
void SignalBase::Sentry::detach()
{
_signal->_sending = false;
if( _signal->_dirty == false )
{
_signal->_sentry = 0;
_signal = 0;
return;
}
std::list<Connection>::iterator it = _signal->_connections.begin();
while( it != _signal->_connections.end() )
{
if( it->valid() )
{
++it;
}
else
{
it = _signal->_connections.erase(it);
}
}
_signal->_dirty = false;
_signal->_sentry = 0;
_signal = 0;
}
SignalBase::SignalBase()
: _sentry(0)
, _sending(false)
, _dirty(false)
{ }
SignalBase::~SignalBase()
{
if(_sentry)
{
_sentry->detach();
}
}
SignalBase& SignalBase::operator=(const SignalBase& other)
{
this->clear();
std::list<Connection>::const_iterator it = other.connections().begin();
std::list<Connection>::const_iterator end = other.connections().end();
for( ; it != end; ++it)
{
const Connectable& signal = it->sender();
if( &signal == &other)
{
const Slot& slot = it->slot();
Connection connection( *this, slot.clone() );
}
}
return *this;
}
void SignalBase::onConnectionOpen(const Connection& c)
{
Connectable::onConnectionOpen(c);
}
void SignalBase::onConnectionClose(const Connection& c)
{
// if the signal is currently calling its slots, do not
// remove the connection now, but only set the cleanup flag
// Any invalid connection objects will be removed after
// the signal has finished calling its slots by the Sentry.
if( _sending )
{
_dirty = true;
}
else
{
Connectable::onConnectionClose(c);
}
}
void SignalBase::disconnectSlot(const Slot& slot)
{
std::list<Connection>::iterator it = Connectable::connections().begin();
std::list<Connection>::iterator end = Connectable::connections().end();
for(; it != end; ++it)
{
if( it->slot().equals(slot) )
{
it->close();
return;
}
}
}
bool CompareEventTypeInfo::operator()(const std::type_info* t1,
const std::type_info* t2) const
{
if(t2 == 0)
return false;
if(t1 == 0)
return true;
return t1->before(*t2) != 0;
}
Signal<const cxxtools::Event&>::Sentry::Sentry(const Signal* signal)
: _signal(signal)
{
_signal->_sentry = this;
_signal->_sending = true;
_signal->_dirty = false;
}
Signal<const cxxtools::Event&>::Sentry::~Sentry()
{
if( _signal )
this->detach();
}
void Signal<const cxxtools::Event&>::Sentry::detach()
{
_signal->_sending = false;
if( _signal->_dirty == false )
{
_signal->_sentry = 0;
_signal = 0;
return;
}
Signal::RouteMap::iterator it = _signal->_routes.begin();
while( it != _signal->_routes.end() )
{
if( it->second->valid() )
{
++it;
}
else
{
delete it->second;
_signal->_routes.erase(it++);
}
}
_signal->_dirty = false;
_signal->_sentry = 0;
_signal = 0;
}
Signal<const cxxtools::Event&>::Signal()
: _sentry(0)
, _sending(false)
, _dirty(false)
{}
Signal<const cxxtools::Event&>::~Signal()
{
if(_sentry)
_sentry->detach();
while( ! _routes.empty() )
{
IEventRoute* route = _routes.begin()->second;
route->connection().close();
}
}
void Signal<const cxxtools::Event&>::send(const cxxtools::Event& ev) const
{
// The sentry will set the Signal to the sending state and
// reset it to not-sending upon destruction. In the sending
// state, removing connection will leave invalid connections
// in the connection list to keep the iterator valid, but mark
// the Signal dirty. If the Signal is dirty, all invalid
// connections will be removed by the Sentry when it destructs..
Signal::Sentry sentry(this);
RouteMap::iterator it = _routes.begin();
while( true )
{
if( it == _routes.end() )
return;
if(it->first != 0)
break;
// The following scenarios must be considered when the
// slot is called:
// - The slot might get deleted and thus disconnected from
// this signal
// - The slot might delete this signal and we must end
// calling any slots immediately
// - A new Connection might get added to this Signal in
// the slot
IEventRoute* route = it->second;
if( route->valid() )
route->route(ev);
// if this signal gets deleted by the slot, the Sentry
// will be detached. In this case we bail out immediately
if( !sentry )
return;
++it;
}
const std::type_info& ti = ev.typeInfo();
it = _routes.lower_bound( &ti );
while(it != _routes.end() && *(it->first) == ti)
{
IEventRoute* route = it->second;
if(route)
route->route(ev);
++it;
// if this signal gets deleted by the slot, the Sentry
// will be detached. In this case we bail out immediately
if( !sentry )
return;
}
}
void Signal<const cxxtools::Event&>::onConnectionOpen(const Connection& c)
{
const Connectable& sender = c.sender();
if(&sender != this)
{
return Connectable::onConnectionOpen(c);
}
}
void Signal<const cxxtools::Event&>::onConnectionClose(const Connection& c)
{
// if the signal is currently calling its slots, do not
// remove the connection now, but only set the cleanup flag
// Any invalid connection objects will be removed after
// the signal has finished calling its slots by the Sentry.
if( _sending )
{
_dirty = true;
}
else
{
RouteMap::iterator it;
for(it = _routes.begin(); it != _routes.end(); ++it )
{
IEventRoute* route = it->second;
if(route->connection() == c )
{
delete route;
_routes.erase(it++);
return;
}
}
Connectable::onConnectionClose(c);
}
}
void Signal<const cxxtools::Event&>::addRoute(const std::type_info* ti, IEventRoute* route)
{
RouteMap::value_type elem(ti, route);
_routes.insert( elem );
}
void Signal<const cxxtools::Event&>::removeRoute(const Slot& slot)
{
RouteMap::iterator it = _routes.begin();
while( it != _routes.end() && it->first == 0 )
{
IEventRoute* route = it->second;
if(route->connection().slot().equals(slot) )
{
route->connection().close();
break;
}
}
}
void Signal<const cxxtools::Event&>::removeRoute(const std::type_info* ti, const Slot& slot)
{
RouteMap::iterator it = _routes.lower_bound( ti );
while(it != _routes.end() && *(it->first) == *ti)
{
IEventRoute* route = it->second;
if(route->connection().slot().equals(slot) )
{
route->connection().close();
break;
}
}
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <math.h>
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <boost/shared_ptr.hpp>
#include <fstream>
using namespace std;
// A serial interface used to send commands to the Arduino that controls
// the motor controllers. (Yeah, recursion!)
std::fstream tty;
// for odometry
ros::Time currentTime;
ros::Time lastTime;
ros::Publisher odomPub;
boost::shared_ptr<tf::TransformBroadcaster> odomBroadcaster;
double x = 0;
double y = 0;
double theta = 0;
double vx = 0;
double vy = 0;
double vtheta = 0;
void velocityCallback(const geometry_msgs::Twist& msg) {
//ROS_INFO("%f", msg.linear.x);
// Store odometry input values
lastTime = currentTime;
currentTime = ros::Time::now();
vx = msg.linear.x;
vy = msg.linear.y;
vtheta = msg.angular.z * 10; // absolutely uneducated guess
// Tank-like steering (rotate around vehicle center)
// Set linear back/forward speed
double leftSpd = msg.linear.x;
double rightSpd = msg.linear.x;
// Add left/right speeds so that turning on the spot is possible
leftSpd -= msg.angular.z;
rightSpd += msg.angular.z;
// Determine rotation directions
char leftDir = leftSpd > 0 ? 'b' : 'f';
char rightDir = rightSpd > 0 ? 'f' : 'b';
// Map [-1, 1] -> [0, 1] as we've extracted the directional component
leftSpd = leftSpd < 0 ? leftSpd * -1.0 : leftSpd;
rightSpd = rightSpd < 0 ? rightSpd * -1.0 : rightSpd;
leftSpd = min(1.0, max(0.0, leftSpd));
rightSpd = min(1.0, max(0.0, rightSpd));
// Apply!
tty << "dl" << leftDir << leftSpd * 256 << std::endl;
tty << "dr" << rightDir << rightSpd * 256 << std::endl;
// Wheel disc rotation
double leftRotSpd = msg.angular.y;
double rightRotSpd = msg.angular.y;
char leftRotDir = leftRotSpd > 0 ? 'b' : 'f';
char rightRotDir = rightRotSpd > 0 ? 'f' : 'b';
leftRotSpd = leftRotSpd < 0 ? leftRotSpd * -1.0 : leftRotSpd;
rightRotSpd = rightRotSpd < 0 ? rightRotSpd * -1.0 : rightRotSpd;
leftRotSpd = min(1.0, max(0.0, leftRotSpd));
rightRotSpd = min(1.0, max(0.0, rightRotSpd));
tty << "rl" << leftRotDir << leftRotSpd * 256 << std::endl;
tty << "rr" << rightRotDir << rightRotSpd * 256 << std::endl;
}
void publishOdometry(const ros::TimerEvent&) {
// Source: http://wiki.ros.org/navigation/Tutorials/RobotSetup/Odom
// Compute input values
double dt = (currentTime - lastTime).toSec();
double dx = (vx * cos(theta) - vy * sin(theta)) * dt;
double dy = (vx * sin(theta) - vy * cos(theta)) * dt;
double dtheta = vtheta * dt;
x += dx;
y += dy;
theta += dtheta;
// Transform frame
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odomQuat = tf::createQuaternionMsgFromYaw(theta);
geometry_msgs::TransformStamped odomTrans;
odomTrans.header.stamp = currentTime;
odomTrans.header.frame_id = "odom";
odomTrans.child_frame_id = "base_link";
odomTrans.transform.translation.x = x;
odomTrans.transform.translation.y = y;
odomTrans.transform.translation.z = 0.0;
odomTrans.transform.rotation = odomQuat;
odomBroadcaster->sendTransform(odomTrans);
// Odometry message
nav_msgs::Odometry odom;
odom.header.stamp = currentTime;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odomQuat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = vtheta;
odomPub.publish(odom);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "enginecontrol");
ros::NodeHandle n;
currentTime = ros::Time::now();
lastTime = ros::Time::now();
tty.open("/dev/ttyACM0", std::fstream::in | std::fstream::out | std::fstream::app);
if(!tty.is_open()) {
ROS_INFO("Couldn't open /dev/ttyACM0. Is the Arduino plugged in?");
}
tty << std::hex;
// This is correct - we're borrowing the turtle's topics
ros::Subscriber sub = n.subscribe("turtle1/cmd_vel", 1, velocityCallback);
odomPub = n.advertise<nav_msgs::Odometry>("odom", 50);
odomBroadcaster = boost::make_shared<tf::TransformBroadcaster>();
ros::Timer odoTimer = n.createTimer(ros::Duration(1.0/2.0/*2 Hz*/), publishOdometry);
ROS_INFO("enginecontrol up and running.");
ros::spin();
tty.close();
return 0;
}
<commit_msg>Abstract the protocol a little better and prevent random pin values on startup<commit_after>#include <string>
#include <math.h>
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <boost/shared_ptr.hpp>
#include <fstream>
using namespace std;
// A serial interface used to send commands to the Arduino that controls
// the motor controllers. (Yeah, recursion!)
std::fstream tty;
// for odometry
ros::Time currentTime;
ros::Time lastTime;
ros::Publisher odomPub;
boost::shared_ptr<tf::TransformBroadcaster> odomBroadcaster;
double x = 0;
double y = 0;
double theta = 0;
double vx = 0;
double vy = 0;
double vtheta = 0;
const char MOTOR_LEFT = 'l';
const char MOTOR_RIGHT = 'r';
const char MOTOR_FORWARD = 'f';
const char MOTOR_BACKWARD = 'b';
const char MOTOR_STOP = 's';
void setDrive(const char motor, const char direction, const float spd = 0f)
{
tty << 'd' << motor << direction;
if(direction != MOTOR_STOP) {
tty << spd * 256;
}
tty << std::endl;
}
void setRotation(const char motor, const char direction, const float spd = 0f)
{
tty << 'r' << motor << direction;
if(direction != MOTOR_STOP) {
tty << spd * 256;
}
tty << std::endl;
}
void velocityCallback(const geometry_msgs::Twist& msg) {
//ROS_INFO("%f", msg.linear.x);
// Store odometry input values
lastTime = currentTime;
currentTime = ros::Time::now();
vx = msg.linear.x;
vy = msg.linear.y;
vtheta = msg.angular.z * 10; // absolutely uneducated guess
// Tank-like steering (rotate around vehicle center)
// Set linear back/forward speed
double leftSpd = msg.linear.x;
double rightSpd = msg.linear.x;
// Add left/right speeds so that turning on the spot is possible
leftSpd -= msg.angular.z;
rightSpd += msg.angular.z;
// Determine rotation directions
char leftDir = leftSpd > 0 ? MOTOR_BACKWARD : MOTOR_FORWARD;
char rightDir = rightSpd > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
// Map [-1, 1] -> [0, 1] as we've extracted the directional component
leftSpd = leftSpd < 0 ? leftSpd * -1.0 : leftSpd;
rightSpd = rightSpd < 0 ? rightSpd * -1.0 : rightSpd;
leftSpd = min(1.0, max(0.0, leftSpd));
rightSpd = min(1.0, max(0.0, rightSpd));
// Apply!
setDrive(MOTOR_LEFT, leftDir, leftSpd);
setDrive(MOTOR_RIGHT, rightDir, rightSpd);
// Wheel disc rotation
double leftRotSpd = msg.angular.y;
double rightRotSpd = msg.angular.y;
char leftRotDir = leftRotSpd > 0 ? MOTOR_BACKWARD : MOTOR_FORWARD;
char rightRotDir = rightRotSpd > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
leftRotSpd = leftRotSpd < 0 ? leftRotSpd * -1.0 : leftRotSpd;
rightRotSpd = rightRotSpd < 0 ? rightRotSpd * -1.0 : rightRotSpd;
leftRotSpd = min(1.0, max(0.0, leftRotSpd));
rightRotSpd = min(1.0, max(0.0, rightRotSpd));
setRotation(MOTOR_LEFT, leftRotDir, leftRotSpd);
setRotation(MOTOR_RIGHT, rightRotDir, rightRotSpd);
}
void publishOdometry(const ros::TimerEvent&) {
// Source: http://wiki.ros.org/navigation/Tutorials/RobotSetup/Odom
// Compute input values
double dt = (currentTime - lastTime).toSec();
double dx = (vx * cos(theta) - vy * sin(theta)) * dt;
double dy = (vx * sin(theta) - vy * cos(theta)) * dt;
double dtheta = vtheta * dt;
x += dx;
y += dy;
theta += dtheta;
// Transform frame
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odomQuat = tf::createQuaternionMsgFromYaw(theta);
geometry_msgs::TransformStamped odomTrans;
odomTrans.header.stamp = currentTime;
odomTrans.header.frame_id = "odom";
odomTrans.child_frame_id = "base_link";
odomTrans.transform.translation.x = x;
odomTrans.transform.translation.y = y;
odomTrans.transform.translation.z = 0.0;
odomTrans.transform.rotation = odomQuat;
odomBroadcaster->sendTransform(odomTrans);
// Odometry message
nav_msgs::Odometry odom;
odom.header.stamp = currentTime;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odomQuat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = vtheta;
odomPub.publish(odom);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "enginecontrol");
ros::NodeHandle n;
currentTime = ros::Time::now();
lastTime = ros::Time::now();
tty.open("/dev/ttyACM0", std::fstream::in | std::fstream::out | std::fstream::app);
if(!tty.is_open()) {
ROS_INFO("Couldn't open /dev/ttyACM0. Is the Arduino plugged in?");
return 1;
}
tty << std::hex;
// Just to make sure we're not going anywhere...
setDrive(MOTOR_LEFT, MOTOR_STOP);
setDrive(MOTOR_RIGHT, MOTOR_STOP);
setRotation(MOTOR_LEFT, MOTOR_STOP);
setRotation(MOTOR_RIGHT, MOTOR_STOP);
// This is correct - we're borrowing the turtle's topics
ros::Subscriber sub = n.subscribe("turtle1/cmd_vel", 1, velocityCallback);
odomPub = n.advertise<nav_msgs::Odometry>("odom", 50);
odomBroadcaster = boost::make_shared<tf::TransformBroadcaster>();
ros::Timer odoTimer = n.createTimer(ros::Duration(1.0/2.0/*2 Hz*/), publishOdometry);
ROS_INFO("enginecontrol up and running.");
ros::spin();
tty.close();
return 0;
}
<|endoftext|> |
<commit_before>#include "constants.hpp"
#include <string>
#include <math.h>
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <boost/shared_ptr.hpp>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <sstream>
#include <limits>
using namespace std;
// A serial interface used to send commands to the Arduino that controls
// the motor controllers. (Yeah, recursion!)
// (C file descriptor)
int tty;
std::stringstream ss;
// for odometry
ros::Time currentTime;
ros::Time lastTime;
ros::Publisher odomPub;
boost::shared_ptr<tf::TransformBroadcaster> odomBroadcaster;
double x = 0;
double y = 0;
double theta = 0;
double vx = 0;
double vy = 0;
double vtheta = 0;
// Make current speeds always available (and query them only once per cycle)
double vLeftCur = 0.0;
double vRightCur = 0.0;
// Used to form the Arduino commands
const char MOTOR_LEFT = 'l';
const char MOTOR_RIGHT = 'r';
const char MOTOR_FORWARD = 'f';
const char MOTOR_BACKWARD = 'b';
const char MOTOR_STOP = 's';
// The motors are stopped (not just set to speed 0.0) below this input speed.
const float STOP_THRESHOLD = 0.01f;
bool initTty()
{
// http://timmurphy.org/2009/08/04/baud-rate-and-other-serial-comm-settings-in-c/
tty = open("/dev/ttyACM0", O_RDWR | O_NOCTTY/* | O_NDELAY*/);
if(tty < 0) {
perror("open(\"/dev/ttyACM0\")");
return false;
}
struct termios settings;
tcgetattr(tty, &settings);
cfsetospeed(&settings, B115200);
cfsetispeed(&settings, B0 /*same as output*/);
settings.c_cflag &= ~PARENB; // no parity
settings.c_cflag &= ~CSTOPB; // one stop bit
settings.c_cflag &= ~CSIZE; // 8 bits per character
settings.c_cflag |= CS8;
settings.c_cflag &= ~CRTSCTS; // Disable hardware flow control
// settings.c_cflag &= ~HUPCL; // Send modem disconnect when closing the fd
settings.c_cflag |= CREAD; // Enable receiver
// settings.c_cflag |= CLOCAL; // Ignore modem status lines
settings.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable start/stop I/O control
settings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Disable user terminal features
settings.c_oflag &= ~OPOST; // Disable output postprocessing
settings.c_cc[VMIN] = 0;
settings.c_cc[VTIME] = 0;
if(tcsetattr(tty, TCSANOW, &settings) != 0) {
perror("tcsetattr");
return false;
}
tcflush(tty, TCOFLUSH);
return true;
}
int readLine(char* const line, const ssize_t LINE_LENGTH)
{
ssize_t bytesRead = 0;
bool lineComplete = false;
while(!lineComplete && bytesRead < LINE_LENGTH) {
// Read bytes into temporary buffer
char buffer[LINE_LENGTH];
// ROS_INFO("a");
ssize_t newBytesRead = read(tty, buffer, LINE_LENGTH);
// ROS_INFO("b");
if(newBytesRead < 0) {
perror("read");
}
// Copy new bytes to 'line'
for(ssize_t i = 0; i < newBytesRead && bytesRead < LINE_LENGTH; i++, bytesRead++) {
line[bytesRead] = buffer[i];
if(buffer[i] == '\n') {
lineComplete = true;
}
}
}
return bytesRead;
}
void setDrive(const char motor, const char direction, const float spd = 0.0f)
{
ss.str("");
ss << "sd" << motor << direction;
if(direction != MOTOR_STOP) {
ss << std::hex << (int8_t)(spd * 255);
}
ss << std::endl;
const char* output = ss.str().c_str();
write(tty, output, ss.str().length());
// ROS_INFO("%s", output);
// check response
char line[2];
const int lineLength = readLine(line, 2);
if(atoi(line) != 0) {
ROS_INFO("Command failed: %s", output);
}
}
void setRotation(const char motor, const char direction, const float spd = 0.0f)
{
ss.str("");
ss << "sr" << motor << direction;
if(direction != MOTOR_STOP) {
ss << std::hex << (int8_t)(spd * 255);
}
ss << std::endl;
const char* output = ss.str().c_str();
// write(tty, output, ss.str().length());
// check response
// char line[2];
// const int lineLength = readLine(line, 2);
// if(atoi(line) != 0) {
// ROS_INFO("Command failed: %s", output);
// }
}
/*
* Returns the speed in m/s the given motor is moving the robot at.
*/
float getSpeed(const char motor)
{
// Write command
ss.str("");
// "get drive left/right rate"
ss << "gd" << motor << 'r' << std::endl;
const char* output = ss.str().c_str();
write(tty, output, ss.str().length());
// ROS_INFO("%s", ss.str().c_str());
// Read response
// Expected: max. 11 characters (-2,147,483,647) + \n
const int LINE_LENGTH = 11;
char line[LINE_LENGTH] = {0};
const int lineLength = readLine(line, LINE_LENGTH);
// We receive the interval in µs bewtween two motor monitor ticks
const int interval = atoi(line);
// Compute motor revolution freq (Hz) from motor tick interval (µs)
// Filter out division by zero and "stop" state
const double freq = (interval == 0 || interval == 1000000) ? 0 : 1000000 / interval;
// if(motor == MOTOR_RIGHT)
// ROS_INFO("interval %c: %i freq: %f", motor, interval, freq);
// Return the resulting robot speed for this motor (m/s)
return freq * WHEEL_DIAMETER * M_PI / (3.0 * WHEEL_REDUCTION);
}
void velocityCallback(const geometry_msgs::Twist& msg) {
// Store current motor speeds for later reference
vLeftCur = getSpeed(MOTOR_LEFT);
vRightCur = getSpeed(MOTOR_RIGHT);
// Compute the motor speeds necessary to achieve the desired linear and angular motion
// Adapted from:
// https://code.google.com/p/differential-drive/source/browse/nodes/twist_to_motors.py
// self.right = 1.0 * self.dx + self.dr * self.w / 2
// self.left = 1.0 * self.dx - self.dr * self.w / 2
double vLeft = msg.linear.x// / MAX_DRV_SPEED
- msg.angular.z * WHEEL_DISTANCE / (2.0);// * MAX_DRV_SPEED);
double vRight = msg.linear.x// / MAX_DRV_SPEED
+ msg.angular.z * WHEEL_DISTANCE / (2.0);// * MAX_DRV_SPEED);
// ROS_INFO("tl: %f tr: %f z: %f", vLeft, vRight, msg.angular.z);
// Determine rotation directions
char dLeft = vLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
char dRight = vRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
// Map [-MAX_DRV_SPEED, MAX_DRV_SPEED] -> [0, 1] as we've extracted the directional component
vLeft = vLeft < 0 ? vLeft * -1.0 : vLeft;
vRight = vRight < 0 ? vRight * -1.0 : vRight;
vLeft = min(1.0, vLeft / MAX_DRV_SPEED);
vRight = min(1.0, vRight / MAX_DRV_SPEED);
// Stop the motors when stopping
if(vLeft < STOP_THRESHOLD) {
dLeft = MOTOR_STOP;
}
if(vRight < STOP_THRESHOLD) {
dRight = MOTOR_STOP;
}
// Apply!
setDrive(MOTOR_LEFT, dLeft, vLeft);
setDrive(MOTOR_RIGHT, dRight, vRight);
// Wheel disc rotation
double vRotLeft = msg.angular.y;
double vRotRight = msg.angular.y;
char dRotLeft = vRotLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
char dRotRight = vRotRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
vRotLeft = vRotLeft < 0 ? vRotLeft * -1.0 : vRotLeft;
vRotRight = vRotRight < 0 ? vRotRight * -1.0 : vRotRight;
vRotLeft = min(1.0, max(0.0, vRotLeft / MAX_ROT_SPEED));
vRotRight = min(1.0, max(0.0, vRotRight / MAX_ROT_SPEED));
if(vRotLeft < STOP_THRESHOLD) {
dRotLeft = MOTOR_STOP;
}
if(vRotRight < STOP_THRESHOLD) {
dRotRight = MOTOR_STOP;
}
setRotation(MOTOR_LEFT, dRotLeft, vRotLeft);
setRotation(MOTOR_RIGHT, dRotRight, vRotRight);
}
void publishOdometry(const ros::TimerEvent&) {
// // Source: http://wiki.ros.org/navigation/Tutorials/RobotSetup/Odom
// // Store odometry input values
vx = (vLeftCur + vRightCur) / 2.0;
// vtheta = (vRight - vLeft) / WHEEL_OFFSET;
// Compute input values
double dt = (currentTime - lastTime).toSec();
lastTime = currentTime;
currentTime = ros::Time::now();
double dx = (vx * cos(theta) - vy * sin(theta)) * dt;
double dy = (vx * sin(theta) - vy * cos(theta)) * dt;
vtheta = (dx - dy) / WHEEL_DISTANCE;
double dtheta = vtheta * dt;
x += dx;
y += dy;
theta += dtheta;
// ROS_INFO("vl: %f vr: %f vx: %f vtheta: %f", vLeftCur, vRightCur, vx, vtheta);
// Transform frame
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odomQuat = tf::createQuaternionMsgFromYaw(theta);
geometry_msgs::TransformStamped odomTrans;
odomTrans.header.stamp = currentTime;
odomTrans.header.frame_id = "odom";
odomTrans.child_frame_id = "base_link";
odomTrans.transform.translation.x = x;
odomTrans.transform.translation.y = y;
odomTrans.transform.translation.z = 0.0;
odomTrans.transform.rotation = odomQuat;
odomBroadcaster->sendTransform(odomTrans);
// Odometry message
nav_msgs::Odometry odom;
odom.header.stamp = currentTime;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odomQuat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = vtheta;
odomPub.publish(odom);
// Test TF
// This circumvents problems that might be introduced because static_transform_publisher
// seems to offset its transforms into the future.
// <node pkg="tf" type="static_transform_publisher" name="base_link_to_laser" args="0.1 0.1 0.15 0.0 0.0 0.0 /base_link /laser 50" />
geometry_msgs::Quaternion laserQuat = tf::createQuaternionMsgFromYaw(0.0);
geometry_msgs::TransformStamped laserTrans;
laserTrans.header.stamp = ros::Time::now();
laserTrans.header.frame_id = "base_link";
laserTrans.child_frame_id = "laser";
laserTrans.transform.translation.x = 0.1;
laserTrans.transform.translation.y = 0.1;
laserTrans.transform.translation.z = 0.15;
laserTrans.transform.rotation = laserQuat;
odomBroadcaster->sendTransform(laserTrans);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "enginecontrol");
ros::NodeHandle n;
currentTime = ros::Time::now();
lastTime = ros::Time::now();
if(!initTty()) {
return 1;
}
// Just to make sure we're not going anywhere...
setDrive(MOTOR_LEFT, MOTOR_STOP);
setDrive(MOTOR_RIGHT, MOTOR_STOP);
setRotation(MOTOR_LEFT, MOTOR_STOP);
setRotation(MOTOR_RIGHT, MOTOR_STOP);
// This is correct - we're borrowing the turtle's topics
ros::Subscriber sub = n.subscribe("cmd_vel", 1, velocityCallback);
odomPub = n.advertise<nav_msgs::Odometry>("odom", 50);
odomBroadcaster = boost::make_shared<tf::TransformBroadcaster>();
ros::Timer odoTimer = n.createTimer(ros::Duration(1.0/10.0/*10 Hz*/), publishOdometry);
ROS_INFO("enginecontrol up and running.");
ros::spin();
close(tty);
return 0;
}
<commit_msg>Enable arduino commands for rotation motors<commit_after>#include "constants.hpp"
#include <string>
#include <math.h>
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <boost/shared_ptr.hpp>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <sstream>
#include <limits>
using namespace std;
// A serial interface used to send commands to the Arduino that controls
// the motor controllers. (Yeah, recursion!)
// (C file descriptor)
int tty;
std::stringstream ss;
// for odometry
ros::Time currentTime;
ros::Time lastTime;
ros::Publisher odomPub;
boost::shared_ptr<tf::TransformBroadcaster> odomBroadcaster;
double x = 0;
double y = 0;
double theta = 0;
double vx = 0;
double vy = 0;
double vtheta = 0;
// Make current speeds always available (and query them only once per cycle)
double vLeftCur = 0.0;
double vRightCur = 0.0;
// Used to form the Arduino commands
const char MOTOR_LEFT = 'l';
const char MOTOR_RIGHT = 'r';
const char MOTOR_FORWARD = 'f';
const char MOTOR_BACKWARD = 'b';
const char MOTOR_STOP = 's';
// The motors are stopped (not just set to speed 0.0) below this input speed.
const float STOP_THRESHOLD = 0.01f;
bool initTty()
{
// http://timmurphy.org/2009/08/04/baud-rate-and-other-serial-comm-settings-in-c/
tty = open("/dev/ttyACM0", O_RDWR | O_NOCTTY/* | O_NDELAY*/);
if(tty < 0) {
perror("open(\"/dev/ttyACM0\")");
return false;
}
struct termios settings;
tcgetattr(tty, &settings);
cfsetospeed(&settings, B115200);
cfsetispeed(&settings, B0 /*same as output*/);
settings.c_cflag &= ~PARENB; // no parity
settings.c_cflag &= ~CSTOPB; // one stop bit
settings.c_cflag &= ~CSIZE; // 8 bits per character
settings.c_cflag |= CS8;
settings.c_cflag &= ~CRTSCTS; // Disable hardware flow control
// settings.c_cflag &= ~HUPCL; // Send modem disconnect when closing the fd
settings.c_cflag |= CREAD; // Enable receiver
// settings.c_cflag |= CLOCAL; // Ignore modem status lines
settings.c_iflag &= ~(IXON | IXOFF | IXANY); // Disable start/stop I/O control
settings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Disable user terminal features
settings.c_oflag &= ~OPOST; // Disable output postprocessing
settings.c_cc[VMIN] = 0;
settings.c_cc[VTIME] = 0;
if(tcsetattr(tty, TCSANOW, &settings) != 0) {
perror("tcsetattr");
return false;
}
tcflush(tty, TCOFLUSH);
return true;
}
int readLine(char* const line, const ssize_t LINE_LENGTH)
{
ssize_t bytesRead = 0;
bool lineComplete = false;
while(!lineComplete && bytesRead < LINE_LENGTH) {
// Read bytes into temporary buffer
char buffer[LINE_LENGTH];
// ROS_INFO("a");
ssize_t newBytesRead = read(tty, buffer, LINE_LENGTH);
// ROS_INFO("b");
if(newBytesRead < 0) {
perror("read");
}
// Copy new bytes to 'line'
for(ssize_t i = 0; i < newBytesRead && bytesRead < LINE_LENGTH; i++, bytesRead++) {
line[bytesRead] = buffer[i];
if(buffer[i] == '\n') {
lineComplete = true;
}
}
}
return bytesRead;
}
void setDrive(const char motor, const char direction, const float spd = 0.0f)
{
ss.str("");
ss << "sd" << motor << direction;
if(direction != MOTOR_STOP) {
ss << std::hex << (int8_t)(spd * 255);
}
ss << std::endl;
const char* output = ss.str().c_str();
write(tty, output, ss.str().length());
// ROS_INFO("%s", output);
// check response
char line[2];
const int lineLength = readLine(line, 2);
if(atoi(line) != 0) {
ROS_INFO("Command failed: %s", output);
}
}
void setRotation(const char motor, const char direction, const float spd = 0.0f)
{
ss.str("");
ss << "sr" << motor << direction;
if(direction != MOTOR_STOP) {
ss << std::hex << (int8_t)(spd * 255);
}
ss << std::endl;
const char* output = ss.str().c_str();
write(tty, output, ss.str().length());
// check response
char line[2];
const int lineLength = readLine(line, 2);
if(atoi(line) != 0) {
ROS_INFO("Command failed: %s", output);
}
}
/*
* Returns the speed in m/s the given motor is moving the robot at.
*/
float getSpeed(const char motor)
{
// Write command
ss.str("");
// "get drive left/right rate"
ss << "gd" << motor << 'r' << std::endl;
const char* output = ss.str().c_str();
write(tty, output, ss.str().length());
// ROS_INFO("%s", ss.str().c_str());
// Read response
// Expected: max. 11 characters (-2,147,483,647) + \n
const int LINE_LENGTH = 11;
char line[LINE_LENGTH] = {0};
const int lineLength = readLine(line, LINE_LENGTH);
// We receive the interval in µs bewtween two motor monitor ticks
const int interval = atoi(line);
// Compute motor revolution freq (Hz) from motor tick interval (µs)
// Filter out division by zero and "stop" state
const double freq = (interval == 0 || interval == 1000000) ? 0 : 1000000 / interval;
// if(motor == MOTOR_RIGHT)
// ROS_INFO("interval %c: %i freq: %f", motor, interval, freq);
// Return the resulting robot speed for this motor (m/s)
return freq * WHEEL_DIAMETER * M_PI / (3.0 * WHEEL_REDUCTION);
}
void velocityCallback(const geometry_msgs::Twist& msg) {
// Store current motor speeds for later reference
vLeftCur = getSpeed(MOTOR_LEFT);
vRightCur = getSpeed(MOTOR_RIGHT);
// Compute the motor speeds necessary to achieve the desired linear and angular motion
// Adapted from:
// https://code.google.com/p/differential-drive/source/browse/nodes/twist_to_motors.py
// self.right = 1.0 * self.dx + self.dr * self.w / 2
// self.left = 1.0 * self.dx - self.dr * self.w / 2
double vLeft = msg.linear.x// / MAX_DRV_SPEED
- msg.angular.z * WHEEL_DISTANCE / (2.0);// * MAX_DRV_SPEED);
double vRight = msg.linear.x// / MAX_DRV_SPEED
+ msg.angular.z * WHEEL_DISTANCE / (2.0);// * MAX_DRV_SPEED);
// ROS_INFO("tl: %f tr: %f z: %f", vLeft, vRight, msg.angular.z);
// Determine rotation directions
char dLeft = vLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
char dRight = vRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
// Map [-MAX_DRV_SPEED, MAX_DRV_SPEED] -> [0, 1] as we've extracted the directional component
vLeft = vLeft < 0 ? vLeft * -1.0 : vLeft;
vRight = vRight < 0 ? vRight * -1.0 : vRight;
vLeft = min(1.0, vLeft / MAX_DRV_SPEED);
vRight = min(1.0, vRight / MAX_DRV_SPEED);
// Stop the motors when stopping
if(vLeft < STOP_THRESHOLD) {
dLeft = MOTOR_STOP;
}
if(vRight < STOP_THRESHOLD) {
dRight = MOTOR_STOP;
}
// Apply!
setDrive(MOTOR_LEFT, dLeft, vLeft);
setDrive(MOTOR_RIGHT, dRight, vRight);
// Wheel disc rotation
double vRotLeft = msg.angular.y;
double vRotRight = msg.angular.y;
char dRotLeft = vRotLeft > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
char dRotRight = vRotRight > 0 ? MOTOR_FORWARD : MOTOR_BACKWARD;
vRotLeft = vRotLeft < 0 ? vRotLeft * -1.0 : vRotLeft;
vRotRight = vRotRight < 0 ? vRotRight * -1.0 : vRotRight;
vRotLeft = min(1.0, max(0.0, vRotLeft / MAX_ROT_SPEED));
vRotRight = min(1.0, max(0.0, vRotRight / MAX_ROT_SPEED));
if(vRotLeft < STOP_THRESHOLD) {
dRotLeft = MOTOR_STOP;
}
if(vRotRight < STOP_THRESHOLD) {
dRotRight = MOTOR_STOP;
}
setRotation(MOTOR_LEFT, dRotLeft, vRotLeft);
setRotation(MOTOR_RIGHT, dRotRight, vRotRight);
}
void publishOdometry(const ros::TimerEvent&) {
// // Source: http://wiki.ros.org/navigation/Tutorials/RobotSetup/Odom
// // Store odometry input values
vx = (vLeftCur + vRightCur) / 2.0;
// vtheta = (vRight - vLeft) / WHEEL_OFFSET;
// Compute input values
double dt = (currentTime - lastTime).toSec();
lastTime = currentTime;
currentTime = ros::Time::now();
double dx = (vx * cos(theta) - vy * sin(theta)) * dt;
double dy = (vx * sin(theta) - vy * cos(theta)) * dt;
vtheta = (dx - dy) / WHEEL_DISTANCE;
double dtheta = vtheta * dt;
x += dx;
y += dy;
theta += dtheta;
// ROS_INFO("vl: %f vr: %f vx: %f vtheta: %f", vLeftCur, vRightCur, vx, vtheta);
// Transform frame
//since all odometry is 6DOF we'll need a quaternion created from yaw
geometry_msgs::Quaternion odomQuat = tf::createQuaternionMsgFromYaw(theta);
geometry_msgs::TransformStamped odomTrans;
odomTrans.header.stamp = currentTime;
odomTrans.header.frame_id = "odom";
odomTrans.child_frame_id = "base_link";
odomTrans.transform.translation.x = x;
odomTrans.transform.translation.y = y;
odomTrans.transform.translation.z = 0.0;
odomTrans.transform.rotation = odomQuat;
odomBroadcaster->sendTransform(odomTrans);
// Odometry message
nav_msgs::Odometry odom;
odom.header.stamp = currentTime;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = x;
odom.pose.pose.position.y = y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odomQuat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vx;
odom.twist.twist.linear.y = vy;
odom.twist.twist.angular.z = vtheta;
odomPub.publish(odom);
// Test TF
// This circumvents problems that might be introduced because static_transform_publisher
// seems to offset its transforms into the future.
// <node pkg="tf" type="static_transform_publisher" name="base_link_to_laser" args="0.1 0.1 0.15 0.0 0.0 0.0 /base_link /laser 50" />
geometry_msgs::Quaternion laserQuat = tf::createQuaternionMsgFromYaw(0.0);
geometry_msgs::TransformStamped laserTrans;
laserTrans.header.stamp = ros::Time::now();
laserTrans.header.frame_id = "base_link";
laserTrans.child_frame_id = "laser";
laserTrans.transform.translation.x = 0.1;
laserTrans.transform.translation.y = 0.1;
laserTrans.transform.translation.z = 0.15;
laserTrans.transform.rotation = laserQuat;
odomBroadcaster->sendTransform(laserTrans);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "enginecontrol");
ros::NodeHandle n;
currentTime = ros::Time::now();
lastTime = ros::Time::now();
if(!initTty()) {
return 1;
}
// Just to make sure we're not going anywhere...
setDrive(MOTOR_LEFT, MOTOR_STOP);
setDrive(MOTOR_RIGHT, MOTOR_STOP);
setRotation(MOTOR_LEFT, MOTOR_STOP);
setRotation(MOTOR_RIGHT, MOTOR_STOP);
// This is correct - we're borrowing the turtle's topics
ros::Subscriber sub = n.subscribe("cmd_vel", 1, velocityCallback);
odomPub = n.advertise<nav_msgs::Odometry>("odom", 50);
odomBroadcaster = boost::make_shared<tf::TransformBroadcaster>();
ros::Timer odoTimer = n.createTimer(ros::Duration(1.0/10.0/*10 Hz*/), publishOdometry);
ROS_INFO("enginecontrol up and running.");
ros::spin();
close(tty);
return 0;
}
<|endoftext|> |
<commit_before>#include "joystick.hpp"
#include "constants.hpp"
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <vector>
#include <string>
#include <math.h>
const int DEAD_ZONE = 16384;
const int AXIS_MAX = 32767;
using namespace ros;
using namespace std;
Joystick joystick;
Publisher pub;
void updateRemote(const TimerEvent&) {
// get axis values
// use axis.0 for left/right
// and axis.1 for up/down
JoystickEvent event = joystick.getEvent();
vector<short> axis = event.getAxis();
vector<bool> buttons = event.getButtons();
// calculate position values
double angular = (-1.0) * axis.at(0) / AXIS_MAX;
double linear = (-1.0) * axis.at(1) / AXIS_MAX;
double stick2y = (-1.0) * axis.at(2) / AXIS_MAX;
angular = min(max(angular, -1.0), 1.0);
linear = min(max(linear, -1.0), 1.0);
stick2y = min(max(stick2y, -1.0), 1.0);
// Normalize driving vector
// This would require a little more computation in enginecontrol, left out
// for now.
// const double scale = sqrt(pow(angular, 2) + pow(linear, 2));
// angular *= scale;
// linear *= scale;
// SPEEED-BUTTON!
if (!buttons.at(0)) {
linear *= 0.25;
} else {
// Safety measures...
angular *= 0.75;
linear *= 0.75;
}
if (!buttons.at(1)) {
stick2y *= 0.2; // Scale wheel rotation nice and slow
} else {
stick2y *= 0.5;
}
// if (linear < 0) {
// angular *= (-1.0);
// }
// Twist is supposed to contain desired speeds in m/s
geometry_msgs::Twist twist;
twist.angular.z = angular * MAX_TURN_SPEED;
twist.angular.y = stick2y * MAX_ROT_SPEED;
twist.linear.x = linear * MAX_DRV_SPEED;
pub.publish(twist);
}
int main(int argc, char **argv) {
// init sdl and connect to controller
SDL_Init(SDL_INIT_JOYSTICK);
if(!joystick.init()) {
cout << "Could not find a joystick!\n";
return 1;
}
string name = joystick.getName();
cout << "Used controller: " << name.c_str() << endl;
// init ros
init(argc, argv, "remotecontrol");
NodeHandle n;
pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
// startup main loop
Timer remoteTimer = n.createTimer(Duration(0.0166 /*60 Hz*/), updateRemote);
spin();
return 0;
}
<commit_msg>reduce remote send frequency<commit_after>#include "joystick.hpp"
#include "constants.hpp"
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <vector>
#include <string>
#include <math.h>
const int DEAD_ZONE = 16384;
const int AXIS_MAX = 32767;
using namespace ros;
using namespace std;
Joystick joystick;
Publisher pub;
void updateRemote(const TimerEvent&) {
// get axis values
// use axis.0 for left/right
// and axis.1 for up/down
JoystickEvent event = joystick.getEvent();
vector<short> axis = event.getAxis();
vector<bool> buttons = event.getButtons();
// calculate position values
double angular = (-1.0) * axis.at(0) / AXIS_MAX;
double linear = (-1.0) * axis.at(1) / AXIS_MAX;
double stick2y = (-1.0) * axis.at(2) / AXIS_MAX;
angular = min(max(angular, -1.0), 1.0);
linear = min(max(linear, -1.0), 1.0);
stick2y = min(max(stick2y, -1.0), 1.0);
// Normalize driving vector
// This would require a little more computation in enginecontrol, left out
// for now.
// const double scale = sqrt(pow(angular, 2) + pow(linear, 2));
// angular *= scale;
// linear *= scale;
// SPEEED-BUTTON!
if (!buttons.at(0)) {
linear *= 0.25;
} else {
// Safety measures...
angular *= 0.75;
linear *= 0.75;
}
if (!buttons.at(1)) {
stick2y *= 0.2; // Scale wheel rotation nice and slow
} else {
stick2y *= 0.5;
}
// if (linear < 0) {
// angular *= (-1.0);
// }
// Twist is supposed to contain desired speeds in m/s
geometry_msgs::Twist twist;
twist.angular.z = angular * MAX_TURN_SPEED;
twist.angular.y = stick2y * MAX_ROT_SPEED;
twist.linear.x = linear * MAX_DRV_SPEED;
pub.publish(twist);
}
int main(int argc, char **argv) {
// init sdl and connect to controller
SDL_Init(SDL_INIT_JOYSTICK);
if(!joystick.init()) {
cout << "Could not find a joystick!\n";
return 1;
}
string name = joystick.getName();
cout << "Used controller: " << name.c_str() << endl;
// init ros
init(argc, argv, "remotecontrol");
NodeHandle n;
pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
// startup main loop
Timer remoteTimer = n.createTimer(Duration(1.0/30.0 /*Hz*/), updateRemote);
spin();
return 0;
}
<|endoftext|> |
<commit_before>#include <MainApplication/Gui/MainWindow.hpp>
#include <QFileDialog>
#include <QToolButton>
#include <Engine/RadiumEngine.hpp>
#include <Engine/Entity/Component.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/Renderer/Renderer.hpp>
#include <MainApplication/MainApplication.hpp>
#include <MainApplication/Gui/EntityTreeModel.hpp>
#include <MainApplication/Gui/EntityTreeItem.hpp>
#include <MainApplication/Viewer/CameraInterface.hpp>
#include <Plugins/Animation/AnimationSystem.hpp>
namespace Ra
{
Gui::MainWindow::MainWindow( QWidget* parent )
: QMainWindow( parent )
{
// Note : at this point most of the components (including the Engine) are
// not initialized. Listen to the "started" signal.
setupUi( this );
setWindowIcon( QPixmap( "../Assets/Images/RadiumIcon.png" ) );
setWindowTitle( QString( "Radium Engine" ) );
QStringList headers;
headers << tr( "Entities -> Components" );
m_entityTreeModel = new EntityTreeModel( headers );
m_entitiesTreeView->setModel( m_entityTreeModel );
createConnections();
mainApp->framesCountForStatsChanged(
m_avgFramesCount->value() );
m_viewer->getCameraInterface()->resetCamera();
}
Gui::MainWindow::~MainWindow()
{
// Child QObjects will automatically be deleted
}
void Gui::MainWindow::createConnections()
{
connect( actionOpenMesh, &QAction::triggered, this, &MainWindow::loadFile );
connect( actionReload_Shaders, &QAction::triggered, m_viewer, &Viewer::reloadShaders );
// Toolbox setup
connect( actionToggle_Local_Global, &QAction::toggled, m_viewer->getGizmoManager(), &GizmoManager::setLocal );
connect( actionGizmoOff, &QAction::triggered, this, &MainWindow::gizmoShowNone );
connect( actionGizmoTranslate, &QAction::triggered, this, &MainWindow::gizmoShowTranslate );
connect( actionGizmoRotate, &QAction::triggered, this, &MainWindow::gizmoShowRotate );
//connect( actionGizmoOff, &QAction::toggled, this, &gizmoShowNone);
// Loading setup.
connect( this, &MainWindow::fileLoading, mainApp, &MainApplication::loadFile );
connect( this, &MainWindow::entitiesUpdated, m_entityTreeModel, &EntityTreeModel::entitiesUpdated );
/* connect( m_entityTreeModel, SIGNAL( objectNameChanged( QString ) ),
this, SLOT( objectNameChanged( QString ) ) );*/
// Side menu setup.
connect( m_entityTreeModel, &EntityTreeModel::dataChanged, m_entityTreeModel, &EntityTreeModel::handleRename );
connect( m_entitiesTreeView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &MainWindow::onSelectionChanged );
// Camera panel setup
connect( m_cameraResetButton, &QPushButton::released, m_viewer->getCameraInterface(), &CameraInterface::resetCamera);
connect( m_setCameraPositionButton, &QPushButton::released, this, &MainWindow::setCameraPosition);
connect( m_setCameraTargetButton, &QPushButton::released, this, &MainWindow::setCameraTarget);
connect( this, &MainWindow::cameraPositionSet, m_viewer->getCameraInterface(), &CameraInterface::setCameraPosition );
connect( this, &MainWindow::cameraTargetSet, m_viewer->getCameraInterface(), &CameraInterface::setCameraTarget );
connect( m_viewer->getCameraInterface(), &CameraInterface::cameraPositionChanged, this, &MainWindow::onCameraPositionChanged );
connect( m_viewer->getCameraInterface(), &CameraInterface::cameraTargetChanged, this, &MainWindow::onCameraTargetChanged );
// Oh C++ why are you so mean to me ?
connect( m_cameraSensitivity, static_cast<void (QDoubleSpinBox::*) (double)>(&QDoubleSpinBox::valueChanged),
m_viewer->getCameraInterface(), &CameraInterface::setCameraSensitivity );
// Connect picking results (TODO Val : use events to dispatch picking directly)
connect( m_viewer, &Viewer::rightClickPicking, this, &MainWindow::handlePicking );
connect (m_viewer, &Viewer::leftClickPicking, m_viewer->getGizmoManager(), &GizmoManager::handlePickingResult );
// Update entities when the engine starts.
connect( mainApp, &MainApplication::starting, this, &MainWindow::onEntitiesUpdated );
connect( m_avgFramesCount, static_cast< void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
mainApp , &MainApplication::framesCountForStatsChanged );
connect(mainApp, &MainApplication::updateFrameStats, this, &MainWindow::onUpdateFramestats);
// Inform property editors of new selections
connect(this, &MainWindow::selectedEntity, tab_edition, &TransformEditorWidget::setEditable);
connect(this, &MainWindow::selectedEntity, m_viewer->getGizmoManager(), &GizmoManager::setEditable);
// Editors should be updated after each frame
connect(mainApp, &MainApplication::endFrame, tab_edition, &TransformEditorWidget::updateValues);
connect(mainApp, &MainApplication::endFrame, m_viewer->getGizmoManager(), &GizmoManager::updateValues);
connect(playButton, SIGNAL(clicked(bool)), this, SLOT(playAnimation()));
connect(pauseButton, SIGNAL(clicked(bool)), this, SLOT(pauseAnimation()));
}
void Gui::MainWindow::playAnimation()
{
AnimationPlugin::AnimationSystem* animSys = (AnimationPlugin::AnimationSystem*) mainApp->m_engine->getSystem("AnimationSystem");
animSys->setPlaying(true);
}
void Gui::MainWindow::pauseAnimation()
{
AnimationPlugin::AnimationSystem* animSys = (AnimationPlugin::AnimationSystem*) mainApp->m_engine->getSystem("AnimationSystem");
animSys->setPlaying(false);
}
void Gui::MainWindow::onEntitiesUpdated()
{
emit entitiesUpdated( mainApp->m_engine->getEntityManager()->getEntities() );
}
void Gui::MainWindow::onCameraPositionChanged( const Core::Vector3& p )
{
// TODO : use a vectorEditor.
m_cameraPositionX->setValue( p.x() );
m_cameraPositionY->setValue( p.y() );
m_cameraPositionZ->setValue( p.z() );
}
void Gui::MainWindow::onCameraTargetChanged( const Core::Vector3& p )
{
m_cameraTargetX->setValue( p.x() );
m_cameraTargetY->setValue( p.y() );
m_cameraTargetZ->setValue( p.z() );
}
void Gui::MainWindow::setCameraPosition()
{
Core::Vector3 P( m_cameraPositionX->value(),
m_cameraPositionY->value(),
m_cameraPositionZ->value() );
emit cameraPositionSet( P );
}
void Gui::MainWindow::setCameraTarget()
{
Core::Vector3 T( m_cameraTargetX->value(),
m_cameraTargetY->value(),
m_cameraTargetZ->value() );
emit cameraTargetSet( T );
}
void Gui::MainWindow::loadFile()
{
QString path = QFileDialog::getOpenFileName( this, QString(), ".." );
if ( path.size() > 0 )
{
emit fileLoading( path );
}
onEntitiesUpdated();
}
void Gui::MainWindow::onUpdateFramestats( const std::vector<FrameTimerData>& stats )
{
QString framesA2B = QString( "Frames #%1 to #%2 stats :" )
.arg( stats.front().numFrame ).arg( stats.back().numFrame );
m_frameA2BLabel->setText( framesA2B );
long sumRender = 0;
long sumTasks = 0;
long sumFrame = 0;
long sumInterFrame = 0;
for ( uint i = 0; i < stats.size(); ++i )
{
sumRender += Core::Timer::getIntervalMicro(
stats[i].renderData.renderStart, stats[i].renderData.renderEnd );
sumTasks += Core::Timer::getIntervalMicro(
stats[i].tasksStart, stats[i].tasksEnd );
sumFrame += Core::Timer::getIntervalMicro(
stats[i].frameStart, stats[i].frameEnd );
if ( i > 0 )
{
sumInterFrame += Core::Timer::getIntervalMicro(
stats[i - 1].frameEnd, stats[i].frameEnd );
}
}
const uint N = stats.size();
const Scalar T( N * 1000000.0 );
m_renderTime->setValue( sumRender / N );
m_renderUpdates->setValue( T / Scalar( sumRender ) );
m_tasksTime->setValue( sumTasks / N );
m_tasksUpdates->setValue( T / Scalar( sumTasks ) );
m_frameTime->setValue( sumFrame / N );
m_frameUpdates->setValue( T / Scalar( sumFrame ) );
m_avgFramerate->setValue( ( N - 1 ) * Scalar( 1000000.0 / sumInterFrame ) );
}
void Gui::MainWindow::keyPressEvent( QKeyEvent* event )
{
QMainWindow::keyPressEvent( event );
m_keyEvents.push_back( keyEventQtToRadium( event ) );
}
void Gui::MainWindow::keyReleaseEvent( QKeyEvent* event )
{
QMainWindow::keyReleaseEvent( event );
m_keyEvents.push_back( keyEventQtToRadium( event ) );
}
Core::MouseEvent Gui::MainWindow::wheelEventQtToRadium( const QWheelEvent* qtEvent )
{
Core::MouseEvent raEvent;
raEvent.wheelDelta = qtEvent->delta();
if ( qtEvent->modifiers().testFlag( Qt::ControlModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_CTRL_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::ShiftModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_SHIFT_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::AltModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_ALT_KEY;
}
raEvent.absoluteXPosition = qtEvent->x();
raEvent.absoluteYPosition = qtEvent->y();
return raEvent;
}
Core::MouseEvent Gui::MainWindow::mouseEventQtToRadium( const QMouseEvent* qtEvent )
{
Core::MouseEvent raEvent;
switch ( qtEvent->button() )
{
case Qt::LeftButton:
{
raEvent.button = Core::MouseButton::RA_MOUSE_LEFT_BUTTON;
}
break;
case Qt::MiddleButton:
{
raEvent.button = Core::MouseButton::RA_MOUSE_MIDDLE_BUTTON;
}
break;
case Qt::RightButton:
{
raEvent.button = Core::MouseButton::RA_MOUSE_RIGHT_BUTTON;
}
break;
default:
{
} break;
}
raEvent.modifier = 0;
if ( qtEvent->modifiers().testFlag( Qt::ControlModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_CTRL_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::ShiftModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_SHIFT_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::AltModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_ALT_KEY;
}
raEvent.absoluteXPosition = qtEvent->x();
raEvent.absoluteYPosition = qtEvent->y();
return raEvent;
}
Core::KeyEvent Gui::MainWindow::keyEventQtToRadium( const QKeyEvent* qtEvent )
{
Core::KeyEvent raEvent;
raEvent.key = qtEvent->key();
raEvent.modifier = 0;
if ( qtEvent->modifiers().testFlag( Qt::ControlModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_CTRL_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::ShiftModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_SHIFT_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::AltModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_ALT_KEY;
}
return raEvent;
}
Gui::Viewer* Gui::MainWindow::getViewer()
{
return m_viewer;
}
void Gui::MainWindow::handlePicking( int drawableIndex )
{
if ( drawableIndex >= 0 )
{
const std::shared_ptr<Engine::RenderObject>& ro =
mainApp->m_engine->getRenderObjectManager()->getRenderObject( drawableIndex );
// Ignore UI render objects.
if(ro->getType() == Engine::RenderObject::Type::RO_UI)
{
return;
}
const Engine::Component* comp = ro->getComponent();
const Engine::Entity* ent = comp->getEntity();
int compIdx = -1;
int i = 0;
for ( auto c : ent->getComponentsMap() )
{
if ( c.second == comp )
{
CORE_ASSERT( c.first == comp->getName(), "Inconsistent names" );
compIdx = i;
break;
}
++i;
}
CORE_ASSERT( compIdx >= 0, "Component is not in entity" );
Core::Index entIdx = ent->idx;
QModelIndex entityIdx = m_entityTreeModel->index( entIdx, 0 );
QModelIndex treeIdx = entityIdx;
if (true) // select component.
{
treeIdx = entityIdx.child(compIdx, 0);
}
m_entitiesTreeView->setExpanded( entityIdx, true );
m_entitiesTreeView->selectionModel()->select( treeIdx, QItemSelectionModel::SelectCurrent );
}
else
{
m_entitiesTreeView->selectionModel()->clear();
}
}
void Gui::MainWindow::onSelectionChanged( const QItemSelection& selected, const QItemSelection& deselected )
{
if ( selected.size() > 0 )
{
QModelIndex selIdx = selected.indexes()[0];
Engine::Entity* entity = m_entityTreeModel->getItem(selIdx)->getData(0).entity;
if (entity)
{
// Debug entity and objects are not selectable
if (entity != Engine::SystemEntity::getInstance())
{
emit selectedEntity(entity);
}
}
else
{
Engine::Component* comp = m_entityTreeModel->getItem(selIdx)->getData(0).component;
emit selectedComponent(comp);
}
}
else
{
emit selectedEntity( nullptr );
emit selectedComponent( nullptr );
}
}
void Gui::MainWindow::closeEvent( QCloseEvent *event )
{
emit closed();
event->accept();
}
void Gui::MainWindow::gizmoShowNone()
{
m_viewer->getGizmoManager()->changeGizmoType(GizmoManager::NONE);
}
void Gui::MainWindow::gizmoShowTranslate()
{
m_viewer->getGizmoManager()->changeGizmoType(GizmoManager::TRANSLATION);
}
void Gui::MainWindow::gizmoShowRotate()
{
m_viewer->getGizmoManager()->changeGizmoType(GizmoManager::ROTATION);
}
} // namespace Ra
<commit_msg>src/MainApplication/Gui/MainWindow.cpp<commit_after>#include <MainApplication/Gui/MainWindow.hpp>
#include <QFileDialog>
#include <QToolButton>
#include <Engine/RadiumEngine.hpp>
#include <Engine/Entity/Component.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/Renderer/Renderer.hpp>
#include <MainApplication/MainApplication.hpp>
#include <MainApplication/Gui/EntityTreeModel.hpp>
#include <MainApplication/Gui/EntityTreeItem.hpp>
#include <MainApplication/Viewer/CameraInterface.hpp>
#include <Plugins/Animation/AnimationSystem.hpp>
#include <assimp/Importer.hpp>
namespace Ra
{
Gui::MainWindow::MainWindow( QWidget* parent )
: QMainWindow( parent )
{
// Note : at this point most of the components (including the Engine) are
// not initialized. Listen to the "started" signal.
setupUi( this );
setWindowIcon( QPixmap( "../Assets/Images/RadiumIcon.png" ) );
setWindowTitle( QString( "Radium Engine" ) );
QStringList headers;
headers << tr( "Entities -> Components" );
m_entityTreeModel = new EntityTreeModel( headers );
m_entitiesTreeView->setModel( m_entityTreeModel );
createConnections();
mainApp->framesCountForStatsChanged(
m_avgFramesCount->value() );
m_viewer->getCameraInterface()->resetCamera();
}
Gui::MainWindow::~MainWindow()
{
// Child QObjects will automatically be deleted
}
void Gui::MainWindow::createConnections()
{
connect( actionOpenMesh, &QAction::triggered, this, &MainWindow::loadFile );
connect( actionReload_Shaders, &QAction::triggered, m_viewer, &Viewer::reloadShaders );
// Toolbox setup
connect( actionToggle_Local_Global, &QAction::toggled, m_viewer->getGizmoManager(), &GizmoManager::setLocal );
connect( actionGizmoOff, &QAction::triggered, this, &MainWindow::gizmoShowNone );
connect( actionGizmoTranslate, &QAction::triggered, this, &MainWindow::gizmoShowTranslate );
connect( actionGizmoRotate, &QAction::triggered, this, &MainWindow::gizmoShowRotate );
//connect( actionGizmoOff, &QAction::toggled, this, &gizmoShowNone);
// Loading setup.
connect( this, &MainWindow::fileLoading, mainApp, &MainApplication::loadFile );
connect( this, &MainWindow::entitiesUpdated, m_entityTreeModel, &EntityTreeModel::entitiesUpdated );
/* connect( m_entityTreeModel, SIGNAL( objectNameChanged( QString ) ),
this, SLOT( objectNameChanged( QString ) ) );*/
// Side menu setup.
connect( m_entityTreeModel, &EntityTreeModel::dataChanged, m_entityTreeModel, &EntityTreeModel::handleRename );
connect( m_entitiesTreeView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &MainWindow::onSelectionChanged );
// Camera panel setup
connect( m_cameraResetButton, &QPushButton::released, m_viewer->getCameraInterface(), &CameraInterface::resetCamera);
connect( m_setCameraPositionButton, &QPushButton::released, this, &MainWindow::setCameraPosition);
connect( m_setCameraTargetButton, &QPushButton::released, this, &MainWindow::setCameraTarget);
connect( this, &MainWindow::cameraPositionSet, m_viewer->getCameraInterface(), &CameraInterface::setCameraPosition );
connect( this, &MainWindow::cameraTargetSet, m_viewer->getCameraInterface(), &CameraInterface::setCameraTarget );
connect( m_viewer->getCameraInterface(), &CameraInterface::cameraPositionChanged, this, &MainWindow::onCameraPositionChanged );
connect( m_viewer->getCameraInterface(), &CameraInterface::cameraTargetChanged, this, &MainWindow::onCameraTargetChanged );
// Oh C++ why are you so mean to me ?
connect( m_cameraSensitivity, static_cast<void (QDoubleSpinBox::*) (double)>(&QDoubleSpinBox::valueChanged),
m_viewer->getCameraInterface(), &CameraInterface::setCameraSensitivity );
// Connect picking results (TODO Val : use events to dispatch picking directly)
connect( m_viewer, &Viewer::rightClickPicking, this, &MainWindow::handlePicking );
connect (m_viewer, &Viewer::leftClickPicking, m_viewer->getGizmoManager(), &GizmoManager::handlePickingResult );
// Update entities when the engine starts.
connect( mainApp, &MainApplication::starting, this, &MainWindow::onEntitiesUpdated );
connect( m_avgFramesCount, static_cast< void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
mainApp , &MainApplication::framesCountForStatsChanged );
connect(mainApp, &MainApplication::updateFrameStats, this, &MainWindow::onUpdateFramestats);
// Inform property editors of new selections
connect(this, &MainWindow::selectedEntity, tab_edition, &TransformEditorWidget::setEditable);
connect(this, &MainWindow::selectedEntity, m_viewer->getGizmoManager(), &GizmoManager::setEditable);
// Editors should be updated after each frame
connect(mainApp, &MainApplication::endFrame, tab_edition, &TransformEditorWidget::updateValues);
connect(mainApp, &MainApplication::endFrame, m_viewer->getGizmoManager(), &GizmoManager::updateValues);
connect(playButton, SIGNAL(clicked(bool)), this, SLOT(playAnimation()));
connect(pauseButton, SIGNAL(clicked(bool)), this, SLOT(pauseAnimation()));
}
void Gui::MainWindow::playAnimation()
{
AnimationPlugin::AnimationSystem* animSys = (AnimationPlugin::AnimationSystem*) mainApp->m_engine->getSystem("AnimationSystem");
animSys->setPlaying(true);
}
void Gui::MainWindow::pauseAnimation()
{
AnimationPlugin::AnimationSystem* animSys = (AnimationPlugin::AnimationSystem*) mainApp->m_engine->getSystem("AnimationSystem");
animSys->setPlaying(false);
}
void Gui::MainWindow::onEntitiesUpdated()
{
emit entitiesUpdated( mainApp->m_engine->getEntityManager()->getEntities() );
}
void Gui::MainWindow::onCameraPositionChanged( const Core::Vector3& p )
{
// TODO : use a vectorEditor.
m_cameraPositionX->setValue( p.x() );
m_cameraPositionY->setValue( p.y() );
m_cameraPositionZ->setValue( p.z() );
}
void Gui::MainWindow::onCameraTargetChanged( const Core::Vector3& p )
{
m_cameraTargetX->setValue( p.x() );
m_cameraTargetY->setValue( p.y() );
m_cameraTargetZ->setValue( p.z() );
}
void Gui::MainWindow::setCameraPosition()
{
Core::Vector3 P( m_cameraPositionX->value(),
m_cameraPositionY->value(),
m_cameraPositionZ->value() );
emit cameraPositionSet( P );
}
void Gui::MainWindow::setCameraTarget()
{
Core::Vector3 T( m_cameraTargetX->value(),
m_cameraTargetY->value(),
m_cameraTargetZ->value() );
emit cameraTargetSet( T );
}
void Gui::MainWindow::loadFile()
{
// Filter the files
aiString extList;
Assimp::Importer importer;
importer.GetExtensionList(extList);
std::string extListStd(extList.C_Str());
std::replace(extListStd.begin(), extListStd.end(), ';', ' ');
QString filter = QString::fromStdString(extListStd);
QString path = QFileDialog::getOpenFileName( this, "Open File", "..", filter);
if ( path.size() > 0 )
{
emit fileLoading( path );
}
onEntitiesUpdated();
}
void Gui::MainWindow::onUpdateFramestats( const std::vector<FrameTimerData>& stats )
{
QString framesA2B = QString( "Frames #%1 to #%2 stats :" )
.arg( stats.front().numFrame ).arg( stats.back().numFrame );
m_frameA2BLabel->setText( framesA2B );
long sumRender = 0;
long sumTasks = 0;
long sumFrame = 0;
long sumInterFrame = 0;
for ( uint i = 0; i < stats.size(); ++i )
{
sumRender += Core::Timer::getIntervalMicro(
stats[i].renderData.renderStart, stats[i].renderData.renderEnd );
sumTasks += Core::Timer::getIntervalMicro(
stats[i].tasksStart, stats[i].tasksEnd );
sumFrame += Core::Timer::getIntervalMicro(
stats[i].frameStart, stats[i].frameEnd );
if ( i > 0 )
{
sumInterFrame += Core::Timer::getIntervalMicro(
stats[i - 1].frameEnd, stats[i].frameEnd );
}
}
const uint N = stats.size();
const Scalar T( N * 1000000.0 );
m_renderTime->setValue( sumRender / N );
m_renderUpdates->setValue( T / Scalar( sumRender ) );
m_tasksTime->setValue( sumTasks / N );
m_tasksUpdates->setValue( T / Scalar( sumTasks ) );
m_frameTime->setValue( sumFrame / N );
m_frameUpdates->setValue( T / Scalar( sumFrame ) );
m_avgFramerate->setValue( ( N - 1 ) * Scalar( 1000000.0 / sumInterFrame ) );
}
void Gui::MainWindow::keyPressEvent( QKeyEvent* event )
{
QMainWindow::keyPressEvent( event );
m_keyEvents.push_back( keyEventQtToRadium( event ) );
}
void Gui::MainWindow::keyReleaseEvent( QKeyEvent* event )
{
QMainWindow::keyReleaseEvent( event );
m_keyEvents.push_back( keyEventQtToRadium( event ) );
}
Core::MouseEvent Gui::MainWindow::wheelEventQtToRadium( const QWheelEvent* qtEvent )
{
Core::MouseEvent raEvent;
raEvent.wheelDelta = qtEvent->delta();
if ( qtEvent->modifiers().testFlag( Qt::ControlModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_CTRL_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::ShiftModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_SHIFT_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::AltModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_ALT_KEY;
}
raEvent.absoluteXPosition = qtEvent->x();
raEvent.absoluteYPosition = qtEvent->y();
return raEvent;
}
Core::MouseEvent Gui::MainWindow::mouseEventQtToRadium( const QMouseEvent* qtEvent )
{
Core::MouseEvent raEvent;
switch ( qtEvent->button() )
{
case Qt::LeftButton:
{
raEvent.button = Core::MouseButton::RA_MOUSE_LEFT_BUTTON;
}
break;
case Qt::MiddleButton:
{
raEvent.button = Core::MouseButton::RA_MOUSE_MIDDLE_BUTTON;
}
break;
case Qt::RightButton:
{
raEvent.button = Core::MouseButton::RA_MOUSE_RIGHT_BUTTON;
}
break;
default:
{
} break;
}
raEvent.modifier = 0;
if ( qtEvent->modifiers().testFlag( Qt::ControlModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_CTRL_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::ShiftModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_SHIFT_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::AltModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_ALT_KEY;
}
raEvent.absoluteXPosition = qtEvent->x();
raEvent.absoluteYPosition = qtEvent->y();
return raEvent;
}
Core::KeyEvent Gui::MainWindow::keyEventQtToRadium( const QKeyEvent* qtEvent )
{
Core::KeyEvent raEvent;
raEvent.key = qtEvent->key();
raEvent.modifier = 0;
if ( qtEvent->modifiers().testFlag( Qt::ControlModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_CTRL_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::ShiftModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_SHIFT_KEY;
}
if ( qtEvent->modifiers().testFlag( Qt::AltModifier ) )
{
raEvent.modifier |= Core::Modifier::RA_ALT_KEY;
}
return raEvent;
}
Gui::Viewer* Gui::MainWindow::getViewer()
{
return m_viewer;
}
void Gui::MainWindow::handlePicking( int drawableIndex )
{
if ( drawableIndex >= 0 )
{
const std::shared_ptr<Engine::RenderObject>& ro =
mainApp->m_engine->getRenderObjectManager()->getRenderObject( drawableIndex );
// Ignore UI render objects.
if(ro->getType() == Engine::RenderObject::Type::RO_UI)
{
return;
}
const Engine::Component* comp = ro->getComponent();
const Engine::Entity* ent = comp->getEntity();
int compIdx = -1;
int i = 0;
for ( auto c : ent->getComponentsMap() )
{
if ( c.second == comp )
{
CORE_ASSERT( c.first == comp->getName(), "Inconsistent names" );
compIdx = i;
break;
}
++i;
}
CORE_ASSERT( compIdx >= 0, "Component is not in entity" );
Core::Index entIdx = ent->idx;
QModelIndex entityIdx = m_entityTreeModel->index( entIdx, 0 );
QModelIndex treeIdx = entityIdx;
if (true) // select component.
{
treeIdx = entityIdx.child(compIdx, 0);
}
m_entitiesTreeView->setExpanded( entityIdx, true );
m_entitiesTreeView->selectionModel()->select( treeIdx, QItemSelectionModel::SelectCurrent );
}
else
{
m_entitiesTreeView->selectionModel()->clear();
}
}
void Gui::MainWindow::onSelectionChanged( const QItemSelection& selected, const QItemSelection& deselected )
{
if ( selected.size() > 0 )
{
QModelIndex selIdx = selected.indexes()[0];
Engine::Entity* entity = m_entityTreeModel->getItem(selIdx)->getData(0).entity;
if (entity)
{
// Debug entity and objects are not selectable
if (entity != Engine::SystemEntity::getInstance())
{
emit selectedEntity(entity);
}
}
else
{
Engine::Component* comp = m_entityTreeModel->getItem(selIdx)->getData(0).component;
emit selectedComponent(comp);
}
}
else
{
emit selectedEntity( nullptr );
emit selectedComponent( nullptr );
}
}
void Gui::MainWindow::closeEvent( QCloseEvent *event )
{
emit closed();
event->accept();
}
void Gui::MainWindow::gizmoShowNone()
{
m_viewer->getGizmoManager()->changeGizmoType(GizmoManager::NONE);
}
void Gui::MainWindow::gizmoShowTranslate()
{
m_viewer->getGizmoManager()->changeGizmoType(GizmoManager::TRANSLATION);
}
void Gui::MainWindow::gizmoShowRotate()
{
m_viewer->getGizmoManager()->changeGizmoType(GizmoManager::ROTATION);
}
} // namespace Ra
<|endoftext|> |
<commit_before>#include <propertyguizeug/ChoicesModel.h>
#include <utility>
#include <reflectionzeug/property/AbstractProperty.h>
#include "util.h"
namespace propertyguizeug
{
ChoicesModel::ChoicesModel(reflectionzeug::AbstractProperty * property)
: m_property(property)
{
if (m_property->hasOption("choices"))
{
auto choices = m_property->option("choices").value<std::vector<std::string>>();
m_strings = util::toQStringList(choices);
}
obtainPixmaps();
}
ChoicesModel::ChoicesModel(reflectionzeug::AbstractProperty * property, const std::vector<std::string> & choices)
: m_property(property)
, m_strings(util::toQStringList(choices))
{
obtainPixmaps();
}
ChoicesModel::~ChoicesModel()
{
}
void ChoicesModel::obtainPixmaps()
{
if (hasIcons())
{
const auto pixmapSize = iconSize();
const auto pixmaps = m_property->option("pixmaps").value<std::vector<std::vector<unsigned char>>>();
for (const auto & pixmap : pixmaps)
{
const QImage image(pixmap.data(), pixmapSize.width(), pixmapSize.height(), QImage::Format_ARGB32);
m_pixmaps.push_back(QPixmap::fromImage(image));
}
}
}
bool ChoicesModel::hasIcons() const
{
return m_property->hasOption("pixmaps") && m_property->hasOption("pixmapSize");
}
QSize ChoicesModel::iconSize() const
{
if (!hasIcons())
{
return { 0u, 0u };
}
const auto size = m_property->option("pixmapSize").value<std::pair<std::uint32_t, std::uint32_t>>();
return QSize(size.first, size.second);
}
QModelIndex ChoicesModel::index(int row, int column, const QModelIndex & /* parent */) const
{
return createIndex(row, column);
}
QModelIndex ChoicesModel::parent(const QModelIndex & /*index*/) const
{
return QModelIndex();
}
int ChoicesModel::rowCount(const QModelIndex & /* parent */) const
{
return qMax(m_strings.size(), m_pixmaps.size());
}
int ChoicesModel::columnCount(const QModelIndex & /* parent */) const
{
return 1;
}
QVariant ChoicesModel::data(const QModelIndex & index, int role) const
{
switch (role)
{
case Qt::DisplayRole:
return m_strings.value(index.row(), "");
break;
case Qt::DecorationRole:
return m_pixmaps.value(index.row(), QPixmap());
break;
default:
return QVariant();
break;
}
}
} // namespace propertyguizeug
<commit_msg>Fix compilation on Windows<commit_after>#include <propertyguizeug/ChoicesModel.h>
#include <utility>
#include <reflectionzeug/property/AbstractProperty.h>
#include "util.h"
namespace propertyguizeug
{
ChoicesModel::ChoicesModel(reflectionzeug::AbstractProperty * property)
: m_property(property)
{
if (m_property->hasOption("choices"))
{
auto choices = m_property->option("choices").value<std::vector<std::string>>();
m_strings = util::toQStringList(choices);
}
obtainPixmaps();
}
ChoicesModel::ChoicesModel(reflectionzeug::AbstractProperty * property, const std::vector<std::string> & choices)
: m_property(property)
, m_strings(util::toQStringList(choices))
{
obtainPixmaps();
}
ChoicesModel::~ChoicesModel()
{
}
void ChoicesModel::obtainPixmaps()
{
if (hasIcons())
{
const auto pixmapSize = iconSize();
const auto pixmaps = m_property->option("pixmaps").value<std::vector<std::vector<unsigned char>>>();
for (const auto & pixmap : pixmaps)
{
const QImage image(pixmap.data(), pixmapSize.width(), pixmapSize.height(), QImage::Format_ARGB32);
m_pixmaps.push_back(QPixmap::fromImage(image));
}
}
}
bool ChoicesModel::hasIcons() const
{
return m_property->hasOption("pixmaps") && m_property->hasOption("pixmapSize");
}
QSize ChoicesModel::iconSize() const
{
if (!hasIcons())
{
return { 0u, 0u };
}
const auto size = m_property->option("pixmapSize").value<std::pair<uint32_t, uint32_t>>();
return QSize(size.first, size.second);
}
QModelIndex ChoicesModel::index(int row, int column, const QModelIndex & /* parent */) const
{
return createIndex(row, column);
}
QModelIndex ChoicesModel::parent(const QModelIndex & /*index*/) const
{
return QModelIndex();
}
int ChoicesModel::rowCount(const QModelIndex & /* parent */) const
{
return qMax(m_strings.size(), m_pixmaps.size());
}
int ChoicesModel::columnCount(const QModelIndex & /* parent */) const
{
return 1;
}
QVariant ChoicesModel::data(const QModelIndex & index, int role) const
{
switch (role)
{
case Qt::DisplayRole:
return m_strings.value(index.row(), "");
break;
case Qt::DecorationRole:
return m_pixmaps.value(index.row(), QPixmap());
break;
default:
return QVariant();
break;
}
}
} // namespace propertyguizeug
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "PointerDataType.h"
#include "HelperFunction.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
using namespace FTL;
namespace FTLTest
{
TEST_CLASS(PointerTest)
{
public:
TEST_METHOD(TestMethod1)
{
unique_ptr<int> ptpt;
int a = 3;
int* pA = &a;
PointerDataType<int*> t1 = &a;
int*& ppA = pA;
*ppA;
decltype((*ppA)) pppA = *pA;
Log(*t1);
}
};
}<commit_msg>Test name changed<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "PointerDataType.h"
#include "HelperFunction.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
using namespace FTL;
namespace FTLTest
{
TEST_CLASS(PointerTest)
{
public:
TEST_METHOD(PointerTest1)
{
unique_ptr<int> ptpt;
int a = 3;
int* pA = &a;
PointerDataType<int*> t1 = &a;
int*& ppA = pA;
*ppA;
decltype((*ppA)) pppA = *pA;
Log(*t1);
}
};
}<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2014-2015 Nathan Miller <Nathan.A.Mill[at]gmail.com> *
* Balázs Bámer *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#include <ShapeFix_Wire.hxx>
#include <ShapeExtend_WireData.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Wire.hxx>
#include <BRepBuilderAPI_Copy.hxx>
#include <Geom_BezierCurve.hxx>
#include <Geom_BSplineCurve.hxx>
#include <GeomFill_BezierCurves.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <TopExp_Explorer.hxx>
#include <BRep_Tool.hxx>
#endif
#include <Base/Exception.h>
#include <Base/Tools.h>
#include "FeatureSurface.h"
using namespace Surface;
ShapeValidator::ShapeValidator()
{
initValidator();
}
void ShapeValidator::initValidator(void)
{
willBezier = willBSpline = false;
edgeCount = 0;
}
// shows error message if the shape is not an edge
void ShapeValidator::checkEdge(const TopoDS_Shape& shape)
{
if (shape.IsNull() || shape.ShapeType() != TopAbs_EDGE) {
Standard_Failure::Raise("Shape is not an edge.");
}
TopoDS_Edge etmp = TopoDS::Edge(shape); //Curve TopoDS_Edge
TopLoc_Location heloc; // this will be output
Standard_Real u0;// contains output
Standard_Real u1;// contains output
Handle_Geom_Curve c_geom = BRep_Tool::Curve(etmp,heloc,u0,u1); //The geometric curve
Handle_Geom_BezierCurve bez_geom = Handle_Geom_BezierCurve::DownCast(c_geom); //Try to get Bezier curve
Handle_Geom_BSplineCurve bsp_geom = Handle_Geom_BSplineCurve::DownCast(c_geom); //Try to get BSpline curve
if (!bez_geom.IsNull()) {
// this one is a Bezier
if (willBSpline) {
// already found the other type, fail
Standard_Failure::Raise("Mixing Bezier and B-Spline curves is not allowed.");
}
// we will create Bezier surface
willBezier = true;
}
else if (!bsp_geom.IsNull()) {
// this one is Bezier
if (willBezier) {
// already found the other type, fail
Standard_Failure::Raise("Mixing Bezier and B-Spline curves is not allowed.");
}
// we will create B-Spline surface
willBSpline = true;
}
else {
//Standard_Failure::Raise("Neither Bezier nor B-Spline curve.");
}
edgeCount++;
}
void ShapeValidator::checkAndAdd(const TopoDS_Shape &shape, Handle(ShapeExtend_WireData) *aWD)
{
checkEdge(shape);
if (aWD != NULL) {
BRepBuilderAPI_Copy copier(shape);
// make a copy of the shape and the underlying geometry to avoid to affect the input shapes
(*aWD)->Add(TopoDS::Edge(copier.Shape()));
}
}
void ShapeValidator::checkAndAdd(const Part::TopoShape &ts, const char *subName, Handle(ShapeExtend_WireData) *aWD)
{
try {
#if 0 // weird logic!
// unwrap the wire
if ((!ts._Shape.IsNull()) && ts._Shape.ShapeType() == TopAbs_WIRE) {
TopoDS_Wire wire = TopoDS::Wire(ts._Shape);
for (TopExp_Explorer wireExplorer (wire, TopAbs_EDGE); wireExplorer.More(); wireExplorer.Next()) {
checkAndAdd(wireExplorer.Current(), aWD);
}
}
else {
if (subName != NULL && *subName != 0) {
//we want only the subshape which is linked
checkAndAdd(ts.getSubShape(subName), aWD);
}
else {
checkAndAdd(ts._Shape, aWD);
}
}
#else
if (subName != NULL && *subName != '\0') {
//we want only the subshape which is linked
checkAndAdd(ts.getSubShape(subName), aWD);
}
else if (!ts.getShape().IsNull() && ts.getShape().ShapeType() == TopAbs_WIRE) {
TopoDS_Wire wire = TopoDS::Wire(ts.getShape());
for (TopExp_Explorer xp(wire, TopAbs_EDGE); xp.More(); xp.Next()) {
checkAndAdd(xp.Current(), aWD);
}
}
else {
checkAndAdd(ts.getShape(), aWD);
}
#endif
}
catch(Standard_Failure) { // any OCC exception means an unappropriate shape in the selection
Standard_Failure::Raise("Wrong shape type.");
}
}
PROPERTY_SOURCE(Surface::SurfaceFeature, Part::Feature)
const char* SurfaceFeature::FillTypeEnums[] = {"Invalid", "Stretched", "Coons", "Curved", NULL};
SurfaceFeature::SurfaceFeature(): Feature()
{
ADD_PROPERTY(FillType, ((long)0));
ADD_PROPERTY(BoundaryList, (0, "Dummy"));
FillType.setStatus(App::Property::ReadOnly, true); // read-only in property editor
FillType.setEnums(FillTypeEnums);
}
//Check if any components of the surface have been modified
short SurfaceFeature::mustExecute() const
{
if (BoundaryList.isTouched() ||
FillType.isTouched())
{
return 1;
}
return 0;
}
GeomFill_FillingStyle SurfaceFeature::getFillingStyle()
{
//Identify filling style
int ftype = FillType.getValue();
if (ftype==StretchStyle)
return GeomFill_StretchStyle;
else if(ftype==CoonsStyle)
return GeomFill_CoonsStyle;
else if(ftype==CurvedStyle)
return GeomFill_CurvedStyle;
else
Standard_Failure::Raise("Filling style must be 1 (Stretch), 2 (Coons), or 3 (Curved).");
throw; // this is to shut up the compiler
}
void SurfaceFeature::getWire(TopoDS_Wire& aWire)
{
Handle(ShapeFix_Wire) aShFW = new ShapeFix_Wire;
Handle(ShapeExtend_WireData) aWD = new ShapeExtend_WireData;
std::vector<App::PropertyLinkSubList::SubSet> boundary = BoundaryList.getSubListValues();
if(boundary.size() > 4) // if too many not even try
{
Standard_Failure::Raise("Only 2-4 curves are allowed");
}
ShapeValidator validator;
for(std::size_t i = 0; i < boundary.size(); i++) {
App::PropertyLinkSubList::SubSet set = boundary[i];
if (set.first->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
for (auto jt: set.second) {
const Part::TopoShape &ts = static_cast<Part::Feature*>(set.first)->Shape.getShape();
validator.checkAndAdd(ts, jt.c_str(), &aWD);
}
}
else {
Standard_Failure::Raise("Curve not from Part::Feature");
}
}
if (validator.numEdges() < 2 || validator.numEdges() > 4) {
Standard_Failure::Raise("Only 2-4 curves are allowed");
}
//Reorder the curves and fix the wire if required
aShFW->Load(aWD); //Load in the wire
aShFW->FixReorder(); //Fix the order of the edges if required
aShFW->ClosedWireMode() = Standard_True; //Enables closed wire mode
aShFW->FixConnected(); //Fix connection between wires
aShFW->FixSelfIntersection(); //Fix Self Intersection
aShFW->Perform(); //Perform the fixes
aWire = aShFW->Wire(); //Healed Wire
if (aWire.IsNull()) {
Standard_Failure::Raise("Wire unable to be constructed");
}
}
void SurfaceFeature::createFace(const Handle_Geom_BoundedSurface &aSurface)
{
BRepBuilderAPI_MakeFace aFaceBuilder;
Standard_Real u1, u2, v1, v2;
// transfer surface bounds to face
aSurface->Bounds(u1, u2, v1, v2);
aFaceBuilder.Init(aSurface, u1, u2, v1, v2, Precision::Confusion());
TopoDS_Face aFace = aFaceBuilder.Face();
if (!aFaceBuilder.IsDone()) {
Standard_Failure::Raise("Face unable to be constructed");
}
if (aFace.IsNull()) {
Standard_Failure::Raise("Resulting Face is null");
}
this->Shape.setValue(aFace);
}
void SurfaceFeature::correcteInvalidFillType()
{
int ftype = FillType.getValue();
if(ftype == InvalidStyle)
{
FillType.setValue(StretchStyle);
}
}
<commit_msg>do not make property read-only in property editor<commit_after>/***************************************************************************
* Copyright (c) 2014-2015 Nathan Miller <Nathan.A.Mill[at]gmail.com> *
* Balázs Bámer *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#include <ShapeFix_Wire.hxx>
#include <ShapeExtend_WireData.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Wire.hxx>
#include <BRepBuilderAPI_Copy.hxx>
#include <Geom_BezierCurve.hxx>
#include <Geom_BSplineCurve.hxx>
#include <GeomFill_BezierCurves.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <TopExp_Explorer.hxx>
#include <BRep_Tool.hxx>
#endif
#include <Base/Exception.h>
#include <Base/Tools.h>
#include "FeatureSurface.h"
using namespace Surface;
ShapeValidator::ShapeValidator()
{
initValidator();
}
void ShapeValidator::initValidator(void)
{
willBezier = willBSpline = false;
edgeCount = 0;
}
// shows error message if the shape is not an edge
void ShapeValidator::checkEdge(const TopoDS_Shape& shape)
{
if (shape.IsNull() || shape.ShapeType() != TopAbs_EDGE) {
Standard_Failure::Raise("Shape is not an edge.");
}
TopoDS_Edge etmp = TopoDS::Edge(shape); //Curve TopoDS_Edge
TopLoc_Location heloc; // this will be output
Standard_Real u0;// contains output
Standard_Real u1;// contains output
Handle_Geom_Curve c_geom = BRep_Tool::Curve(etmp,heloc,u0,u1); //The geometric curve
Handle_Geom_BezierCurve bez_geom = Handle_Geom_BezierCurve::DownCast(c_geom); //Try to get Bezier curve
Handle_Geom_BSplineCurve bsp_geom = Handle_Geom_BSplineCurve::DownCast(c_geom); //Try to get BSpline curve
if (!bez_geom.IsNull()) {
// this one is a Bezier
if (willBSpline) {
// already found the other type, fail
Standard_Failure::Raise("Mixing Bezier and B-Spline curves is not allowed.");
}
// we will create Bezier surface
willBezier = true;
}
else if (!bsp_geom.IsNull()) {
// this one is Bezier
if (willBezier) {
// already found the other type, fail
Standard_Failure::Raise("Mixing Bezier and B-Spline curves is not allowed.");
}
// we will create B-Spline surface
willBSpline = true;
}
else {
//Standard_Failure::Raise("Neither Bezier nor B-Spline curve.");
}
edgeCount++;
}
void ShapeValidator::checkAndAdd(const TopoDS_Shape &shape, Handle(ShapeExtend_WireData) *aWD)
{
checkEdge(shape);
if (aWD != NULL) {
BRepBuilderAPI_Copy copier(shape);
// make a copy of the shape and the underlying geometry to avoid to affect the input shapes
(*aWD)->Add(TopoDS::Edge(copier.Shape()));
}
}
void ShapeValidator::checkAndAdd(const Part::TopoShape &ts, const char *subName, Handle(ShapeExtend_WireData) *aWD)
{
try {
#if 0 // weird logic!
// unwrap the wire
if ((!ts._Shape.IsNull()) && ts._Shape.ShapeType() == TopAbs_WIRE) {
TopoDS_Wire wire = TopoDS::Wire(ts._Shape);
for (TopExp_Explorer wireExplorer (wire, TopAbs_EDGE); wireExplorer.More(); wireExplorer.Next()) {
checkAndAdd(wireExplorer.Current(), aWD);
}
}
else {
if (subName != NULL && *subName != 0) {
//we want only the subshape which is linked
checkAndAdd(ts.getSubShape(subName), aWD);
}
else {
checkAndAdd(ts._Shape, aWD);
}
}
#else
if (subName != NULL && *subName != '\0') {
//we want only the subshape which is linked
checkAndAdd(ts.getSubShape(subName), aWD);
}
else if (!ts.getShape().IsNull() && ts.getShape().ShapeType() == TopAbs_WIRE) {
TopoDS_Wire wire = TopoDS::Wire(ts.getShape());
for (TopExp_Explorer xp(wire, TopAbs_EDGE); xp.More(); xp.Next()) {
checkAndAdd(xp.Current(), aWD);
}
}
else {
checkAndAdd(ts.getShape(), aWD);
}
#endif
}
catch(Standard_Failure) { // any OCC exception means an unappropriate shape in the selection
Standard_Failure::Raise("Wrong shape type.");
}
}
PROPERTY_SOURCE(Surface::SurfaceFeature, Part::Feature)
const char* SurfaceFeature::FillTypeEnums[] = {"Invalid", "Stretched", "Coons", "Curved", NULL};
SurfaceFeature::SurfaceFeature(): Feature()
{
ADD_PROPERTY(FillType, ((long)0));
ADD_PROPERTY(BoundaryList, (0, "Dummy"));
FillType.setEnums(FillTypeEnums);
}
//Check if any components of the surface have been modified
short SurfaceFeature::mustExecute() const
{
if (BoundaryList.isTouched() ||
FillType.isTouched())
{
return 1;
}
return 0;
}
GeomFill_FillingStyle SurfaceFeature::getFillingStyle()
{
//Identify filling style
int ftype = FillType.getValue();
if (ftype==StretchStyle)
return GeomFill_StretchStyle;
else if(ftype==CoonsStyle)
return GeomFill_CoonsStyle;
else if(ftype==CurvedStyle)
return GeomFill_CurvedStyle;
else
Standard_Failure::Raise("Filling style must be 1 (Stretch), 2 (Coons), or 3 (Curved).");
throw; // this is to shut up the compiler
}
void SurfaceFeature::getWire(TopoDS_Wire& aWire)
{
Handle(ShapeFix_Wire) aShFW = new ShapeFix_Wire;
Handle(ShapeExtend_WireData) aWD = new ShapeExtend_WireData;
std::vector<App::PropertyLinkSubList::SubSet> boundary = BoundaryList.getSubListValues();
if(boundary.size() > 4) // if too many not even try
{
Standard_Failure::Raise("Only 2-4 curves are allowed");
}
ShapeValidator validator;
for(std::size_t i = 0; i < boundary.size(); i++) {
App::PropertyLinkSubList::SubSet set = boundary[i];
if (set.first->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
for (auto jt: set.second) {
const Part::TopoShape &ts = static_cast<Part::Feature*>(set.first)->Shape.getShape();
validator.checkAndAdd(ts, jt.c_str(), &aWD);
}
}
else {
Standard_Failure::Raise("Curve not from Part::Feature");
}
}
if (validator.numEdges() < 2 || validator.numEdges() > 4) {
Standard_Failure::Raise("Only 2-4 curves are allowed");
}
//Reorder the curves and fix the wire if required
aShFW->Load(aWD); //Load in the wire
aShFW->FixReorder(); //Fix the order of the edges if required
aShFW->ClosedWireMode() = Standard_True; //Enables closed wire mode
aShFW->FixConnected(); //Fix connection between wires
aShFW->FixSelfIntersection(); //Fix Self Intersection
aShFW->Perform(); //Perform the fixes
aWire = aShFW->Wire(); //Healed Wire
if (aWire.IsNull()) {
Standard_Failure::Raise("Wire unable to be constructed");
}
}
void SurfaceFeature::createFace(const Handle_Geom_BoundedSurface &aSurface)
{
BRepBuilderAPI_MakeFace aFaceBuilder;
Standard_Real u1, u2, v1, v2;
// transfer surface bounds to face
aSurface->Bounds(u1, u2, v1, v2);
aFaceBuilder.Init(aSurface, u1, u2, v1, v2, Precision::Confusion());
TopoDS_Face aFace = aFaceBuilder.Face();
if (!aFaceBuilder.IsDone()) {
Standard_Failure::Raise("Face unable to be constructed");
}
if (aFace.IsNull()) {
Standard_Failure::Raise("Resulting Face is null");
}
this->Shape.setValue(aFace);
}
void SurfaceFeature::correcteInvalidFillType()
{
int ftype = FillType.getValue();
if(ftype == InvalidStyle)
{
FillType.setValue(StretchStyle);
}
}
<|endoftext|> |
<commit_before>/**
* @file persistence_dat.cpp
*
* @brief Purpose: Contains methods to save the game
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*
*/
#include "persistence_dat.hpp"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>
using namespace engine;
PersistenceDat *PersistenceDat::instance = 0;
/**
* @brief Get Instance
*
* Method responsible for get instance
*
* @return void
*/
PersistenceDat *PersistenceDat::get_instance(){
if (!instance)
instance = new PersistenceDat();
return instance;
}
/**
* @brief Load Method
*
* Method responsible for load the saved game
*
* @param p_path path to saved game
* @return game loaded
*/
PersistenceMap * PersistenceDat::load(std::string p_path){
PersistenceMap *data = new PersistenceMap();
std::stack<std::string> paths;
paths.push(p_path);
std::string line;
while(!paths.empty()){
std::string path = paths.top();
paths.pop();
std::ifstream save_file;
save_file.open(path, std::ifstream::in);
if (save_file.is_open()){
while (std::getline(save_file,line)){
bool is_include = false;
std::istringstream iss(line);
std::string key;
std::string value;
std::unordered_map<std::string, std::string> object_data;
if (line != "" && line[0] != '#'){
while(iss >> key && iss >> value){
if((is_include = (key == "include"))){
paths.push(value);
}
object_data[key] = value;
}
if (!is_include) data->insert_object(object_data);
}
}
}
else {
std::cout << "Unable to open file" << std::endl;
return NULL;
}
}
return data;
}
/**
* @brief Dump Method
*
* Method responsible for dump
*
* @param path path to save the open game in a file
* @param data saved game
* @return void
*/
bool PersistenceDat::dump(std::string path, PersistenceMap * data){
std::ofstream save_file;
save_file.open(path);
if(save_file.is_open())
for(auto it = data->begin(); it < data->end(); it++){
for(auto each_data : *it){
save_file << each_data.first << " " << each_data.second << " ";
}
save_file << std::endl;
}
else
return false;
save_file.close();
return true;
}
<commit_msg>[INITIALIZATION] Applies initialization in persistence_dat.cpp<commit_after>/**
* @file persistence_dat.cpp
*
* @brief Purpose: Contains methods to save the game
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*
*/
#include "persistence_dat.hpp"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>
using namespace engine;
PersistenceDat *PersistenceDat::instance = 0;
/**
* @brief Get Instance
*
* Method responsible for get instance
*
* @return void
*/
PersistenceDat *PersistenceDat::get_instance(){
if (!instance)
instance = nullptr;
instance = new PersistenceDat();
return instance;
}
/**
* @brief Load Method
*
* Method responsible for load the saved game
*
* @param p_path path to saved game
* @return game loaded
*/
PersistenceMap * PersistenceDat::load(std::string p_path){
PersistenceMap *data = nullptr;
data = new PersistenceMap();
std::stack<std::string> paths;
paths.push(p_path);
std::string line;
while(!paths.empty()){
std::string path = paths.top();
paths.pop();
std::ifstream save_file;
save_file.open(path, std::ifstream::in);
if (save_file.is_open()){
while (std::getline(save_file,line)){
bool is_include = false;
std::istringstream iss(line);
std::string key;
std::string value;
std::unordered_map<std::string, std::string> object_data;
if (line != "" && line[0] != '#'){
while(iss >> key && iss >> value){
if((is_include = (key == "include"))){
paths.push(value);
}
object_data[key] = value;
}
if (!is_include) data->insert_object(object_data);
}
}
}
else {
std::cout << "Unable to open file" << std::endl;
return NULL;
}
}
return data;
}
/**
* @brief Dump Method
*
* Method responsible for dump
*
* @param path path to save the open game in a file
* @param data saved game
* @return void
*/
bool PersistenceDat::dump(std::string path, PersistenceMap * data){
std::ofstream save_file;
save_file.open(path);
if(save_file.is_open())
for(auto it = data->begin(); it < data->end(); it++){
for(auto each_data : *it){
save_file << each_data.first << " " << each_data.second << " ";
}
save_file << std::endl;
}
else
return false;
save_file.close();
return true;
}
<|endoftext|> |
<commit_before>/*
PubSubClient.cpp - A simple client for MQTT.
Nicholas O'Leary
http://knolleary.net
*/
#include "PubSubClient.h"
#include <string.h>
PubSubClient::PubSubClient(Client& c) :
_callback(NULL),
_client(&c),
_max_retries(10)
{}
PubSubClient::PubSubClient(Client& c, IPAddress &ip, uint16_t port) :
_callback(NULL),
_client(&c),
_max_retries(10),
server_ip(ip),
server_port(port)
{}
PubSubClient::PubSubClient(Client& c, String hostname, uint16_t port) :
_callback(NULL),
_client(&c),
_max_retries(10),
server_port(port),
server_hostname(hostname)
{}
PubSubClient& PubSubClient::set_server(IPAddress &ip, uint16_t port) {
server_hostname = "";
server_ip = ip;
server_port = port;
return *this;
}
PubSubClient& PubSubClient::set_server(String hostname, uint16_t port) {
server_hostname = hostname;
server_port = port;
return *this;
}
MQTT::Message* PubSubClient::_recv_message(void) {
MQTT::Message *msg = MQTT::readPacket(*_client);
if (msg != NULL)
lastInActivity = millis();
return msg;
}
bool PubSubClient::_send_message(MQTT::Message& msg) {
MQTT::message_type r_type = msg.response_type();
if (msg.need_packet_id())
msg.set_packet_id(_next_packet_id());
uint8_t retries = 0;
send:
if (!msg.send(*_client)) {
if (retries < _max_retries) {
retries++;
goto send;
}
return false;
}
lastOutActivity = millis();
if (r_type == MQTT::None)
return true;
if (!_wait_for(r_type, msg.packet_id())) {
if (retries < _max_retries) {
retries++;
goto send;
}
return false;
}
return true;
}
void PubSubClient::_process_message(MQTT::Message* msg) {
switch (msg->type()) {
case MQTT::PUBLISH:
{
MQTT::Publish *pub = static_cast<MQTT::Publish*>(msg); // RTTI is disabled on embedded, so no dynamic_cast<>()
if (_callback)
_callback(*pub);
if (pub->qos() == 1) {
MQTT::PublishAck puback(pub->packet_id());
_send_message(puback);
} else if (pub->qos() == 2) {
uint8_t retries = 0;
{
MQTT::PublishRec pubrec(pub->packet_id());
if (!_send_message(pubrec))
return;
}
{
MQTT::PublishComp pubcomp(pub->packet_id());
_send_message(pubcomp);
}
}
}
break;
case MQTT::PINGREQ:
{
MQTT::PingResp pr;
_send_message(pr);
}
break;
case MQTT::PINGRESP:
pingOutstanding = false;
}
}
bool PubSubClient::_wait_for(MQTT::message_type match_type, uint16_t match_pid) {
while (!_client->available()) {
if (millis() - lastInActivity > keepalive * 1000UL)
return false;
yield();
}
while (millis() < lastInActivity + (keepalive * 1000)) {
// Read the packet and check it
MQTT::Message *msg = _recv_message();
if (msg != NULL) {
if (msg->type() == match_type) {
uint8_t pid = msg->packet_id();
delete msg;
if (match_pid)
return pid == match_pid;
return true;
}
_process_message(msg);
delete msg;
}
yield();
}
return false;
}
bool PubSubClient::connect(String id) {
return connect(id, "", 0, false, "");
}
bool PubSubClient::connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage) {
MQTT::Connect conn(id);
if (willTopic.length())
conn.set_will(willTopic, willMessage, willQos, willRetain);
return connect(conn);
}
bool PubSubClient::connect(MQTT::Connect &conn) {
if (connected())
return false;
int result = 0;
if (server_hostname.length() > 0)
result = _client->connect(server_hostname.c_str(), server_port);
else
result = _client->connect(server_ip, server_port);
if (!result) {
_client->stop();
return false;
}
pingOutstanding = false;
nextMsgId = 1; // Init the next packet id
keepalive = conn.keepalive(); // Store the keepalive period from this connection
bool ret = _send_message(conn);
lastInActivity = lastOutActivity;
if (!ret)
_client->stop();
return ret;
}
bool PubSubClient::loop() {
if (!connected())
return false;
unsigned long t = millis();
if ((t - lastInActivity > keepalive * 1000UL) || (t - lastOutActivity > keepalive * 1000UL)) {
if (pingOutstanding) {
_client->stop();
return false;
} else {
MQTT::Ping ping;
_send_message(ping);
lastInActivity = lastOutActivity;
pingOutstanding = true;
}
}
if (_client->available()) {
// Read the packet and check it
MQTT::Message *msg = _recv_message();
if (msg != NULL) {
_process_message(msg);
delete msg;
}
}
return true;
}
bool PubSubClient::publish(String topic, String payload) {
if (!connected())
return false;
MQTT::Publish pub(topic, payload);
return publish(pub);
}
bool PubSubClient::publish(String topic, const uint8_t* payload, uint32_t plength, bool retained) {
if (!connected())
return false;
MQTT::Publish pub(topic, const_cast<uint8_t*>(payload), plength);
pub.set_retain(retained);
return publish(pub);
}
bool PubSubClient::publish_P(String topic, PGM_P payload, uint32_t plength, bool retained) {
if (!connected())
return false;
MQTT::Publish pub = MQTT::Publish_P(topic, payload, plength);
pub.set_retain(retained);
return publish(pub);
}
bool PubSubClient::publish(MQTT::Publish &pub) {
if (!connected())
return false;
switch (pub.qos()) {
case 0:
_send_message(pub);
break;
case 1:
if (!_send_message(pub))
return false;
break;
case 2:
{
if (!_send_message(pub))
return false;
MQTT::PublishRel pubrel(pub.packet_id());
if (!_send_message(pubrel))
return false;
}
break;
}
return true;
}
bool PubSubClient::subscribe(String topic, uint8_t qos) {
if (!connected())
return false;
if (qos > 2)
return false;
MQTT::Subscribe sub(topic, qos);
return subscribe(sub);
}
bool PubSubClient::subscribe(MQTT::Subscribe &sub) {
if (!connected())
return false;
if (!_send_message(sub))
return false;
return true;
}
bool PubSubClient::unsubscribe(String topic) {
if (!connected())
return false;
MQTT::Unsubscribe unsub(topic);
return unsubscribe(unsub);
}
bool PubSubClient::unsubscribe(MQTT::Unsubscribe &unsub) {
if (!connected())
return false;
if (!_send_message(unsub))
return false;
return true;
}
void PubSubClient::disconnect() {
if (!connected())
return;
MQTT::Disconnect discon;
_send_message(discon);
lastInActivity = lastOutActivity;
_client->stop();
}
bool PubSubClient::connected() {
bool rc = _client->connected();
if (!rc)
_client->stop();
return rc;
}
<commit_msg>A bunch of places where we can directly return the result from _send_message()<commit_after>/*
PubSubClient.cpp - A simple client for MQTT.
Nicholas O'Leary
http://knolleary.net
*/
#include "PubSubClient.h"
#include <string.h>
PubSubClient::PubSubClient(Client& c) :
_callback(NULL),
_client(&c),
_max_retries(10)
{}
PubSubClient::PubSubClient(Client& c, IPAddress &ip, uint16_t port) :
_callback(NULL),
_client(&c),
_max_retries(10),
server_ip(ip),
server_port(port)
{}
PubSubClient::PubSubClient(Client& c, String hostname, uint16_t port) :
_callback(NULL),
_client(&c),
_max_retries(10),
server_port(port),
server_hostname(hostname)
{}
PubSubClient& PubSubClient::set_server(IPAddress &ip, uint16_t port) {
server_hostname = "";
server_ip = ip;
server_port = port;
return *this;
}
PubSubClient& PubSubClient::set_server(String hostname, uint16_t port) {
server_hostname = hostname;
server_port = port;
return *this;
}
MQTT::Message* PubSubClient::_recv_message(void) {
MQTT::Message *msg = MQTT::readPacket(*_client);
if (msg != NULL)
lastInActivity = millis();
return msg;
}
bool PubSubClient::_send_message(MQTT::Message& msg) {
MQTT::message_type r_type = msg.response_type();
if (msg.need_packet_id())
msg.set_packet_id(_next_packet_id());
uint8_t retries = 0;
send:
if (!msg.send(*_client)) {
if (retries < _max_retries) {
retries++;
goto send;
}
return false;
}
lastOutActivity = millis();
if (r_type == MQTT::None)
return true;
if (!_wait_for(r_type, msg.packet_id())) {
if (retries < _max_retries) {
retries++;
goto send;
}
return false;
}
return true;
}
void PubSubClient::_process_message(MQTT::Message* msg) {
switch (msg->type()) {
case MQTT::PUBLISH:
{
MQTT::Publish *pub = static_cast<MQTT::Publish*>(msg); // RTTI is disabled on embedded, so no dynamic_cast<>()
if (_callback)
_callback(*pub);
if (pub->qos() == 1) {
MQTT::PublishAck puback(pub->packet_id());
_send_message(puback);
} else if (pub->qos() == 2) {
uint8_t retries = 0;
{
MQTT::PublishRec pubrec(pub->packet_id());
if (!_send_message(pubrec))
return;
}
{
MQTT::PublishComp pubcomp(pub->packet_id());
_send_message(pubcomp);
}
}
}
break;
case MQTT::PINGREQ:
{
MQTT::PingResp pr;
_send_message(pr);
}
break;
case MQTT::PINGRESP:
pingOutstanding = false;
}
}
bool PubSubClient::_wait_for(MQTT::message_type match_type, uint16_t match_pid) {
while (!_client->available()) {
if (millis() - lastInActivity > keepalive * 1000UL)
return false;
yield();
}
while (millis() < lastInActivity + (keepalive * 1000)) {
// Read the packet and check it
MQTT::Message *msg = _recv_message();
if (msg != NULL) {
if (msg->type() == match_type) {
uint8_t pid = msg->packet_id();
delete msg;
if (match_pid)
return pid == match_pid;
return true;
}
_process_message(msg);
delete msg;
}
yield();
}
return false;
}
bool PubSubClient::connect(String id) {
return connect(id, "", 0, false, "");
}
bool PubSubClient::connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage) {
MQTT::Connect conn(id);
if (willTopic.length())
conn.set_will(willTopic, willMessage, willQos, willRetain);
return connect(conn);
}
bool PubSubClient::connect(MQTT::Connect &conn) {
if (connected())
return false;
int result = 0;
if (server_hostname.length() > 0)
result = _client->connect(server_hostname.c_str(), server_port);
else
result = _client->connect(server_ip, server_port);
if (!result) {
_client->stop();
return false;
}
pingOutstanding = false;
nextMsgId = 1; // Init the next packet id
keepalive = conn.keepalive(); // Store the keepalive period from this connection
bool ret = _send_message(conn);
lastInActivity = lastOutActivity;
if (!ret)
_client->stop();
return ret;
}
bool PubSubClient::loop() {
if (!connected())
return false;
unsigned long t = millis();
if ((t - lastInActivity > keepalive * 1000UL) || (t - lastOutActivity > keepalive * 1000UL)) {
if (pingOutstanding) {
_client->stop();
return false;
} else {
MQTT::Ping ping;
_send_message(ping);
lastInActivity = lastOutActivity;
pingOutstanding = true;
}
}
if (_client->available()) {
// Read the packet and check it
MQTT::Message *msg = _recv_message();
if (msg != NULL) {
_process_message(msg);
delete msg;
}
}
return true;
}
bool PubSubClient::publish(String topic, String payload) {
if (!connected())
return false;
MQTT::Publish pub(topic, payload);
return publish(pub);
}
bool PubSubClient::publish(String topic, const uint8_t* payload, uint32_t plength, bool retained) {
if (!connected())
return false;
MQTT::Publish pub(topic, const_cast<uint8_t*>(payload), plength);
pub.set_retain(retained);
return publish(pub);
}
bool PubSubClient::publish_P(String topic, PGM_P payload, uint32_t plength, bool retained) {
if (!connected())
return false;
MQTT::Publish pub = MQTT::Publish_P(topic, payload, plength);
pub.set_retain(retained);
return publish(pub);
}
bool PubSubClient::publish(MQTT::Publish &pub) {
if (!connected())
return false;
switch (pub.qos()) {
case 0:
return _send_message(pub);
case 1:
return _send_message(pub);
case 2:
{
if (!_send_message(pub))
return false;
MQTT::PublishRel pubrel(pub.packet_id());
return _send_message(pubrel);
}
}
return false;
}
bool PubSubClient::subscribe(String topic, uint8_t qos) {
if (!connected())
return false;
if (qos > 2)
return false;
MQTT::Subscribe sub(topic, qos);
return subscribe(sub);
}
bool PubSubClient::subscribe(MQTT::Subscribe &sub) {
if (!connected())
return false;
return _send_message(sub);
}
bool PubSubClient::unsubscribe(String topic) {
if (!connected())
return false;
MQTT::Unsubscribe unsub(topic);
return unsubscribe(unsub);
}
bool PubSubClient::unsubscribe(MQTT::Unsubscribe &unsub) {
if (!connected())
return false;
return _send_message(unsub);
}
void PubSubClient::disconnect() {
if (!connected())
return;
MQTT::Disconnect discon;
_send_message(discon);
lastInActivity = lastOutActivity;
_client->stop();
}
bool PubSubClient::connected() {
bool rc = _client->connected();
if (!rc)
_client->stop();
return rc;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <FractalMath\Vector.h>
#include <FractalMath\Matrix.h>
#include "core\systems\Engine.h"
//> const, define = all upper case ex: PI, RADIUS_TO_DEGEE
//> Class = all first letter of all words upper case ex: MyClass
//> function = first letter lower case, the rest of the first letter upper case ex: void myName() {}
//> private = m_myPrivate. <-- that set up
//> public = first letter lower case, the rest of the first letter upper case ex : int myInt;
using namespace fractal;
int main(int argc, char* argv[]) {
fmath::Vector3 a(2,5,1);
fmath::Vector3 b(3, 4, 3);
fmath::Matrix4 projectionMatrix;
fmath::Matrix4 projectionMatrix = fmath::Matrix4::rotate(30, 1,0,0) * fmath::Matrix4::translate(2,4,5) * fmath::Matrix4::scale(2,2,2);
std::cout << fmath::Matrix4::rotate(30, 1, 0, 0);
std::cout << fmath::Matrix4::translate(2, 4, 5);
std::cout << fmath::Matrix4::scale(2, 2, 2);
std::cout << projectionMatrix;
projectionMatrix.print();
std::cout << " test " << a + b << std::endl;
std::cout << " test " << a.dot(b) << std::endl;
std::cout << " test " << a.cross(b) << std::endl;
std::cout << " test " << projectionMatrix * a << std::endl;
//test of sdl
/*SDL_Init(SDL_INIT_EVERYTHING);
//set it to use "two" windows making the game smoother
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
Uint32 flags = SDL_WINDOW_OPENGL;
//flags |= SDL_WINDOW_FULLSCREEN;
SDL_Window* window = SDL_CreateWindow("test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 640, flags);
SDL_GLContext glContext = SDL_GL_CreateContext(window);
glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
glewInit();
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
bool running = true;
while (running) {
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SDL_Event evnt;
while (SDL_PollEvent(&evnt)) {
switch (evnt.type) {
case SDL_QUIT:
// Exit the game here!
std::cout << "quit!" << std::endl;
running = false;
//return false; //should be removed
break;
}
}
SDL_GL_SwapWindow(window);
}
SDL_DestroyWindow(window);
SDL_Quit();
//end of sdl test
getchar();*/
fractal::fcore::Engine* engine = new fractal::fcore::Engine();
engine->run();
getchar();
return 0;
}<commit_msg>changing main<commit_after>#include <iostream>
#include <FractalMath\Vector.h>
#include <FractalMath\Matrix.h>
#include "core\systems\Engine.h"
//> const, define = all upper case ex: PI, RADIUS_TO_DEGEE
//> Class = all first letter of all words upper case ex: MyClass
//> function = first letter lower case, the rest of the first letter upper case ex: void myName() {}
//> private = m_myPrivate. <-- that set up
//> public = first letter lower case, the rest of the first letter upper case ex : int myInt;
using namespace fractal;
int main(int argc, char* argv[]) {
fmath::Vector3 a(2,5,1);
fmath::Vector3 b(3, 4, 3);
fmath::Matrix4 projectionMatrix = fmath::Matrix4::rotate(30, 1,0,0) * fmath::Matrix4::translate(2,4,5) * fmath::Matrix4::scale(2,2,2);
std::cout << fmath::Matrix4::rotate(30, 1, 0, 0);
std::cout << fmath::Matrix4::translate(2, 4, 5);
std::cout << fmath::Matrix4::scale(2, 2, 2);
std::cout << projectionMatrix;
projectionMatrix.print();
std::cout << " test " << a + b << std::endl;
std::cout << " test " << a.dot(b) << std::endl;
std::cout << " test " << a.cross(b) << std::endl;
std::cout << " test " << projectionMatrix * a << std::endl;
//test of sdl
/*SDL_Init(SDL_INIT_EVERYTHING);
//set it to use "two" windows making the game smoother
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
Uint32 flags = SDL_WINDOW_OPENGL;
//flags |= SDL_WINDOW_FULLSCREEN;
SDL_Window* window = SDL_CreateWindow("test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 640, flags);
SDL_GLContext glContext = SDL_GL_CreateContext(window);
glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
glewInit();
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
bool running = true;
while (running) {
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SDL_Event evnt;
while (SDL_PollEvent(&evnt)) {
switch (evnt.type) {
case SDL_QUIT:
// Exit the game here!
std::cout << "quit!" << std::endl;
running = false;
//return false; //should be removed
break;
}
}
SDL_GL_SwapWindow(window);
}
SDL_DestroyWindow(window);
SDL_Quit();
//end of sdl test
getchar();*/
fractal::fcore::Engine* engine = new fractal::fcore::Engine();
engine->run();
getchar();
return 0;
}<|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "GGIKitImpl.hh"
#include "VisualImpl.hh"
using namespace Fresco;
GGIKitImpl::GGIKitImpl(const std::string &id, const Fresco::Kit::PropertySeq &p)
: KitImpl(id, p) {}
GGIKitImpl::~GGIKitImpl() {}
GGI::Visual_ptr GGIKitImpl::create_visual(Fresco::PixelCoord w, Fresco::PixelCoord h)
{
VisualImpl *visual = new VisualImpl(w, h);
activate(visual);
return visual->_this();
}
extern "C" KitImpl *load()
{
static std::string properties[] = {"implementation", "GGIKitImpl"};
return create_kit<GGIKitImpl>("IDL:GGI/GGIKit:1.0", properties, 2);
}
<commit_msg>Forgot this Kit with my last commit:-) Actually belongs to the commit with this message:<commit_after>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "GGIKitImpl.hh"
#include "VisualImpl.hh"
using namespace Fresco;
GGIKitImpl::GGIKitImpl(const std::string &id, const Fresco::Kit::PropertySeq &p)
: KitImpl(id, p) {}
GGIKitImpl::~GGIKitImpl() {}
GGI::Visual_ptr GGIKitImpl::create_visual(Fresco::PixelCoord w, Fresco::PixelCoord h)
{
return create<Visual>(new VisualImpl(w, h));
}
extern "C" KitImpl *load()
{
static std::string properties[] = {"implementation", "GGIKitImpl"};
return create_kit<GGIKitImpl>("IDL:GGI/GGIKit:1.0", properties, 2);
}
<|endoftext|> |
<commit_before>//
// Shader.cpp
// ModelViewer
//
// Created by Mattias Bergström on 2014-01-30.
// Copyright (c) 2014 Mattias Bergström. All rights reserved.
//
#include "Shader.h"
#include "glm/gtc/matrix_inverse.hpp"
#include <GLFW/glfw3.h>
#include <math.h>
#include "Constants.h"
#include "Mesh.h"
#include <iostream>
Shader::Shader() {
// Setup default values
this->programId = 0;
this->materialBuffer = GL_INVALID_VALUE;
}
Shader::~Shader() {
glDeleteProgram(programId);
}
void Shader::use() {
if(programId == 0) {
throw "Shader not initialized, run init before calling use";
}
glUseProgram(this->programId);
}
void Shader::setUniforms(glm::mat4& proj, glm::mat4& view, glm::mat4& model) {
GLint projId = glGetUniformLocation(this->programId, "proj");
GLint viewId = glGetUniformLocation(this->programId, "view");
GLint modelId = glGetUniformLocation(this->programId, "model");
GLint mvpId = glGetUniformLocation(this->programId, "mvp");
GLint normalMatrixId = glGetUniformLocation(this->programId, "normal_matrix");
GLint inverseProjId = glGetUniformLocation(this->programId, "inverse_proj");
GLint inverseViewId = glGetUniformLocation(this->programId, "inverse_view");
GLint nearZId = glGetUniformLocation(this->programId, "nearZ");
GLint farZId = glGetUniformLocation(this->programId, "farZ");
glm::mat3 normalMatrix = glm::inverseTranspose(glm::mat3(view * model));
glm::mat4 inverseProj = glm::inverse(proj);
glm::mat4 inverseView = glm::inverse(view);
glUniformMatrix4fv(projId, 1, GL_FALSE, glm::value_ptr(proj));
glUniformMatrix4fv(viewId, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(modelId, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(mvpId, 1, GL_FALSE, glm::value_ptr(proj * view * model));
glUniformMatrix3fv(normalMatrixId, 1, GL_FALSE, glm::value_ptr(normalMatrix));
glUniformMatrix4fv(inverseProjId, 1, GL_FALSE, glm::value_ptr(inverseProj));
glUniformMatrix4fv(inverseViewId, 1, GL_FALSE, glm::value_ptr(inverseView));
glUniform1f(nearZId, 0.1f);
glUniform1f(farZId, 100.0f);
glBindBufferBase(GL_UNIFORM_BUFFER, Shader::MATERIAL, materialBuffer);
glBindBufferBase(GL_UNIFORM_BUFFER, Shader::LIGHT, lightBuffer);
}
void Shader::setupBufferBindings() {
GLuint bindingPoint = Shader::MATERIAL;
GLuint blockIndex;
blockIndex = glGetUniformBlockIndex(programId, "Material");
if(blockIndex != GL_INVALID_INDEX) {
glUniformBlockBinding(programId, blockIndex, bindingPoint);
glGenBuffers(1, &materialBuffer);
glBindBuffer(GL_UNIFORM_BUFFER, materialBuffer);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, materialBuffer);
}
bindingPoint = Shader::LIGHT;
blockIndex = glGetUniformBlockIndex(programId, "Light");
if(blockIndex != GL_INVALID_INDEX) {
glUniformBlockBinding(programId, blockIndex, bindingPoint);
glGenBuffers(1, &lightBuffer);
glBindBuffer(GL_UNIFORM_BUFFER, lightBuffer);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, lightBuffer);
}
}<commit_msg>Removed unnecessary lines<commit_after>//
// Shader.cpp
// ModelViewer
//
// Created by Mattias Bergström on 2014-01-30.
// Copyright (c) 2014 Mattias Bergström. All rights reserved.
//
#include "Shader.h"
#include "glm/gtc/matrix_inverse.hpp"
#include <GLFW/glfw3.h>
#include <math.h>
#include "Constants.h"
#include "Mesh.h"
#include <iostream>
Shader::Shader() {
// Setup default values
this->programId = 0;
this->materialBuffer = GL_INVALID_VALUE;
}
Shader::~Shader() {
glDeleteProgram(programId);
}
void Shader::use() {
if(programId == 0) {
throw "Shader not initialized, run init before calling use";
}
glUseProgram(this->programId);
}
void Shader::setUniforms(glm::mat4& proj, glm::mat4& view, glm::mat4& model) {
GLint projId = glGetUniformLocation(this->programId, "proj");
GLint viewId = glGetUniformLocation(this->programId, "view");
GLint modelId = glGetUniformLocation(this->programId, "model");
GLint mvpId = glGetUniformLocation(this->programId, "mvp");
GLint normalMatrixId = glGetUniformLocation(this->programId, "normal_matrix");
GLint inverseProjId = glGetUniformLocation(this->programId, "inverse_proj");
GLint inverseViewId = glGetUniformLocation(this->programId, "inverse_view");
GLint nearZId = glGetUniformLocation(this->programId, "nearZ");
GLint farZId = glGetUniformLocation(this->programId, "farZ");
glm::mat3 normalMatrix = glm::inverseTranspose(glm::mat3(view * model));
glm::mat4 inverseProj = glm::inverse(proj);
glm::mat4 inverseView = glm::inverse(view);
glUniformMatrix4fv(projId, 1, GL_FALSE, glm::value_ptr(proj));
glUniformMatrix4fv(viewId, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(modelId, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(mvpId, 1, GL_FALSE, glm::value_ptr(proj * view * model));
glUniformMatrix3fv(normalMatrixId, 1, GL_FALSE, glm::value_ptr(normalMatrix));
glUniformMatrix4fv(inverseProjId, 1, GL_FALSE, glm::value_ptr(inverseProj));
glUniformMatrix4fv(inverseViewId, 1, GL_FALSE, glm::value_ptr(inverseView));
glUniform1f(nearZId, 0.1f);
glUniform1f(farZId, 100.0f);
}
void Shader::setupBufferBindings() {
GLuint bindingPoint = Shader::MATERIAL;
GLuint blockIndex;
blockIndex = glGetUniformBlockIndex(programId, "Material");
if(blockIndex != GL_INVALID_INDEX) {
glUniformBlockBinding(programId, blockIndex, bindingPoint);
glGenBuffers(1, &materialBuffer);
glBindBuffer(GL_UNIFORM_BUFFER, materialBuffer);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, materialBuffer);
}
bindingPoint = Shader::LIGHT;
blockIndex = glGetUniformBlockIndex(programId, "Light");
if(blockIndex != GL_INVALID_INDEX) {
glUniformBlockBinding(programId, blockIndex, bindingPoint);
glGenBuffers(1, &lightBuffer);
glBindBuffer(GL_UNIFORM_BUFFER, lightBuffer);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, lightBuffer);
}
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: ContourF.cc
Language: C++
Date: 02/07/94
Version: 1.4
Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkContourFilter.h"
#include "vtkFloatScalars.h"
#include "vtkCell.h"
#include "vtkMergePoints.h"
#include "vtkMarchingSquares.h"
#include "vtkMarchingCubes.h"
// Description:
// Construct object with initial range (0,1) and single contour value
// of 0.0.
vtkContourFilter::vtkContourFilter()
{
for (int i=0; i<VTK_MAX_CONTOURS; i++) this->Values[i] = 0.0;
this->NumberOfContours = 1;
this->Range[0] = 0.0;
this->Range[1] = 1.0;
this->ComputeNormals = 1;
this->ComputeGradients = 0;
this->ComputeScalars = 1;
this->Locator = NULL;
this->SelfCreatedLocator = 0;
}
// Description:
// Set a particular contour value at contour number i. The index i ranges
// between 0<=i<NumberOfContours.
void vtkContourFilter::SetValue(int i, float value)
{
i = (i >= VTK_MAX_CONTOURS ? VTK_MAX_CONTOURS-1 : (i < 0 ? 0 : i) );
if ( this->Values[i] != value )
{
this->Modified();
this->Values[i] = value;
if ( i >= this->NumberOfContours ) this->NumberOfContours = i + 1;
if ( value < this->Range[0] ) this->Range[0] = value;
if ( value > this->Range[1] ) this->Range[1] = value;
}
}
void vtkContourFilter::GenerateValues(int numContours, float range1,
float range2)
{
float rng[2];
rng[0] = range1;
rng[1] = range2;
this->GenerateValues(numContours,rng);
}
// Description:
// Generate numContours equally spaced contour values between specified
// range. Contour values will include min/max range values.
void vtkContourFilter::GenerateValues(int numContours, float range[2])
{
float val, incr;
int i;
numContours = (numContours >= VTK_MAX_CONTOURS ? VTK_MAX_CONTOURS-1 :
(numContours > 1 ? numContours : 2) );
incr = (range[1] - range[0]) / (numContours-1);
for (i=0, val=range[0]; i < numContours; i++, val+=incr)
{
this->SetValue(i,val);
}
this->NumberOfContours = numContours;
}
//
// General contouring filter. Handles arbitrary input.
//
void vtkContourFilter::Execute()
{
int cellId, i;
vtkIdList *cellPts;
vtkScalars *inScalars;
vtkFloatScalars cellScalars(VTK_CELL_SIZE);
vtkCell *cell;
float range[2];
vtkCellArray *newVerts, *newLines, *newPolys;
vtkFloatPoints *newPts;
cellScalars.ReferenceCountingOff();
vtkPolyData *output = this->GetOutput();
int numCells, estimatedSize, numScalars;
vtkPointData *inPd, *outPd;
vtkDebugMacro(<< "Executing contour filter");
numCells = this->Input->GetNumberOfCells();
inScalars = this->Input->GetPointData()->GetScalars();
if ( ! inScalars || numCells < 1 )
{
vtkErrorMacro(<<"No data to contour");
return;
}
// If structured points, use more efficient algorithms
if ( ! strcmp(this->Input->GetDataType(),"vtkStructuredPoints") )
{
int dim = this->Input->GetCell(0)->GetCellDimension();
if ( this->Input->GetCell(0)->GetCellDimension() >= 2 )
{
this->StructuredPointsContour(dim);
return;
}
}
inScalars->GetRange(range);
//
// Create objects to hold output of contour operation. First estimate allocation size.
//
estimatedSize = (int) pow ((double) numCells, .75);
estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024
if (estimatedSize < 1024) estimatedSize = 1024;
newPts = new vtkFloatPoints(estimatedSize,estimatedSize);
newVerts = new vtkCellArray(estimatedSize,estimatedSize);
newLines = new vtkCellArray(estimatedSize,estimatedSize);
newPolys = new vtkCellArray(estimatedSize,estimatedSize);
// locator used to merge potentially duplicate points
if ( this->Locator == NULL ) this->CreateDefaultLocator();
this->Locator->InitPointInsertion (newPts, this->Input->GetBounds());
// interpolate data along edge
inPd = this->Input->GetPointData();
outPd = output->GetPointData();
outPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize);
//
// Loop over all contour values. Then for each contour value,
// loop over all cells.
//
for (cellId=0; cellId < numCells; cellId++)
{
cell = Input->GetCell(cellId);
cellPts = cell->GetPointIds();
inScalars->GetScalars(*cellPts,cellScalars);
for (i=0; i < this->NumberOfContours; i++)
{
cell->Contour(this->Values[i], &cellScalars, this->Locator,
newVerts, newLines, newPolys, inPd, outPd);
} // for all contour values
} // for all cells
vtkDebugMacro(<<"Created: "
<< newPts->GetNumberOfPoints() << " points, "
<< newVerts->GetNumberOfCells() << " verts, "
<< newLines->GetNumberOfCells() << " lines, "
<< newPolys->GetNumberOfCells() << " triangles");
//
// Update ourselves. Because we don't know up front how many verts, lines,
// polys we've created, take care to reclaim memory.
//
output->SetPoints(newPts);
newPts->Delete();
if (newVerts->GetNumberOfCells()) output->SetVerts(newVerts);
newVerts->Delete();
if (newLines->GetNumberOfCells()) output->SetLines(newLines);
newLines->Delete();
if (newPolys->GetNumberOfCells()) output->SetPolys(newPolys);
newPolys->Delete();
this->Locator->Initialize();//releases leftover memory
output->Squeeze();
}
//
// Special method handles structured points
//
void vtkContourFilter::StructuredPointsContour(int dim)
{
vtkPolyData *output;
vtkPolyData *thisOutput = (vtkPolyData *)this->Output;
int i;
if ( dim == 2 ) //marching squares
{
static vtkMarchingSquares msquares;
msquares.SetInput((vtkStructuredPoints *)this->Input);
msquares.SetDebug(this->Debug);
msquares.SetNumberOfContours(this->NumberOfContours);
for (i=0; i < this->NumberOfContours; i++)
msquares.SetValue(i,this->Values[i]);
msquares.Update();
output = msquares.GetOutput();
}
else //marching cubes
{
static vtkMarchingCubes mcubes;
mcubes.SetInput((vtkStructuredPoints *)this->Input);
mcubes.SetComputeNormals (this->ComputeNormals);
mcubes.SetComputeGradients (this->ComputeGradients);
mcubes.SetComputeScalars (this->ComputeScalars);
mcubes.SetDebug(this->Debug);
mcubes.SetNumberOfContours(this->NumberOfContours);
for (i=0; i < this->NumberOfContours; i++)
mcubes.SetValue(i,this->Values[i]);
mcubes.Update();
output = mcubes.GetOutput();
}
thisOutput->CopyStructure(output);
*thisOutput->GetPointData() = *output->GetPointData();
output->Initialize();
}
// Description:
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkContourFilter::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator != locator )
{
if ( this->SelfCreatedLocator ) this->Locator->Delete();
this->SelfCreatedLocator = 0;
this->Locator = locator;
this->Modified();
}
}
void vtkContourFilter::CreateDefaultLocator()
{
if ( this->SelfCreatedLocator ) this->Locator->Delete();
this->Locator = new vtkMergePoints;
this->SelfCreatedLocator = 1;
}
void vtkContourFilter::PrintSelf(ostream& os, vtkIndent indent)
{
int i;
vtkDataSetToPolyFilter::PrintSelf(os,indent);
os << indent << "Number Of Contours : " << this->NumberOfContours << "\n";
os << indent << "Contour Values: \n";
for ( i=0; i<this->NumberOfContours; i++)
{
os << indent << " Value " << i << ": " << this->Values[i] << "\n";
}
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
<commit_msg>ERR: Removed unused variable<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: ContourF.cc
Language: C++
Date: 02/07/94
Version: 1.4
Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkContourFilter.h"
#include "vtkFloatScalars.h"
#include "vtkCell.h"
#include "vtkMergePoints.h"
#include "vtkMarchingSquares.h"
#include "vtkMarchingCubes.h"
// Description:
// Construct object with initial range (0,1) and single contour value
// of 0.0.
vtkContourFilter::vtkContourFilter()
{
for (int i=0; i<VTK_MAX_CONTOURS; i++) this->Values[i] = 0.0;
this->NumberOfContours = 1;
this->Range[0] = 0.0;
this->Range[1] = 1.0;
this->ComputeNormals = 1;
this->ComputeGradients = 0;
this->ComputeScalars = 1;
this->Locator = NULL;
this->SelfCreatedLocator = 0;
}
// Description:
// Set a particular contour value at contour number i. The index i ranges
// between 0<=i<NumberOfContours.
void vtkContourFilter::SetValue(int i, float value)
{
i = (i >= VTK_MAX_CONTOURS ? VTK_MAX_CONTOURS-1 : (i < 0 ? 0 : i) );
if ( this->Values[i] != value )
{
this->Modified();
this->Values[i] = value;
if ( i >= this->NumberOfContours ) this->NumberOfContours = i + 1;
if ( value < this->Range[0] ) this->Range[0] = value;
if ( value > this->Range[1] ) this->Range[1] = value;
}
}
void vtkContourFilter::GenerateValues(int numContours, float range1,
float range2)
{
float rng[2];
rng[0] = range1;
rng[1] = range2;
this->GenerateValues(numContours,rng);
}
// Description:
// Generate numContours equally spaced contour values between specified
// range. Contour values will include min/max range values.
void vtkContourFilter::GenerateValues(int numContours, float range[2])
{
float val, incr;
int i;
numContours = (numContours >= VTK_MAX_CONTOURS ? VTK_MAX_CONTOURS-1 :
(numContours > 1 ? numContours : 2) );
incr = (range[1] - range[0]) / (numContours-1);
for (i=0, val=range[0]; i < numContours; i++, val+=incr)
{
this->SetValue(i,val);
}
this->NumberOfContours = numContours;
}
//
// General contouring filter. Handles arbitrary input.
//
void vtkContourFilter::Execute()
{
int cellId, i;
vtkIdList *cellPts;
vtkScalars *inScalars;
vtkFloatScalars cellScalars(VTK_CELL_SIZE);
vtkCell *cell;
float range[2];
vtkCellArray *newVerts, *newLines, *newPolys;
vtkFloatPoints *newPts;
cellScalars.ReferenceCountingOff();
vtkPolyData *output = this->GetOutput();
int numCells, estimatedSize;
vtkPointData *inPd, *outPd;
vtkDebugMacro(<< "Executing contour filter");
numCells = this->Input->GetNumberOfCells();
inScalars = this->Input->GetPointData()->GetScalars();
if ( ! inScalars || numCells < 1 )
{
vtkErrorMacro(<<"No data to contour");
return;
}
// If structured points, use more efficient algorithms
if ( ! strcmp(this->Input->GetDataType(),"vtkStructuredPoints") )
{
int dim = this->Input->GetCell(0)->GetCellDimension();
if ( this->Input->GetCell(0)->GetCellDimension() >= 2 )
{
this->StructuredPointsContour(dim);
return;
}
}
inScalars->GetRange(range);
//
// Create objects to hold output of contour operation. First estimate allocation size.
//
estimatedSize = (int) pow ((double) numCells, .75);
estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024
if (estimatedSize < 1024) estimatedSize = 1024;
newPts = new vtkFloatPoints(estimatedSize,estimatedSize);
newVerts = new vtkCellArray(estimatedSize,estimatedSize);
newLines = new vtkCellArray(estimatedSize,estimatedSize);
newPolys = new vtkCellArray(estimatedSize,estimatedSize);
// locator used to merge potentially duplicate points
if ( this->Locator == NULL ) this->CreateDefaultLocator();
this->Locator->InitPointInsertion (newPts, this->Input->GetBounds());
// interpolate data along edge
inPd = this->Input->GetPointData();
outPd = output->GetPointData();
outPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize);
//
// Loop over all contour values. Then for each contour value,
// loop over all cells.
//
for (cellId=0; cellId < numCells; cellId++)
{
cell = Input->GetCell(cellId);
cellPts = cell->GetPointIds();
inScalars->GetScalars(*cellPts,cellScalars);
for (i=0; i < this->NumberOfContours; i++)
{
cell->Contour(this->Values[i], &cellScalars, this->Locator,
newVerts, newLines, newPolys, inPd, outPd);
} // for all contour values
} // for all cells
vtkDebugMacro(<<"Created: "
<< newPts->GetNumberOfPoints() << " points, "
<< newVerts->GetNumberOfCells() << " verts, "
<< newLines->GetNumberOfCells() << " lines, "
<< newPolys->GetNumberOfCells() << " triangles");
//
// Update ourselves. Because we don't know up front how many verts, lines,
// polys we've created, take care to reclaim memory.
//
output->SetPoints(newPts);
newPts->Delete();
if (newVerts->GetNumberOfCells()) output->SetVerts(newVerts);
newVerts->Delete();
if (newLines->GetNumberOfCells()) output->SetLines(newLines);
newLines->Delete();
if (newPolys->GetNumberOfCells()) output->SetPolys(newPolys);
newPolys->Delete();
this->Locator->Initialize();//releases leftover memory
output->Squeeze();
}
//
// Special method handles structured points
//
void vtkContourFilter::StructuredPointsContour(int dim)
{
vtkPolyData *output;
vtkPolyData *thisOutput = (vtkPolyData *)this->Output;
int i;
if ( dim == 2 ) //marching squares
{
static vtkMarchingSquares msquares;
msquares.SetInput((vtkStructuredPoints *)this->Input);
msquares.SetDebug(this->Debug);
msquares.SetNumberOfContours(this->NumberOfContours);
for (i=0; i < this->NumberOfContours; i++)
msquares.SetValue(i,this->Values[i]);
msquares.Update();
output = msquares.GetOutput();
}
else //marching cubes
{
static vtkMarchingCubes mcubes;
mcubes.SetInput((vtkStructuredPoints *)this->Input);
mcubes.SetComputeNormals (this->ComputeNormals);
mcubes.SetComputeGradients (this->ComputeGradients);
mcubes.SetComputeScalars (this->ComputeScalars);
mcubes.SetDebug(this->Debug);
mcubes.SetNumberOfContours(this->NumberOfContours);
for (i=0; i < this->NumberOfContours; i++)
mcubes.SetValue(i,this->Values[i]);
mcubes.Update();
output = mcubes.GetOutput();
}
thisOutput->CopyStructure(output);
*thisOutput->GetPointData() = *output->GetPointData();
output->Initialize();
}
// Description:
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkContourFilter::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator != locator )
{
if ( this->SelfCreatedLocator ) this->Locator->Delete();
this->SelfCreatedLocator = 0;
this->Locator = locator;
this->Modified();
}
}
void vtkContourFilter::CreateDefaultLocator()
{
if ( this->SelfCreatedLocator ) this->Locator->Delete();
this->Locator = new vtkMergePoints;
this->SelfCreatedLocator = 1;
}
void vtkContourFilter::PrintSelf(ostream& os, vtkIndent indent)
{
int i;
vtkDataSetToPolyFilter::PrintSelf(os,indent);
os << indent << "Number Of Contours : " << this->NumberOfContours << "\n";
os << indent << "Contour Values: \n";
for ( i=0; i<this->NumberOfContours; i++)
{
os << indent << " Value " << i << ": " << this->Values[i] << "\n";
}
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
<|endoftext|> |
<commit_before>/*
* Part of tivars_lib_cpp
* (C) 2015-2017 Adrien 'Adriweb' Bertrand
* https://github.com/adriweb/tivars_lib_cpp
* License: MIT
*/
#include <assert.h>
#include "src/autoloader.h"
#include "src/TIModels.h"
#include "src/TIVarTypes.h"
#include "src/BinaryFile.h"
#include "src/TIVarFile.h"
#include "src/TypeHandlers/TypeHandlers.h"
#include "src/utils.h"
using namespace std;
using namespace tivars;
int main(int argc, char** argv)
{
(void)argc;
(void)argv;
/* Init Stuff */
TIModels::initTIModelsArray();
TIVarTypes::initTIVarTypesArray();
TH_0x05::initTokens();
using tivars::TH_0x05::LANG_FR;
using tivars::TH_0x05::LANG_EN;
/* Tests */
assert(TIVarTypes::getIDFromName("ExactRealPi") == 32);
TIVarFile toksPrgm = TIVarFile::loadFromFile("testData/ALLTOKS.8Xp");
cout << toksPrgm.getReadableContent() << "\n" << endl;
TIVarFile testAppVar = TIVarFile::createNew(TIVarType::createFromName("AppVar"), "TEST");
testAppVar.setContentFromString("ABCD1234C9C8C7C6"); // random but valid hex string
assert(testAppVar.getReadableContent() == "ABCD1234C9C8C7C6");
assert(testAppVar.getRawContent().size() == strlen("ABCD1234C9C8C7C6") / 2 + 2);
testAppVar.saveVarToFile("testData", "testAVnew");
TIVarFile testString = TIVarFile::loadFromFile("testData/String.8xs");
assert(testString.getReadableContent() == "Hello World");
TIVarFile testPrgmQuotes = TIVarFile::loadFromFile("testData/testPrgmQuotes.8xp");
cout << "testPrgmQuotes.getReadableContent() : " << testPrgmQuotes.getReadableContent() << endl;
assert(testPrgmQuotes.getReadableContent() == "Pause \"2 SECS\",2");
TIVarFile testEquation = TIVarFile::loadFromFile("testData/Equation_Y1T.8xy");
assert(testEquation.getReadableContent() == "3sin(T)+4");
TIVarFile testReal = TIVarFile::loadFromFile("testData/Real.8xn");
assert(testReal.getReadableContent() == "-42.1337");
testReal.setContentFromString(".5");
cout << "testReal.getReadableContent() : " << testReal.getReadableContent() << endl;
assert(testReal.getReadableContent() == "0.5");
TIVarFile testReal42 = TIVarFile::createNew(TIVarType::createFromName("Real"), "R");
testReal42.setCalcModel(TIModel::createFromName("84+"));
testReal42.setContentFromString("9001.42");
cout << "testReal42.getReadableContent() : " << testReal42.getReadableContent() << endl;
assert(testReal42.getReadableContent() == "9001.42");
testReal42.setContentFromString("-0.00000008");
cout << "testReal42.getReadableContent() : " << testReal42.getReadableContent() << endl;
assert(atof(testReal42.getReadableContent().c_str()) == -8e-08);
testReal42.saveVarToFile("testData", "Real_new");
string test = "Disp 42:Wait 5:toString(42):Pause\nInput A,\"?\":Asdf(123)\nFor(I,1,10)\nThen\nDisp I:For(J,1,10)\nThen\nDisp J\nEnd\nEnd";
cout << "Indented code:" << endl << TH_0x05::reindentCodeString(test) << endl;
TIVarFile testPrgmReindent = TIVarFile::createNew(TIVarType::createFromName("Program"), "asdf");
testPrgmReindent.setContentFromString("\"http://TIPlanet.org");
assert(trim(testPrgmReindent.getReadableContent({ {"prettify", true}, {"reindent", true} })) == "\"http://TIPlanet.org");
#ifndef __EMSCRIPTEN__
try
{
auto goodTypeForCalc = TIVarFile::createNew(TIVarType::createFromName("Program"), "Bla", TIModel::createFromName("83PCE"));
} catch (runtime_error& e) {
cout << "Caught unexpected exception: " << e.what() << endl;
}
try
{
auto badTypeForCalc = TIVarFile::createNew(TIVarType::createFromName("ExactComplexFrac"), "Bla", TIModel::createFromName("84+"));
} catch (runtime_error& e) {
cout << "Caught expected exception: " << e.what() << endl;
}
#endif
assert(TIVarTypes::getIDFromName("ExactRealPi") == 32);
TIVarFile testPrgm = TIVarFile::loadFromFile("testData/Program.8xp");
cout << "testPrgm.getHeader().entries_len = " << testPrgm.getHeader().entries_len << "\t testPrgm.size() - 57 == " << (testPrgm.size() - 57) << endl;
assert(testPrgm.getHeader().entries_len == testPrgm.size() - 57);
string testPrgmcontent = testPrgm.getReadableContent({{"lang", LANG_FR}});
TIVarFile newPrgm = TIVarFile::createNew(TIVarType::createFromName("Program"));
newPrgm.setContentFromString(testPrgmcontent);
string newPrgmcontent = newPrgm.getReadableContent({{"lang", LANG_FR}});
assert(testPrgmcontent == newPrgmcontent);
newPrgm.saveVarToFile("testData", "Program_new");
cout << endl << "testPrgmcontent : " << endl << testPrgmcontent << endl;
cout << "\n\n\n" << endl;
TIVarFile testPrgm42 = TIVarFile::createNew(TIVarType::createFromName("Program"), "asdf");
testPrgm42.setCalcModel(TIModel::createFromName("82A"));
testPrgm42.setContentFromString("Grande blabla:Disp \"Grande blabla");
testPrgm42.setVarName("Toto");
assert(testPrgm42.getReadableContent() == "Grande blabla:Disp \"Grande blabla");
testPrgm42.saveVarToFile("testData", "testMinTok_new");
testPrgm42.setArchived(true);
testPrgm42.saveVarToFile("testData", "testMinTok_archived_new");
testPrgm = TIVarFile::createNew(TIVarType::createFromName("Program"), "asdf");
testPrgm.setContentFromString("Pause 42:Pause 43:Disp \"\",\"Bouh la =/*: déf\",\"suite :\",\" OK");
testPrgmcontent = testPrgm.getReadableContent({ {"prettify", true}, {"reindent", true} });
assert(trim(testPrgmcontent) == "Pause 42\nPause 43\nDisp \"\",\"Bouh la =/*: déf\",\"suite :\",\" OK");
TIVarFile testRealList = TIVarFile::loadFromFile("testData/RealList.8xl");
cout << "Before: " << testRealList.getReadableContent() << "\n Now: ";
testRealList.setContentFromString("{9, 0, .5, -6e-8}");
cout << testRealList.getReadableContent() << "\n";
testRealList.saveVarToFile("testData", "RealList_new");
TIVarFile testStandardMatrix = TIVarFile::loadFromFile("testData/Matrix_3x3_standard.8xm");
cout << "Before: " << testStandardMatrix.getReadableContent() << "\n Now: ";
testStandardMatrix.setContentFromString("[[1,2,3][4,5,6][-7,-8,-9]]");
testStandardMatrix.setContentFromString("[[1,2,3][4,5,6][-7.5,-8,-9][1,2,3][4,5,6][-0.002,-8,-9]]");
cout << testStandardMatrix.getReadableContent() << "\n";
testStandardMatrix.saveVarToFile("testData", "Matrix_new");
TIVarFile testComplex = TIVarFile::loadFromFile("testData/Complex.8xc"); // -5 + 2i
cout << "Before: " << testComplex.getReadableContent() << "\n Now: ";
assert(testComplex.getReadableContent() == "-5+2i");
TIVarFile newComplex = TIVarFile::createNew(TIVarType::createFromName("Complex"), "C");
newComplex.setContentFromString("-5+2i");
assert(newComplex.getRawContent() == newComplex.getRawContent());
newComplex.setContentFromString("2.5+0.001i");
cout << "After: " << newComplex.getReadableContent() << endl;
testComplex.saveVarToFile("testData", "Complex_new");
TIVarFile testComplexList = TIVarFile::loadFromFile("testData/ComplexList.8xl");
cout << "Before: " << testComplexList.getReadableContent() << "\n Now: ";
testComplexList.setContentFromString("{9+2i, 0i, .5, -0.5+6e-8i}");
cout << testComplexList.getReadableContent() << "\n";
testComplexList.saveVarToFile("testData", "ComplexList_new");
TIVarFile testExact_RealRadical = TIVarFile::loadFromFile("testData/Exact_RealRadical.8xn");
cout << "Before: " << testExact_RealRadical.getReadableContent() << endl;
assert(testExact_RealRadical.getReadableContent() == "(41*√(789)+14*√(654))/259");
TIVarFile newExact_RealRadical = TIVarFile::createNew(TIVarType::createFromName("ExactRealRadical"), "A", TIModel::createFromName("83PCE"));
//newExact_RealRadical.setContentFromString("-42.1337");
//assert(testExact_RealRadical.getRawContent() == newExact_RealRadical.getRawContent());
//newExact_RealRadical.saveVarToFile("testData", "Exact_RealRadical_new");
TIVarFile testExactComplexFrac = TIVarFile::loadFromFile("testData/Exact_ComplexFrac.8xc");
cout << "Before: " << testExactComplexFrac.getReadableContent() << endl;
assert(testExactComplexFrac.getReadableContent() == "1/5-2/5i");
TIVarFile newExactComplexFrac = TIVarFile::createNew(TIVarType::createFromName("ExactComplexFrac"), "A", TIModel::createFromName("83PCE"));
//newExactComplexFrac.setContentFromString("-42.1337");
//assert(testExactComplexFrac.getRawContent() == newExactComplexFrac.getRawContent());
//newExactComplexFrac.saveVarToFile("testData", "Exact_ComplexFrac_new");
TIVarFile testExactComplexPi = TIVarFile::loadFromFile("testData/Exact_ComplexPi.8xc");
cout << "Before: " << testExactComplexPi.getReadableContent() << endl;
assert(testExactComplexPi.getReadableContent() == "1/5-3*π*i");
TIVarFile newExactComplexPi = TIVarFile::createNew(TIVarType::createFromName("ExactComplexPi"), "A", TIModel::createFromName("83PCE"));
//newExactComplexPi.setContentFromString("-42.1337");
//assert(testExactComplexPi.getRawContent() == newExactComplexPi.getRawContent());
//newExactComplexPi.saveVarToFile("testData", "Exact_ComplexPi_new");
TIVarFile testExactComplexPiFrac = TIVarFile::loadFromFile("testData/Exact_ComplexPiFrac.8xc");
cout << "Before: " << testExactComplexPiFrac.getReadableContent() << endl;
assert(testExactComplexPiFrac.getReadableContent() == "2/7*π*i");
TIVarFile newExactComplexPiFrac = TIVarFile::createNew(TIVarType::createFromName("ExactComplexPiFrac"), "A", TIModel::createFromName("83PCE"));
//newExactComplexPiFrac.setContentFromString("-42.1337");
//assert(testExactComplexPiFrac.getRawContent() == newExactComplexPiFrac.getRawContent());
//newExactComplexPiFrac.saveVarToFile("testData", "Exact_ComplexPiFrac_new");
TIVarFile testExactComplexRadical = TIVarFile::loadFromFile("testData/Exact_ComplexRadical.8xc");
cout << "Before: " << testExactComplexRadical.getReadableContent() << endl;
assert(testExactComplexRadical.getReadableContent() == "((√(6)+√(2))/4)+((√(6)-√(2))/4)*i");
TIVarFile newExactComplexRadical = TIVarFile::createNew(TIVarType::createFromName("ExactComplexRadical"), "A", TIModel::createFromName("83PCE"));
//newExactComplexRadical.setContentFromString("-42.1337");
//assert(testExactComplexRadical.getRawContent() == newExactComplexRadical.getRawContent());
//newExactComplexRadical.saveVarToFile("testData", "Exact_ComplexRadical_new");
TIVarFile testExactRealPi = TIVarFile::loadFromFile("testData/Exact_RealPi.8xn");
cout << "Before: " << testExactRealPi.getReadableContent() << endl;
assert(testExactRealPi.getReadableContent() == "30*π");
TIVarFile newExactRealPi = TIVarFile::createNew(TIVarType::createFromName("ExactRealPi"), "A", TIModel::createFromName("83PCE"));
//newExactRealPi.setContentFromString("-42.1337");
//assert(testExactRealPi.getRawContent() == newExactRealPi.getRawContent());
//newExactRealPi.saveVarToFile("testData", "Exact_RealPi_new");
TIVarFile testExactRealPiFrac = TIVarFile::loadFromFile("testData/Exact_RealPiFrac.8xn");
cout << "Before: " << testExactRealPiFrac.getReadableContent() << endl;
assert(testExactRealPiFrac.getReadableContent() == "2/7*π");
TIVarFile newExactRealPiFrac = TIVarFile::createNew(TIVarType::createFromName("ExactRealPiFrac"), "A", TIModel::createFromName("83PCE"));
//newExactRealPiFrac.setContentFromString("-42.1337");
//assert(testExactRealPiFrac.getRawContent() == newExactRealPiFrac.getRawContent());
//newExactRealPiFrac.saveVarToFile("testData", "Exact_RealPiFrac_new");
return 0;
}
/*
$testPrgm = TIVarFile::loadFromFile('testData/ProtectedProgram_long.8xp');
$testPrgmcontent = $testPrgm->getReadableContent(['prettify' => true, 'reindent' => true]);
echo "All prettified and reindented:\n" . $testPrgmcontent . "\n";
$testPrgm = TIVarFile::loadFromFile('testData/Program.8xp');
$newPrgm = TIVarFile::createNew(TIVarType::createFromName("Program"));
$newPrgm->setContentFromString($testPrgm->getReadableContent(['lang' => 'en']));
assert($testPrgm->getRawContent() === $newPrgm->getRawContent());
$testExactRealFrac = TIVarFile::loadFromFile('testData/Exact_RealFrac.8xn');
//echo "Before: " . $testExactRealFrac->getReadableContent() . "\t" . "Now: ";
$testExactRealFrac->setContentFromString("0.2");
//echo $testExactRealFrac->getReadableContent() . "\n";
//$testExactRealFrac->saveVarToFile();
//$testMatrixStandard = TIVarFile::loadFromFile('testData/Matrix_3x3_standard.8xm');
//print_r($testMatrixStandard);
//echo "Before: " . $testExactRealFrac->getReadableContent() . "\t" . "Now: ";
//$testExactRealFrac->setContentFromString("0.2");
//echo $testExactRealFrac->getReadableContent() . "\n";
//$testExactRealFrac->saveVarToFile();
*/
<commit_msg>Limit fd usage in tests.cpp (isolate each one)<commit_after>/*
* Part of tivars_lib_cpp
* (C) 2015-2017 Adrien 'Adriweb' Bertrand
* https://github.com/adriweb/tivars_lib_cpp
* License: MIT
*/
#include <assert.h>
#include "src/autoloader.h"
#include "src/TIModels.h"
#include "src/TIVarTypes.h"
#include "src/BinaryFile.h"
#include "src/TIVarFile.h"
#include "src/TypeHandlers/TypeHandlers.h"
#include "src/utils.h"
using namespace std;
using namespace tivars;
int main(int argc, char** argv)
{
(void)argc;
(void)argv;
/* Init Stuff */
TIModels::initTIModelsArray();
TIVarTypes::initTIVarTypesArray();
TH_0x05::initTokens();
using tivars::TH_0x05::LANG_FR;
using tivars::TH_0x05::LANG_EN;
/* Tests */
assert(TIVarTypes::getIDFromName("ExactRealPi") == 32);
{
TIVarFile toksPrgm = TIVarFile::loadFromFile("testData/ALLTOKS.8Xp");
cout << toksPrgm.getReadableContent() << "\n" << endl << std::flush;
}
{
TIVarFile testAppVar = TIVarFile::createNew(TIVarType::createFromName("AppVar"), "TEST");
testAppVar.setContentFromString("ABCD1234C9C8C7C6"); // random but valid hex string
assert(testAppVar.getReadableContent() == "ABCD1234C9C8C7C6");
assert(testAppVar.getRawContent().size() == strlen("ABCD1234C9C8C7C6") / 2 + 2);
testAppVar.saveVarToFile("testData", "testAVnew");
}
{
TIVarFile testString = TIVarFile::loadFromFile("testData/String.8xs");
assert(testString.getReadableContent() == "Hello World");
}
{
TIVarFile testPrgmQuotes = TIVarFile::loadFromFile("testData/testPrgmQuotes.8xp");
cout << "testPrgmQuotes.getReadableContent() : " << testPrgmQuotes.getReadableContent() << endl << std::flush;
assert(testPrgmQuotes.getReadableContent() == "Pause \"2 SECS\",2");
}
{
TIVarFile testEquation = TIVarFile::loadFromFile("testData/Equation_Y1T.8xy");
assert(testEquation.getReadableContent() == "3sin(T)+4");
}
{
TIVarFile testReal = TIVarFile::loadFromFile("testData/Real.8xn");
assert(testReal.getReadableContent() == "-42.1337");
testReal.setContentFromString(".5");
cout << "testReal.getReadableContent() : " << testReal.getReadableContent() << endl << std::flush;
assert(testReal.getReadableContent() == "0.5");
}
{
TIVarFile testReal42 = TIVarFile::createNew(TIVarType::createFromName("Real"), "R");
testReal42.setCalcModel(TIModel::createFromName("84+"));
testReal42.setContentFromString("9001.42");
cout << "testReal42.getReadableContent() : " << testReal42.getReadableContent() << endl << std::flush;
assert(testReal42.getReadableContent() == "9001.42");
testReal42.setContentFromString("-0.00000008");
cout << "testReal42.getReadableContent() : " << testReal42.getReadableContent() << endl << std::flush;
assert(atof(testReal42.getReadableContent().c_str()) == -8e-08);
testReal42.saveVarToFile("testData", "Real_new");
}
{
string test = "Disp 42:Wait 5:toString(42):Pause\nInput A,\"?\":Asdf(123)\nFor(I,1,10)\nThen\nDisp I:For(J,1,10)\nThen\nDisp J\nEnd\nEnd";
cout << "Indented code:" << endl << TH_0x05::reindentCodeString(test) << endl << std::flush;
}
{
TIVarFile testPrgmReindent = TIVarFile::createNew(TIVarType::createFromName("Program"), "asdf");
testPrgmReindent.setContentFromString("\"http://TIPlanet.org");
assert(trim(testPrgmReindent.getReadableContent({{"prettify", true}, {"reindent", true}})) == "\"http://TIPlanet.org");
}
#ifndef __EMSCRIPTEN__
{
try
{
auto goodTypeForCalc = TIVarFile::createNew(TIVarType::createFromName("Program"), "Bla", TIModel::createFromName("83PCE"));
} catch (runtime_error& e) {
cout << "Caught unexpected exception: " << e.what() << endl << std::flush;
}
try
{
auto badTypeForCalc = TIVarFile::createNew(TIVarType::createFromName("ExactComplexFrac"), "Bla", TIModel::createFromName("84+"));
} catch (runtime_error& e) {
cout << "Caught expected exception: " << e.what() << endl << std::flush;
}
}
#endif
assert(TIVarTypes::getIDFromName("ExactRealPi") == 32);
{
TIVarFile testPrgm = TIVarFile::loadFromFile("testData/Program.8xp");
cout << "testPrgm.getHeader().entries_len = " << testPrgm.getHeader().entries_len
<< "\t testPrgm.size() - 57 == " << (testPrgm.size() - 57) << endl << std::flush;
assert(testPrgm.getHeader().entries_len == testPrgm.size() - 57);
string testPrgmcontent = testPrgm.getReadableContent({{"lang", LANG_FR}});
TIVarFile newPrgm = TIVarFile::createNew(TIVarType::createFromName("Program"));
newPrgm.setContentFromString(testPrgmcontent);
string newPrgmcontent = newPrgm.getReadableContent({{"lang", LANG_FR}});
assert(testPrgmcontent == newPrgmcontent);
newPrgm.saveVarToFile("testData", "Program_new");
cout << endl << "testPrgmcontent : " << endl << testPrgmcontent << endl << std::flush;
cout << "\n\n\n" << endl << std::flush;
}
{
TIVarFile testPrgm42 = TIVarFile::createNew(TIVarType::createFromName("Program"), "asdf");
testPrgm42.setCalcModel(TIModel::createFromName("82A"));
testPrgm42.setContentFromString("Grande blabla:Disp \"Grande blabla");
testPrgm42.setVarName("Toto");
assert(testPrgm42.getReadableContent() == "Grande blabla:Disp \"Grande blabla");
testPrgm42.saveVarToFile("testData", "testMinTok_new");
testPrgm42.setArchived(true);
testPrgm42.saveVarToFile("testData", "testMinTok_archived_new");
}
{
TIVarFile testPrgm = TIVarFile::createNew(TIVarType::createFromName("Program"), "asdf");
testPrgm.setContentFromString("Pause 42:Pause 43:Disp \"\",\"Bouh la =/*: déf\",\"suite :\",\" OK");
string testPrgmcontent = testPrgm.getReadableContent({{"prettify", true}, {"reindent", true}});
assert(trim(testPrgmcontent) == "Pause 42\nPause 43\nDisp \"\",\"Bouh la =/*: déf\",\"suite :\",\" OK");
}
{
TIVarFile testRealList = TIVarFile::loadFromFile("testData/RealList.8xl");
cout << "Before: " << testRealList.getReadableContent() << "\n Now: ";
testRealList.setContentFromString("{9, 0, .5, -6e-8}");
cout << testRealList.getReadableContent() << "\n";
testRealList.saveVarToFile("testData", "RealList_new");
}
{
TIVarFile testStandardMatrix = TIVarFile::loadFromFile("testData/Matrix_3x3_standard.8xm");
cout << "Before: " << testStandardMatrix.getReadableContent() << "\n Now: ";
testStandardMatrix.setContentFromString("[[1,2,3][4,5,6][-7,-8,-9]]");
testStandardMatrix.setContentFromString("[[1,2,3][4,5,6][-7.5,-8,-9][1,2,3][4,5,6][-0.002,-8,-9]]");
cout << testStandardMatrix.getReadableContent() << "\n";
testStandardMatrix.saveVarToFile("testData", "Matrix_new");
}
{
TIVarFile testComplex = TIVarFile::loadFromFile("testData/Complex.8xc"); // -5 + 2i
cout << "Before: " << testComplex.getReadableContent() << "\n Now: ";
assert(testComplex.getReadableContent() == "-5+2i");
TIVarFile newComplex = TIVarFile::createNew(TIVarType::createFromName("Complex"), "C");
newComplex.setContentFromString("-5+2i");
assert(newComplex.getRawContent() == newComplex.getRawContent());
newComplex.setContentFromString("2.5+0.001i");
cout << "After: " << newComplex.getReadableContent() << endl << std::flush;
testComplex.saveVarToFile("testData", "Complex_new");
}
{
TIVarFile testComplexList = TIVarFile::loadFromFile("testData/ComplexList.8xl");
cout << "Before: " << testComplexList.getReadableContent() << "\n Now: ";
testComplexList.setContentFromString("{9+2i, 0i, .5, -0.5+6e-8i}");
cout << testComplexList.getReadableContent() << "\n";
testComplexList.saveVarToFile("testData", "ComplexList_new");
}
{
TIVarFile testExact_RealRadical = TIVarFile::loadFromFile("testData/Exact_RealRadical.8xn");
cout << "Before: " << testExact_RealRadical.getReadableContent() << endl << std::flush;
assert(testExact_RealRadical.getReadableContent() == "(41*√(789)+14*√(654))/259");
//TIVarFile newExact_RealRadical = TIVarFile::createNew(TIVarType::createFromName("ExactRealRadical"), "A", TIModel::createFromName("83PCE"));
//newExact_RealRadical.setContentFromString("-42.1337");
//assert(testExact_RealRadical.getRawContent() == newExact_RealRadical.getRawContent());
//newExact_RealRadical.saveVarToFile("testData", "Exact_RealRadical_new");
}
{
TIVarFile testExactComplexFrac = TIVarFile::loadFromFile("testData/Exact_ComplexFrac.8xc");
cout << "Before: " << testExactComplexFrac.getReadableContent() << endl << std::flush;
assert(testExactComplexFrac.getReadableContent() == "1/5-2/5i");
//TIVarFile newExactComplexFrac = TIVarFile::createNew(TIVarType::createFromName("ExactComplexFrac"), "A", TIModel::createFromName("83PCE"));
//newExactComplexFrac.setContentFromString("-42.1337");
//assert(testExactComplexFrac.getRawContent() == newExactComplexFrac.getRawContent());
//newExactComplexFrac.saveVarToFile("testData", "Exact_ComplexFrac_new");
}
{
TIVarFile testExactComplexPi = TIVarFile::loadFromFile("testData/Exact_ComplexPi.8xc");
cout << "Before: " << testExactComplexPi.getReadableContent() << endl << std::flush;
assert(testExactComplexPi.getReadableContent() == "1/5-3*π*i");
//TIVarFile newExactComplexPi = TIVarFile::createNew(TIVarType::createFromName("ExactComplexPi"), "A", TIModel::createFromName("83PCE"));
//newExactComplexPi.setContentFromString("-42.1337");
//assert(testExactComplexPi.getRawContent() == newExactComplexPi.getRawContent());
//newExactComplexPi.saveVarToFile("testData", "Exact_ComplexPi_new");
}
{
TIVarFile testExactComplexPiFrac = TIVarFile::loadFromFile("testData/Exact_ComplexPiFrac.8xc");
cout << "Before: " << testExactComplexPiFrac.getReadableContent() << endl << std::flush;
assert(testExactComplexPiFrac.getReadableContent() == "2/7*π*i");
//TIVarFile newExactComplexPiFrac = TIVarFile::createNew(TIVarType::createFromName("ExactComplexPiFrac"), "A", TIModel::createFromName("83PCE"));
//newExactComplexPiFrac.setContentFromString("-42.1337");
//assert(testExactComplexPiFrac.getRawContent() == newExactComplexPiFrac.getRawContent());
//newExactComplexPiFrac.saveVarToFile("testData", "Exact_ComplexPiFrac_new");
}
{
TIVarFile testExactComplexRadical = TIVarFile::loadFromFile("testData/Exact_ComplexRadical.8xc");
cout << "Before: " << testExactComplexRadical.getReadableContent() << endl << std::flush;
assert(testExactComplexRadical.getReadableContent() == "((√(6)+√(2))/4)+((√(6)-√(2))/4)*i");
//TIVarFile newExactComplexRadical = TIVarFile::createNew(TIVarType::createFromName("ExactComplexRadical"), "A", TIModel::createFromName("83PCE"));
//newExactComplexRadical.setContentFromString("-42.1337");
//assert(testExactComplexRadical.getRawContent() == newExactComplexRadical.getRawContent());
//newExactComplexRadical.saveVarToFile("testData", "Exact_ComplexRadical_new");
}
{
TIVarFile testExactRealPi = TIVarFile::loadFromFile("testData/Exact_RealPi.8xn");
cout << "Before: " << testExactRealPi.getReadableContent() << endl << std::flush;
assert(testExactRealPi.getReadableContent() == "30*π");
//TIVarFile newExactRealPi = TIVarFile::createNew(TIVarType::createFromName("ExactRealPi"), "A", TIModel::createFromName("83PCE"));
//newExactRealPi.setContentFromString("-42.1337");
//assert(testExactRealPi.getRawContent() == newExactRealPi.getRawContent());
//newExactRealPi.saveVarToFile("testData", "Exact_RealPi_new");
}
{
TIVarFile testExactRealPiFrac = TIVarFile::loadFromFile("testData/Exact_RealPiFrac.8xn");
cout << "Before: " << testExactRealPiFrac.getReadableContent() << endl << std::flush;
assert(testExactRealPiFrac.getReadableContent() == "2/7*π");
//TIVarFile newExactRealPiFrac = TIVarFile::createNew(TIVarType::createFromName("ExactRealPiFrac"), "A", TIModel::createFromName("83PCE"));
//newExactRealPiFrac.setContentFromString("-42.1337");
//assert(testExactRealPiFrac.getRawContent() == newExactRealPiFrac.getRawContent());
//newExactRealPiFrac.saveVarToFile("testData", "Exact_RealPiFrac_new");
}
return 0;
}
<|endoftext|> |
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2010 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
#include <iostream>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>
#include <OpenMesh/Tools/Dualizer/meshDualT.hh>
typedef OpenMesh::PolyMesh_ArrayKernelT<> MyMesh;
int main(int argc, char **argv)
{
MyMesh mesh;
// read mesh from argv[1]
if ( !OpenMesh::IO::read_mesh(mesh, argv[1]) )
{
std::cerr << "Cannot read mesh from file" << argv[1] << std::endl;
return 1;
}
MyMesh *dual = OpenMesh::Util::MeshDual(mesh);
// write mesh to output.obj
if ( !OpenMesh::IO::write_mesh(*dual, "output.obj") )
{
std::cerr << "Cannot write mesh to file 'output.obj'" << std::endl;
return 1;
}
delete dual;
return 0;
}
<commit_msg>Dont crash on wrong command line options<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2010 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
#include <iostream>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>
#include <OpenMesh/Tools/Dualizer/meshDualT.hh>
typedef OpenMesh::PolyMesh_ArrayKernelT<> MyMesh;
int main(int argc, char **argv)
{
MyMesh mesh;
if ( argc != 2 ) {
std::cerr << "Please specify input filename only!" << std::endl;
return 1;
}
// read mesh from argv[1]
if ( !OpenMesh::IO::read_mesh(mesh, argv[1]) )
{
std::cerr << "Cannot read mesh from file" << argv[1] << std::endl;
return 1;
}
MyMesh *dual = OpenMesh::Util::MeshDual(mesh);
// write mesh to output.obj
if ( !OpenMesh::IO::write_mesh(*dual, "output.obj") )
{
std::cerr << "Cannot write mesh to file 'output.obj'" << std::endl;
return 1;
}
delete dual;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/foreign_session_helper.h"
#include <jni.h>
#include "base/android/jni_string.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile_android.h"
#include "chrome/browser/sessions/session_restore.h"
#include "chrome/browser/sync/open_tabs_ui_delegate.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/android/tab_model/tab_model.h"
#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
#include "jni/ForeignSessionHelper_jni.h"
using base::android::ScopedJavaGlobalRef;
using base::android::ScopedJavaLocalRef;
using base::android::AttachCurrentThread;
using base::android::ConvertUTF16ToJavaString;
using base::android::ConvertUTF8ToJavaString;
using base::android::ConvertJavaStringToUTF8;
using browser_sync::OpenTabsUIDelegate;
using browser_sync::SyncedSession;
namespace {
OpenTabsUIDelegate* GetOpenTabsUIDelegate(Profile* profile) {
ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->
GetForProfile(profile);
// Only return the delegate if it exists and it is done syncing sessions.
if (!service || !service->ShouldPushChanges())
return NULL;
return service->GetOpenTabsUIDelegate();
}
void CopyTabsToJava(
JNIEnv* env,
const SessionWindow& window,
ScopedJavaLocalRef<jobject>& j_window) {
for (std::vector<SessionTab*>::const_iterator tab_it = window.tabs.begin();
tab_it != window.tabs.end(); ++tab_it) {
const SessionTab &session_tab = **tab_it;
int selected_index = session_tab.normalized_navigation_index();
const ::sessions::SerializedNavigationEntry& current_navigation =
session_tab.navigations.at(selected_index);
GURL tab_url = current_navigation.virtual_url();
Java_ForeignSessionHelper_pushTab(
env, j_window.obj(),
ConvertUTF8ToJavaString(env, tab_url.spec()).obj(),
ConvertUTF16ToJavaString(env, current_navigation.title()).obj(),
session_tab.timestamp.ToJavaTime(),
session_tab.tab_id.id());
}
}
void CopyWindowsToJava(
JNIEnv* env,
const SyncedSession& session,
ScopedJavaLocalRef<jobject>& j_session) {
for (SyncedSession::SyncedWindowMap::const_iterator it =
session.windows.begin(); it != session.windows.end(); ++it) {
const SessionWindow &window = *(it->second);
ScopedJavaLocalRef<jobject> last_pushed_window;
last_pushed_window.Reset(
Java_ForeignSessionHelper_pushWindow(
env, j_session.obj(),
window.timestamp.ToJavaTime(),
window.window_id.id()));
CopyTabsToJava(env, window, last_pushed_window);
}
}
} // namespace
static jlong Init(JNIEnv* env, jclass clazz, jobject profile) {
ForeignSessionHelper* foreign_session_helper = new ForeignSessionHelper(
ProfileAndroid::FromProfileAndroid(profile));
return reinterpret_cast<intptr_t>(foreign_session_helper);
}
ForeignSessionHelper::ForeignSessionHelper(Profile* profile)
: profile_(profile) {
ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->
GetForProfile(profile);
registrar_.Add(this, chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
content::Source<ProfileSyncService>(service));
registrar_.Add(this, chrome::NOTIFICATION_FOREIGN_SESSION_UPDATED,
content::Source<Profile>(profile));
registrar_.Add(this, chrome::NOTIFICATION_FOREIGN_SESSION_DISABLED,
content::Source<Profile>(profile));
}
ForeignSessionHelper::~ForeignSessionHelper() {
}
void ForeignSessionHelper::Destroy(JNIEnv* env, jobject obj) {
delete this;
}
jboolean ForeignSessionHelper::IsTabSyncEnabled(JNIEnv* env, jobject obj) {
ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->
GetForProfile(profile_);
return service && service->GetActiveDataTypes().Has(syncer::PROXY_TABS);
}
void ForeignSessionHelper::SetOnForeignSessionCallback(JNIEnv* env,
jobject obj,
jobject callback) {
callback_.Reset(env, callback);
}
void ForeignSessionHelper::Observe(
int type, const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (callback_.is_null())
return;
JNIEnv* env = AttachCurrentThread();
switch (type) {
case chrome::NOTIFICATION_FOREIGN_SESSION_DISABLED:
// Tab sync is disabled, so clean up data about collapsed sessions.
profile_->GetPrefs()->ClearPref(
prefs::kNtpCollapsedForeignSessions);
// Purposeful fall through.
case chrome::NOTIFICATION_SYNC_CONFIGURE_DONE:
case chrome::NOTIFICATION_FOREIGN_SESSION_UPDATED:
Java_ForeignSessionCallback_onUpdated(env, callback_.obj());
break;
default:
NOTREACHED();
}
}
jboolean ForeignSessionHelper::GetForeignSessions(JNIEnv* env,
jobject obj,
jobject result) {
OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(profile_);
if (!open_tabs)
return false;
std::vector<const browser_sync::SyncedSession*> sessions;
if (!open_tabs->GetAllForeignSessions(&sessions))
return false;
// Use a pref to keep track of sessions that were collapsed by the user.
// To prevent the pref from accumulating stale sessions, clear it each time
// and only add back sessions that are still current.
DictionaryPrefUpdate pref_update(profile_->GetPrefs(),
prefs::kNtpCollapsedForeignSessions);
base::DictionaryValue* pref_collapsed_sessions = pref_update.Get();
scoped_ptr<base::DictionaryValue> collapsed_sessions(
pref_collapsed_sessions->DeepCopy());
pref_collapsed_sessions->Clear();
ScopedJavaLocalRef<jobject> last_pushed_session;
ScopedJavaLocalRef<jobject> last_pushed_window;
// Note: we don't own the SyncedSessions themselves.
for (size_t i = 0; i < sessions.size(); ++i) {
const browser_sync::SyncedSession &session = *(sessions[i]);
const bool is_collapsed = collapsed_sessions->HasKey(session.session_tag);
if (is_collapsed)
pref_collapsed_sessions->SetBoolean(session.session_tag, true);
last_pushed_session.Reset(
Java_ForeignSessionHelper_pushSession(
env,
result,
ConvertUTF8ToJavaString(env, session.session_tag).obj(),
ConvertUTF8ToJavaString(env, session.session_name).obj(),
session.device_type,
session.modified_time.ToJavaTime()));
CopyWindowsToJava(env, session, last_pushed_session);
}
return true;
}
jboolean ForeignSessionHelper::OpenForeignSessionTab(JNIEnv* env,
jobject obj,
jobject j_tab,
jstring session_tag,
jint session_tab_id,
jint j_disposition) {
OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(profile_);
if (!open_tabs) {
LOG(ERROR) << "Null OpenTabsUIDelegate returned.";
return false;
}
const SessionTab* session_tab;
if (!open_tabs->GetForeignTab(ConvertJavaStringToUTF8(env, session_tag),
session_tab_id,
&session_tab)) {
LOG(ERROR) << "Failed to load foreign tab.";
return false;
}
if (session_tab->navigations.empty()) {
LOG(ERROR) << "Foreign tab no longer has valid navigations.";
return false;
}
TabAndroid* tab_android = TabAndroid::GetNativeTab(env, j_tab);
if (!tab_android)
return false;
content::WebContents* web_contents = tab_android->web_contents();
if (!web_contents)
return false;
WindowOpenDisposition disposition =
static_cast<WindowOpenDisposition>(j_disposition);
SessionRestore::RestoreForeignSessionTab(web_contents,
*session_tab,
disposition);
return true;
}
void ForeignSessionHelper::DeleteForeignSession(JNIEnv* env, jobject obj,
jstring session_tag) {
OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(profile_);
if (open_tabs)
open_tabs->DeleteForeignSession(ConvertJavaStringToUTF8(env, session_tag));
}
// static
bool ForeignSessionHelper::RegisterForeignSessionHelper(JNIEnv* env) {
return RegisterNativesImpl(env);
}
<commit_msg>Revert of Fix foreign tabs with > 6 navigations not showing up on Android. (https://codereview.chromium.org/433633002/)<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/foreign_session_helper.h"
#include <jni.h>
#include "base/android/jni_string.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile_android.h"
#include "chrome/browser/sessions/session_restore.h"
#include "chrome/browser/sync/open_tabs_ui_delegate.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/ui/android/tab_model/tab_model.h"
#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
#include "jni/ForeignSessionHelper_jni.h"
using base::android::ScopedJavaGlobalRef;
using base::android::ScopedJavaLocalRef;
using base::android::AttachCurrentThread;
using base::android::ConvertUTF16ToJavaString;
using base::android::ConvertUTF8ToJavaString;
using base::android::ConvertJavaStringToUTF8;
using browser_sync::OpenTabsUIDelegate;
using browser_sync::SyncedSession;
namespace {
OpenTabsUIDelegate* GetOpenTabsUIDelegate(Profile* profile) {
ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->
GetForProfile(profile);
// Only return the delegate if it exists and it is done syncing sessions.
if (!service || !service->ShouldPushChanges())
return NULL;
return service->GetOpenTabsUIDelegate();
}
bool ShouldSkipTab(const SessionTab& session_tab) {
if (session_tab.navigations.empty())
return true;
int selected_index = session_tab.current_navigation_index;
if (selected_index < 0 ||
selected_index >= static_cast<int>(session_tab.navigations.size()))
return true;
const ::sessions::SerializedNavigationEntry& current_navigation =
session_tab.navigations.at(selected_index);
if (current_navigation.virtual_url().is_empty())
return true;
return false;
}
bool ShouldSkipWindow(const SessionWindow& window) {
for (std::vector<SessionTab*>::const_iterator tab_it = window.tabs.begin();
tab_it != window.tabs.end(); ++tab_it) {
const SessionTab &session_tab = **tab_it;
if (!ShouldSkipTab(session_tab))
return false;
}
return true;
}
bool ShouldSkipSession(const browser_sync::SyncedSession& session) {
for (SyncedSession::SyncedWindowMap::const_iterator it =
session.windows.begin(); it != session.windows.end(); ++it) {
const SessionWindow &window = *(it->second);
if (!ShouldSkipWindow(window))
return false;
}
return true;
}
void CopyTabsToJava(
JNIEnv* env,
const SessionWindow& window,
ScopedJavaLocalRef<jobject>& j_window) {
for (std::vector<SessionTab*>::const_iterator tab_it = window.tabs.begin();
tab_it != window.tabs.end(); ++tab_it) {
const SessionTab &session_tab = **tab_it;
if (ShouldSkipTab(session_tab))
continue;
int selected_index = session_tab.current_navigation_index;
DCHECK(selected_index >= 0);
DCHECK(selected_index < static_cast<int>(session_tab.navigations.size()));
const ::sessions::SerializedNavigationEntry& current_navigation =
session_tab.navigations.at(selected_index);
GURL tab_url = current_navigation.virtual_url();
Java_ForeignSessionHelper_pushTab(
env, j_window.obj(),
ConvertUTF8ToJavaString(env, tab_url.spec()).obj(),
ConvertUTF16ToJavaString(env, current_navigation.title()).obj(),
session_tab.timestamp.ToJavaTime(),
session_tab.tab_id.id());
}
}
void CopyWindowsToJava(
JNIEnv* env,
const SyncedSession& session,
ScopedJavaLocalRef<jobject>& j_session) {
for (SyncedSession::SyncedWindowMap::const_iterator it =
session.windows.begin(); it != session.windows.end(); ++it) {
const SessionWindow &window = *(it->second);
if (ShouldSkipWindow(window))
continue;
ScopedJavaLocalRef<jobject> last_pushed_window;
last_pushed_window.Reset(
Java_ForeignSessionHelper_pushWindow(
env, j_session.obj(),
window.timestamp.ToJavaTime(),
window.window_id.id()));
CopyTabsToJava(env, window, last_pushed_window);
}
}
} // namespace
static jlong Init(JNIEnv* env, jclass clazz, jobject profile) {
ForeignSessionHelper* foreign_session_helper = new ForeignSessionHelper(
ProfileAndroid::FromProfileAndroid(profile));
return reinterpret_cast<intptr_t>(foreign_session_helper);
}
ForeignSessionHelper::ForeignSessionHelper(Profile* profile)
: profile_(profile) {
ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->
GetForProfile(profile);
registrar_.Add(this, chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
content::Source<ProfileSyncService>(service));
registrar_.Add(this, chrome::NOTIFICATION_FOREIGN_SESSION_UPDATED,
content::Source<Profile>(profile));
registrar_.Add(this, chrome::NOTIFICATION_FOREIGN_SESSION_DISABLED,
content::Source<Profile>(profile));
}
ForeignSessionHelper::~ForeignSessionHelper() {
}
void ForeignSessionHelper::Destroy(JNIEnv* env, jobject obj) {
delete this;
}
jboolean ForeignSessionHelper::IsTabSyncEnabled(JNIEnv* env, jobject obj) {
ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->
GetForProfile(profile_);
return service && service->GetActiveDataTypes().Has(syncer::PROXY_TABS);
}
void ForeignSessionHelper::SetOnForeignSessionCallback(JNIEnv* env,
jobject obj,
jobject callback) {
callback_.Reset(env, callback);
}
void ForeignSessionHelper::Observe(
int type, const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (callback_.is_null())
return;
JNIEnv* env = AttachCurrentThread();
switch (type) {
case chrome::NOTIFICATION_FOREIGN_SESSION_DISABLED:
// Tab sync is disabled, so clean up data about collapsed sessions.
profile_->GetPrefs()->ClearPref(
prefs::kNtpCollapsedForeignSessions);
// Purposeful fall through.
case chrome::NOTIFICATION_SYNC_CONFIGURE_DONE:
case chrome::NOTIFICATION_FOREIGN_SESSION_UPDATED:
Java_ForeignSessionCallback_onUpdated(env, callback_.obj());
break;
default:
NOTREACHED();
}
}
jboolean ForeignSessionHelper::GetForeignSessions(JNIEnv* env,
jobject obj,
jobject result) {
OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(profile_);
if (!open_tabs)
return false;
std::vector<const browser_sync::SyncedSession*> sessions;
if (!open_tabs->GetAllForeignSessions(&sessions))
return false;
// Use a pref to keep track of sessions that were collapsed by the user.
// To prevent the pref from accumulating stale sessions, clear it each time
// and only add back sessions that are still current.
DictionaryPrefUpdate pref_update(profile_->GetPrefs(),
prefs::kNtpCollapsedForeignSessions);
base::DictionaryValue* pref_collapsed_sessions = pref_update.Get();
scoped_ptr<base::DictionaryValue> collapsed_sessions(
pref_collapsed_sessions->DeepCopy());
pref_collapsed_sessions->Clear();
ScopedJavaLocalRef<jobject> last_pushed_session;
ScopedJavaLocalRef<jobject> last_pushed_window;
// Note: we don't own the SyncedSessions themselves.
for (size_t i = 0; i < sessions.size(); ++i) {
const browser_sync::SyncedSession &session = *(sessions[i]);
if (ShouldSkipSession(session))
continue;
const bool is_collapsed = collapsed_sessions->HasKey(session.session_tag);
if (is_collapsed)
pref_collapsed_sessions->SetBoolean(session.session_tag, true);
last_pushed_session.Reset(
Java_ForeignSessionHelper_pushSession(
env,
result,
ConvertUTF8ToJavaString(env, session.session_tag).obj(),
ConvertUTF8ToJavaString(env, session.session_name).obj(),
session.device_type,
session.modified_time.ToJavaTime()));
CopyWindowsToJava(env, session, last_pushed_session);
}
return true;
}
jboolean ForeignSessionHelper::OpenForeignSessionTab(JNIEnv* env,
jobject obj,
jobject j_tab,
jstring session_tag,
jint session_tab_id,
jint j_disposition) {
OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(profile_);
if (!open_tabs) {
LOG(ERROR) << "Null OpenTabsUIDelegate returned.";
return false;
}
const SessionTab* session_tab;
if (!open_tabs->GetForeignTab(ConvertJavaStringToUTF8(env, session_tag),
session_tab_id,
&session_tab)) {
LOG(ERROR) << "Failed to load foreign tab.";
return false;
}
if (session_tab->navigations.empty()) {
LOG(ERROR) << "Foreign tab no longer has valid navigations.";
return false;
}
TabAndroid* tab_android = TabAndroid::GetNativeTab(env, j_tab);
if (!tab_android)
return false;
content::WebContents* web_contents = tab_android->web_contents();
if (!web_contents)
return false;
WindowOpenDisposition disposition =
static_cast<WindowOpenDisposition>(j_disposition);
SessionRestore::RestoreForeignSessionTab(web_contents,
*session_tab,
disposition);
return true;
}
void ForeignSessionHelper::DeleteForeignSession(JNIEnv* env, jobject obj,
jstring session_tag) {
OpenTabsUIDelegate* open_tabs = GetOpenTabsUIDelegate(profile_);
if (open_tabs)
open_tabs->DeleteForeignSession(ConvertJavaStringToUTF8(env, session_tag));
}
// static
bool ForeignSessionHelper::RegisterForeignSessionHelper(JNIEnv* env) {
return RegisterNativesImpl(env);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/cros/language_library.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
template <>
struct RunnableMethodTraits<chromeos::LanguageLibrary> {
void RetainCallee(chromeos::LanguageLibrary* obj) {}
void ReleaseCallee(chromeos::LanguageLibrary* obj) {}
};
namespace {
// Finds a property which has |new_prop.key| from |prop_list|, and replaces the
// property with |new_prop|. Returns true if such a property is found.
bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
chromeos::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
// Update the list except the radio id. As written in chromeos_language.h,
// |prop.selection_item_id| is dummy.
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
} // namespace
namespace chromeos {
LanguageLibrary::LanguageLibrary() : language_status_connection_(NULL) {
}
LanguageLibrary::~LanguageLibrary() {
if (EnsureLoadedAndStarted()) {
chromeos::DisconnectLanguageStatus(language_status_connection_);
}
}
LanguageLibrary::Observer::~Observer() {
}
// static
LanguageLibrary* LanguageLibrary::Get() {
return Singleton<LanguageLibrary>::get();
}
void LanguageLibrary::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void LanguageLibrary::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
chromeos::InputLanguageList* LanguageLibrary::GetActiveLanguages() {
chromeos::InputLanguageList* result = NULL;
if (EnsureLoadedAndStarted()) {
result = chromeos::GetActiveLanguages(language_status_connection_);
}
return result ? result : CreateFallbackInputLanguageList();
}
chromeos::InputLanguageList* LanguageLibrary::GetSupportedLanguages() {
chromeos::InputLanguageList* result = NULL;
if (EnsureLoadedAndStarted()) {
result = chromeos::GetSupportedLanguages(language_status_connection_);
}
return result ? result : CreateFallbackInputLanguageList();
}
void LanguageLibrary::ChangeLanguage(
LanguageCategory category, const std::string& id) {
if (EnsureLoadedAndStarted()) {
chromeos::ChangeLanguage(language_status_connection_, category, id.c_str());
}
}
void LanguageLibrary::ActivateImeProperty(const std::string& key) {
DCHECK(!key.empty());
if (EnsureLoadedAndStarted()) {
chromeos::ActivateImeProperty(
language_status_connection_, key.c_str());
}
}
void LanguageLibrary::DeactivateImeProperty(const std::string& key) {
DCHECK(!key.empty());
if (EnsureLoadedAndStarted()) {
chromeos::DeactivateImeProperty(
language_status_connection_, key.c_str());
}
}
bool LanguageLibrary::ActivateLanguage(
LanguageCategory category, const std::string& id) {
bool success = false;
if (EnsureLoadedAndStarted()) {
success = chromeos::ActivateLanguage(language_status_connection_,
category, id.c_str());
}
return success;
}
bool LanguageLibrary::DeactivateLanguage(
LanguageCategory category, const std::string& id) {
bool success = false;
if (EnsureLoadedAndStarted()) {
success = chromeos::DeactivateLanguage(language_status_connection_,
category, id.c_str());
}
return success;
}
bool LanguageLibrary::GetImeConfig(
const char* section, const char* config_name, ImeConfigValue* out_value) {
bool success = false;
if (EnsureLoadedAndStarted()) {
success = chromeos::GetImeConfig(
language_status_connection_, section, config_name, out_value);
}
return success;
}
bool LanguageLibrary::SetImeConfig(
const char* section, const char* config_name, const ImeConfigValue& value) {
bool success = false;
if (EnsureLoadedAndStarted()) {
success = chromeos::SetImeConfig(
language_status_connection_, section, config_name, value);
}
return success;
}
// static
void LanguageLibrary::LanguageChangedHandler(
void* object, const chromeos::InputLanguage& current_language) {
LanguageLibrary* language_library = static_cast<LanguageLibrary*>(object);
language_library->UpdateCurrentLanguage(current_language);
}
// static
void LanguageLibrary::RegisterPropertiesHandler(
void* object, const ImePropertyList& prop_list) {
LanguageLibrary* language_library = static_cast<LanguageLibrary*>(object);
language_library->RegisterProperties(prop_list);
}
// static
void LanguageLibrary::UpdatePropertyHandler(
void* object, const ImePropertyList& prop_list) {
LanguageLibrary* language_library = static_cast<LanguageLibrary*>(object);
language_library->UpdateProperty(prop_list);
}
bool LanguageLibrary::EnsureStarted() {
if (language_status_connection_) {
return true;
}
chromeos::LanguageStatusMonitorFunctions monitor_functions;
monitor_functions.current_language = &LanguageChangedHandler;
monitor_functions.register_ime_properties = &RegisterPropertiesHandler;
monitor_functions.update_ime_property = &UpdatePropertyHandler;
language_status_connection_
= chromeos::MonitorLanguageStatus(monitor_functions, this);
return language_status_connection_ != NULL;
}
bool LanguageLibrary::EnsureLoadedAndStarted() {
return CrosLibrary::EnsureLoaded() && EnsureStarted();
}
void LanguageLibrary::UpdateCurrentLanguage(
const chromeos::InputLanguage& current_language) {
// Make sure we run on UI thread.
if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
DLOG(INFO) << "UpdateCurrentLanguage (Background thread)";
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
// NewRunnableMethod() copies |current_language| by value.
NewRunnableMethod(
this, &LanguageLibrary::UpdateCurrentLanguage, current_language));
return;
}
DLOG(INFO) << "UpdateCurrentLanguage (UI thread)";
current_language_ = current_language;
FOR_EACH_OBSERVER(Observer, observers_, LanguageChanged(this));
}
void LanguageLibrary::RegisterProperties(const ImePropertyList& prop_list) {
if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(
this, &LanguageLibrary::RegisterProperties, prop_list));
return;
}
// |prop_list| might be empty. This means "clear all properties."
current_ime_properties_ = prop_list;
FOR_EACH_OBSERVER(Observer, observers_, ImePropertiesChanged(this));
}
void LanguageLibrary::UpdateProperty(const ImePropertyList& prop_list) {
if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(
this, &LanguageLibrary::UpdateProperty, prop_list));
return;
}
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
FOR_EACH_OBSERVER(Observer, observers_, ImePropertiesChanged(this));
}
} // namespace chromeos
<commit_msg>Automatically recovers an IME connection.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/cros/language_library.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
template <>
struct RunnableMethodTraits<chromeos::LanguageLibrary> {
void RetainCallee(chromeos::LanguageLibrary* obj) {}
void ReleaseCallee(chromeos::LanguageLibrary* obj) {}
};
namespace {
// Finds a property which has |new_prop.key| from |prop_list|, and replaces the
// property with |new_prop|. Returns true if such a property is found.
bool FindAndUpdateProperty(const chromeos::ImeProperty& new_prop,
chromeos::ImePropertyList* prop_list) {
for (size_t i = 0; i < prop_list->size(); ++i) {
chromeos::ImeProperty& prop = prop_list->at(i);
if (prop.key == new_prop.key) {
const int saved_id = prop.selection_item_id;
// Update the list except the radio id. As written in chromeos_language.h,
// |prop.selection_item_id| is dummy.
prop = new_prop;
prop.selection_item_id = saved_id;
return true;
}
}
return false;
}
} // namespace
namespace chromeos {
LanguageLibrary::LanguageLibrary() : language_status_connection_(NULL) {
}
LanguageLibrary::~LanguageLibrary() {
if (EnsureLoadedAndStarted()) {
chromeos::DisconnectLanguageStatus(language_status_connection_);
}
}
LanguageLibrary::Observer::~Observer() {
}
// static
LanguageLibrary* LanguageLibrary::Get() {
return Singleton<LanguageLibrary>::get();
}
void LanguageLibrary::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void LanguageLibrary::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
chromeos::InputLanguageList* LanguageLibrary::GetActiveLanguages() {
chromeos::InputLanguageList* result = NULL;
if (EnsureLoadedAndStarted()) {
result = chromeos::GetActiveLanguages(language_status_connection_);
}
return result ? result : CreateFallbackInputLanguageList();
}
chromeos::InputLanguageList* LanguageLibrary::GetSupportedLanguages() {
chromeos::InputLanguageList* result = NULL;
if (EnsureLoadedAndStarted()) {
result = chromeos::GetSupportedLanguages(language_status_connection_);
}
return result ? result : CreateFallbackInputLanguageList();
}
void LanguageLibrary::ChangeLanguage(
LanguageCategory category, const std::string& id) {
if (EnsureLoadedAndStarted()) {
chromeos::ChangeLanguage(language_status_connection_, category, id.c_str());
}
}
void LanguageLibrary::ActivateImeProperty(const std::string& key) {
DCHECK(!key.empty());
if (EnsureLoadedAndStarted()) {
chromeos::ActivateImeProperty(
language_status_connection_, key.c_str());
}
}
void LanguageLibrary::DeactivateImeProperty(const std::string& key) {
DCHECK(!key.empty());
if (EnsureLoadedAndStarted()) {
chromeos::DeactivateImeProperty(
language_status_connection_, key.c_str());
}
}
bool LanguageLibrary::ActivateLanguage(
LanguageCategory category, const std::string& id) {
bool success = false;
if (EnsureLoadedAndStarted()) {
success = chromeos::ActivateLanguage(language_status_connection_,
category, id.c_str());
}
return success;
}
bool LanguageLibrary::DeactivateLanguage(
LanguageCategory category, const std::string& id) {
bool success = false;
if (EnsureLoadedAndStarted()) {
success = chromeos::DeactivateLanguage(language_status_connection_,
category, id.c_str());
}
return success;
}
bool LanguageLibrary::GetImeConfig(
const char* section, const char* config_name, ImeConfigValue* out_value) {
bool success = false;
if (EnsureLoadedAndStarted()) {
success = chromeos::GetImeConfig(
language_status_connection_, section, config_name, out_value);
}
return success;
}
bool LanguageLibrary::SetImeConfig(
const char* section, const char* config_name, const ImeConfigValue& value) {
bool success = false;
if (EnsureLoadedAndStarted()) {
success = chromeos::SetImeConfig(
language_status_connection_, section, config_name, value);
}
return success;
}
// static
void LanguageLibrary::LanguageChangedHandler(
void* object, const chromeos::InputLanguage& current_language) {
LanguageLibrary* language_library = static_cast<LanguageLibrary*>(object);
language_library->UpdateCurrentLanguage(current_language);
}
// static
void LanguageLibrary::RegisterPropertiesHandler(
void* object, const ImePropertyList& prop_list) {
LanguageLibrary* language_library = static_cast<LanguageLibrary*>(object);
language_library->RegisterProperties(prop_list);
}
// static
void LanguageLibrary::UpdatePropertyHandler(
void* object, const ImePropertyList& prop_list) {
LanguageLibrary* language_library = static_cast<LanguageLibrary*>(object);
language_library->UpdateProperty(prop_list);
}
bool LanguageLibrary::EnsureStarted() {
if (language_status_connection_) {
if (chromeos::LanguageStatusConnectionIsAlive(
language_status_connection_)) {
return true;
}
DLOG(WARNING) << "IBus/XKB connection is closed. Trying to reconnect...";
chromeos::DisconnectLanguageStatus(language_status_connection_);
}
chromeos::LanguageStatusMonitorFunctions monitor_functions;
monitor_functions.current_language = &LanguageChangedHandler;
monitor_functions.register_ime_properties = &RegisterPropertiesHandler;
monitor_functions.update_ime_property = &UpdatePropertyHandler;
language_status_connection_
= chromeos::MonitorLanguageStatus(monitor_functions, this);
return language_status_connection_ != NULL;
}
bool LanguageLibrary::EnsureLoadedAndStarted() {
return CrosLibrary::EnsureLoaded() && EnsureStarted();
}
void LanguageLibrary::UpdateCurrentLanguage(
const chromeos::InputLanguage& current_language) {
// Make sure we run on UI thread.
if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
DLOG(INFO) << "UpdateCurrentLanguage (Background thread)";
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
// NewRunnableMethod() copies |current_language| by value.
NewRunnableMethod(
this, &LanguageLibrary::UpdateCurrentLanguage, current_language));
return;
}
DLOG(INFO) << "UpdateCurrentLanguage (UI thread)";
current_language_ = current_language;
FOR_EACH_OBSERVER(Observer, observers_, LanguageChanged(this));
}
void LanguageLibrary::RegisterProperties(const ImePropertyList& prop_list) {
if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(
this, &LanguageLibrary::RegisterProperties, prop_list));
return;
}
// |prop_list| might be empty. This means "clear all properties."
current_ime_properties_ = prop_list;
FOR_EACH_OBSERVER(Observer, observers_, ImePropertiesChanged(this));
}
void LanguageLibrary::UpdateProperty(const ImePropertyList& prop_list) {
if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableMethod(
this, &LanguageLibrary::UpdateProperty, prop_list));
return;
}
for (size_t i = 0; i < prop_list.size(); ++i) {
FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_);
}
FOR_EACH_OBSERVER(Observer, observers_, ImePropertiesChanged(this));
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/tab_contents/web_drag_dest_gtk.h"
#include <string>
#include "app/gtk_dnd_util.h"
#include "base/file_path.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/gtk/bookmark_utils_gtk.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "net/base/net_util.h"
using WebKit::WebDragOperation;
using WebKit::WebDragOperationNone;
WebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)
: tab_contents_(tab_contents),
widget_(widget),
context_(NULL),
method_factory_(this) {
gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),
NULL, 0,
static_cast<GdkDragAction>(GDK_ACTION_COPY |
GDK_ACTION_LINK |
GDK_ACTION_MOVE));
g_signal_connect(widget, "drag-motion",
G_CALLBACK(OnDragMotionThunk), this);
g_signal_connect(widget, "drag-leave",
G_CALLBACK(OnDragLeaveThunk), this);
g_signal_connect(widget, "drag-drop",
G_CALLBACK(OnDragDropThunk), this);
g_signal_connect(widget, "drag-data-received",
G_CALLBACK(OnDragDataReceivedThunk), this);
// TODO(tony): Need a drag-data-delete handler for moving content out of
// the tab contents. http://crbug.com/38989
destroy_handler_ = g_signal_connect(
widget, "destroy", G_CALLBACK(gtk_widget_destroyed), &widget_);
}
WebDragDestGtk::~WebDragDestGtk() {
if (widget_) {
gtk_drag_dest_unset(widget_);
g_signal_handler_disconnect(widget_, destroy_handler_);
}
}
void WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {
if (context_) {
is_drop_target_ = operation != WebDragOperationNone;
gdk_drag_status(context_, gtk_dnd_util::WebDragOpToGdkDragAction(operation),
drag_over_time_);
}
}
void WebDragDestGtk::DragLeave() {
tab_contents_->render_view_host()->DragTargetDragLeave();
if (tab_contents_->GetBookmarkDragDelegate()) {
tab_contents_->GetBookmarkDragDelegate()->OnDragLeave(bookmark_drag_data_);
}
}
gboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,
GdkDragContext* context,
gint x, gint y,
guint time) {
if (context_ != context) {
context_ = context;
drop_data_.reset(new WebDropData);
bookmark_drag_data_.Clear();
is_drop_target_ = false;
static int supported_targets[] = {
gtk_dnd_util::TEXT_PLAIN,
gtk_dnd_util::TEXT_URI_LIST,
gtk_dnd_util::TEXT_HTML,
gtk_dnd_util::NETSCAPE_URL,
gtk_dnd_util::CHROME_NAMED_URL,
gtk_dnd_util::CHROME_BOOKMARK_ITEM,
// TODO(estade): support image drags?
};
data_requests_ = arraysize(supported_targets);
for (size_t i = 0; i < arraysize(supported_targets); ++i) {
gtk_drag_get_data(widget_, context,
gtk_dnd_util::GetAtomForTarget(supported_targets[i]),
time);
}
} else if (data_requests_ == 0) {
tab_contents_->render_view_host()->
DragTargetDragOver(
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
gtk_dnd_util::GdkDragActionToWebDragOp(context->actions));
if (tab_contents_->GetBookmarkDragDelegate())
tab_contents_->GetBookmarkDragDelegate()->OnDragOver(bookmark_drag_data_);
drag_over_time_ = time;
}
// Pretend we are a drag destination because we don't want to wait for
// the renderer to tell us if we really are or not.
return TRUE;
}
void WebDragDestGtk::OnDragDataReceived(
GtkWidget* sender, GdkDragContext* context, gint x, gint y,
GtkSelectionData* data, guint info, guint time) {
// We might get the data from an old get_data() request that we no longer
// care about.
if (context != context_)
return;
data_requests_--;
// Decode the data.
if (data->data) {
// If the source can't provide us with valid data for a requested target,
// data->data will be NULL.
if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) {
guchar* text = gtk_selection_data_get_text(data);
if (text) {
drop_data_->plain_text =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(text),
data->length));
g_free(text);
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) {
gchar** uris = gtk_selection_data_get_uris(data);
if (uris) {
for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {
// TODO(estade): Can the filenames have a non-UTF8 encoding?
FilePath file_path;
if (net::FileURLToFilePath(GURL(*uri_iter), &file_path))
drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));
}
// Also, write the first URI as the URL.
if (uris[0])
drop_data_->url = GURL(uris[0]);
g_strfreev(uris);
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) {
// TODO(estade): Can the html have a non-UTF8 encoding?
drop_data_->text_html =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),
data->length));
// We leave the base URL empty.
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL)) {
std::string netscape_url(reinterpret_cast<char*>(data->data),
data->length);
size_t split = netscape_url.find_first_of('\n');
if (split != std::string::npos) {
drop_data_->url = GURL(netscape_url.substr(0, split));
if (split < netscape_url.size() - 1)
drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1));
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL)) {
gtk_dnd_util::ExtractNamedURL(data,
&drop_data_->url, &drop_data_->url_title);
}
}
// For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source
// doesn't have any data available for us. In this case we try to synthesize a
// URL bookmark.
if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_BOOKMARK_ITEM)) {
if (data->data) {
bookmark_drag_data_.ReadFromVector(
bookmark_utils::GetNodesFromSelection(
NULL, data,
gtk_dnd_util::CHROME_BOOKMARK_ITEM,
tab_contents_->profile(), NULL, NULL));
bookmark_drag_data_.SetOriginatingProfile(tab_contents_->profile());
} else {
bookmark_drag_data_.ReadFromTuple(drop_data_->url,
drop_data_->url_title);
}
}
if (data_requests_ == 0) {
// Tell the renderer about the drag.
// |x| and |y| are seemingly arbitrary at this point.
tab_contents_->render_view_host()->
DragTargetDragEnter(*drop_data_.get(),
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
gtk_dnd_util::GdkDragActionToWebDragOp(context->actions));
// This is non-null if tab_contents_ is showing an ExtensionDOMUI with
// support for (at the moment experimental) drag and drop extensions.
if (tab_contents_->GetBookmarkDragDelegate()) {
tab_contents_->GetBookmarkDragDelegate()->OnDragEnter(
bookmark_drag_data_);
}
drag_over_time_ = time;
}
}
// The drag has left our widget; forward this information to the renderer.
void WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,
guint time) {
// Set |context_| to NULL to make sure we will recognize the next DragMotion
// as an enter.
context_ = NULL;
drop_data_.reset();
// When GTK sends us a drag-drop signal, it is shortly (and synchronously)
// preceded by a drag-leave. The renderer doesn't like getting the signals
// in this order so delay telling it about the drag-leave till we are sure
// we are not getting a drop as well.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));
}
// Called by GTK when the user releases the mouse, executing a drop.
gboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,
gint x, gint y, guint time) {
// Cancel that drag leave!
method_factory_.RevokeAll();
tab_contents_->render_view_host()->
DragTargetDrop(gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_));
// This is non-null if tab_contents_ is showing an ExtensionDOMUI with
// support for (at the moment experimental) drag and drop extensions.
if (tab_contents_->GetBookmarkDragDelegate())
tab_contents_->GetBookmarkDragDelegate()->OnDrop(bookmark_drag_data_);
// The second parameter is just an educated guess as to whether or not the
// drag succeeded, but at least we will get the drag-end animation right
// sometimes.
gtk_drag_finish(context, is_drop_target_, FALSE, time);
return TRUE;
}
<commit_msg>GTK: don't accept DnD drops of size 0 in the render view.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/tab_contents/web_drag_dest_gtk.h"
#include <string>
#include "app/gtk_dnd_util.h"
#include "base/file_path.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/gtk/bookmark_utils_gtk.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "net/base/net_util.h"
using WebKit::WebDragOperation;
using WebKit::WebDragOperationNone;
WebDragDestGtk::WebDragDestGtk(TabContents* tab_contents, GtkWidget* widget)
: tab_contents_(tab_contents),
widget_(widget),
context_(NULL),
method_factory_(this) {
gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),
NULL, 0,
static_cast<GdkDragAction>(GDK_ACTION_COPY |
GDK_ACTION_LINK |
GDK_ACTION_MOVE));
g_signal_connect(widget, "drag-motion",
G_CALLBACK(OnDragMotionThunk), this);
g_signal_connect(widget, "drag-leave",
G_CALLBACK(OnDragLeaveThunk), this);
g_signal_connect(widget, "drag-drop",
G_CALLBACK(OnDragDropThunk), this);
g_signal_connect(widget, "drag-data-received",
G_CALLBACK(OnDragDataReceivedThunk), this);
// TODO(tony): Need a drag-data-delete handler for moving content out of
// the tab contents. http://crbug.com/38989
destroy_handler_ = g_signal_connect(
widget, "destroy", G_CALLBACK(gtk_widget_destroyed), &widget_);
}
WebDragDestGtk::~WebDragDestGtk() {
if (widget_) {
gtk_drag_dest_unset(widget_);
g_signal_handler_disconnect(widget_, destroy_handler_);
}
}
void WebDragDestGtk::UpdateDragStatus(WebDragOperation operation) {
if (context_) {
is_drop_target_ = operation != WebDragOperationNone;
gdk_drag_status(context_, gtk_dnd_util::WebDragOpToGdkDragAction(operation),
drag_over_time_);
}
}
void WebDragDestGtk::DragLeave() {
tab_contents_->render_view_host()->DragTargetDragLeave();
if (tab_contents_->GetBookmarkDragDelegate()) {
tab_contents_->GetBookmarkDragDelegate()->OnDragLeave(bookmark_drag_data_);
}
}
gboolean WebDragDestGtk::OnDragMotion(GtkWidget* sender,
GdkDragContext* context,
gint x, gint y,
guint time) {
if (context_ != context) {
context_ = context;
drop_data_.reset(new WebDropData);
bookmark_drag_data_.Clear();
is_drop_target_ = false;
static int supported_targets[] = {
gtk_dnd_util::TEXT_PLAIN,
gtk_dnd_util::TEXT_URI_LIST,
gtk_dnd_util::TEXT_HTML,
gtk_dnd_util::NETSCAPE_URL,
gtk_dnd_util::CHROME_NAMED_URL,
gtk_dnd_util::CHROME_BOOKMARK_ITEM,
// TODO(estade): support image drags?
};
data_requests_ = arraysize(supported_targets);
for (size_t i = 0; i < arraysize(supported_targets); ++i) {
gtk_drag_get_data(widget_, context,
gtk_dnd_util::GetAtomForTarget(supported_targets[i]),
time);
}
} else if (data_requests_ == 0) {
tab_contents_->render_view_host()->
DragTargetDragOver(
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
gtk_dnd_util::GdkDragActionToWebDragOp(context->actions));
if (tab_contents_->GetBookmarkDragDelegate())
tab_contents_->GetBookmarkDragDelegate()->OnDragOver(bookmark_drag_data_);
drag_over_time_ = time;
}
// Pretend we are a drag destination because we don't want to wait for
// the renderer to tell us if we really are or not.
return TRUE;
}
void WebDragDestGtk::OnDragDataReceived(
GtkWidget* sender, GdkDragContext* context, gint x, gint y,
GtkSelectionData* data, guint info, guint time) {
// We might get the data from an old get_data() request that we no longer
// care about.
if (context != context_)
return;
data_requests_--;
// Decode the data.
if (data->data && data->length > 0) {
// If the source can't provide us with valid data for a requested target,
// data->data will be NULL.
if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN)) {
guchar* text = gtk_selection_data_get_text(data);
if (text) {
drop_data_->plain_text =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(text),
data->length));
g_free(text);
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_URI_LIST)) {
gchar** uris = gtk_selection_data_get_uris(data);
if (uris) {
for (gchar** uri_iter = uris; *uri_iter; uri_iter++) {
// TODO(estade): Can the filenames have a non-UTF8 encoding?
FilePath file_path;
if (net::FileURLToFilePath(GURL(*uri_iter), &file_path))
drop_data_->filenames.push_back(UTF8ToUTF16(file_path.value()));
}
// Also, write the first URI as the URL.
if (uris[0])
drop_data_->url = GURL(uris[0]);
g_strfreev(uris);
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML)) {
// TODO(estade): Can the html have a non-UTF8 encoding?
drop_data_->text_html =
UTF8ToUTF16(std::string(reinterpret_cast<char*>(data->data),
data->length));
// We leave the base URL empty.
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL)) {
std::string netscape_url(reinterpret_cast<char*>(data->data),
data->length);
size_t split = netscape_url.find_first_of('\n');
if (split != std::string::npos) {
drop_data_->url = GURL(netscape_url.substr(0, split));
if (split < netscape_url.size() - 1)
drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1));
}
} else if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL)) {
gtk_dnd_util::ExtractNamedURL(data,
&drop_data_->url, &drop_data_->url_title);
}
}
// For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source
// doesn't have any data available for us. In this case we try to synthesize a
// URL bookmark.
if (data->target ==
gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::CHROME_BOOKMARK_ITEM)) {
if (data->data && data->length > 0) {
bookmark_drag_data_.ReadFromVector(
bookmark_utils::GetNodesFromSelection(
NULL, data,
gtk_dnd_util::CHROME_BOOKMARK_ITEM,
tab_contents_->profile(), NULL, NULL));
bookmark_drag_data_.SetOriginatingProfile(tab_contents_->profile());
} else {
bookmark_drag_data_.ReadFromTuple(drop_data_->url,
drop_data_->url_title);
}
}
if (data_requests_ == 0) {
// Tell the renderer about the drag.
// |x| and |y| are seemingly arbitrary at this point.
tab_contents_->render_view_host()->
DragTargetDragEnter(*drop_data_.get(),
gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_),
gtk_dnd_util::GdkDragActionToWebDragOp(context->actions));
// This is non-null if tab_contents_ is showing an ExtensionDOMUI with
// support for (at the moment experimental) drag and drop extensions.
if (tab_contents_->GetBookmarkDragDelegate()) {
tab_contents_->GetBookmarkDragDelegate()->OnDragEnter(
bookmark_drag_data_);
}
drag_over_time_ = time;
}
}
// The drag has left our widget; forward this information to the renderer.
void WebDragDestGtk::OnDragLeave(GtkWidget* sender, GdkDragContext* context,
guint time) {
// Set |context_| to NULL to make sure we will recognize the next DragMotion
// as an enter.
context_ = NULL;
drop_data_.reset();
// When GTK sends us a drag-drop signal, it is shortly (and synchronously)
// preceded by a drag-leave. The renderer doesn't like getting the signals
// in this order so delay telling it about the drag-leave till we are sure
// we are not getting a drop as well.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&WebDragDestGtk::DragLeave));
}
// Called by GTK when the user releases the mouse, executing a drop.
gboolean WebDragDestGtk::OnDragDrop(GtkWidget* sender, GdkDragContext* context,
gint x, gint y, guint time) {
// Cancel that drag leave!
method_factory_.RevokeAll();
tab_contents_->render_view_host()->
DragTargetDrop(gtk_util::ClientPoint(widget_),
gtk_util::ScreenPoint(widget_));
// This is non-null if tab_contents_ is showing an ExtensionDOMUI with
// support for (at the moment experimental) drag and drop extensions.
if (tab_contents_->GetBookmarkDragDelegate())
tab_contents_->GetBookmarkDragDelegate()->OnDrop(bookmark_drag_data_);
// The second parameter is just an educated guess as to whether or not the
// drag succeeded, but at least we will get the drag-end animation right
// sometimes.
gtk_drag_finish(context, is_drop_target_, FALSE, time);
return TRUE;
}
<|endoftext|> |
<commit_before>/**
@file debug.hpp
@brief Debug utilities.
@author Tim Howard
@copyright 2010-2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef DUCT_DEBUG_HPP_
#define DUCT_DEBUG_HPP_
#include "./config.hpp"
#include <cstdlib>
#include <cstdarg>
#include <cassert>
#include <cstdio>
namespace duct {
/**
@addtogroup debug
@{
*/
#ifdef DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI
/**
@ingroup config
When defined, force all #DUCT_DEBUG and #DUCT_DEBUG_ASSERT
macros to be defined (regardless of @c NDEBUG presence).
*/
#define DUCT_CONFIG_FORCE_DEBUG_MACROS
#endif
/**
@name Non-debug assertion
@note These macros mimic @c assert(), and will @c std::abort()
the program if @a expr evaluates to @c false.
@note These macros are always defined.
@sa DUCT_DEBUG_ASSERT(),
DUCT_DEBUG_ASSERTE(),
DUCT_DEBUG_ASSERTF(),
DUCT_DEBUG_ASSERTP(),
DUCT_DEBUG_ASSERTPF()
*/ /// @{
/**
Assertion with message.
@param expr Expression to evaluate.
@param mesg Message.
*/
#define DUCT_ASSERT(expr, mesg) ( \
(expr) ? void(0) : ( \
std::fprintf( \
stderr, "assertion failure: " mesg \
"\n in %s:%d: %s: Assertion: `" #expr "`\n", \
__FILE__, __LINE__, DUCT_FUNC_SIG \
), \
std::abort() \
) \
)
/**
Assertion with expression.
@param expr Expression to evaluate.
*/
#define DUCT_ASSERTE(expr) ( \
(expr) ? void(0) : ( \
std::fprintf( \
stderr, "assertion failure " \
"in %s:%d: %s: `" #expr "`\n", \
__FILE__, __LINE__, DUCT_FUNC_SIG \
), \
std::abort() \
) \
)
/**
Assertion with formatted message.
@param expr Expression to evaluate.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_ASSERTF(expr, format, ...) ( \
(expr) ? void(0) : ( \
std::fprintf( \
stderr, "assertion failure: " format \
"\n in %s:%d: %s: Assertion: `" #expr "`\n", \
__VA_ARGS__, __FILE__, __LINE__, DUCT_FUNC_SIG \
), \
std::abort() \
) \
)
/**
Assertion with pointer and message.
@param expr Expression to evaluate.
@param p Pointer.
@param mesg Message.
*/
#define DUCT_ASSERTP(expr, p, mesg) \
DUCT_ASSERTF(expr, "[%p] " mesg, (void const* const)p)
/**
Assertion with pointer and formatted message.
@param expr Expression to evaluate.
@param p Pointer.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_ASSERTPF(expr, p, format, ...) \
DUCT_ASSERTF(expr, "[%p] " format, (void const* const)p, __VA_ARGS__)
/// @}
#if (defined(NDEBUG) && !defined(DUCT_CONFIG_FORCE_DEBUG_MACROS)) \
|| defined(DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI)
/** @name Message */ /// @{
/**
Print debug message.
@param mesg Debug message.
*/
#define DUCT_DEBUG(mesg)
/**
Print formatted debug message.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGF(format, ...)
/**
Print debug message with no newline.
@param mesg Debug message.
*/
#define DUCT_DEBUGN(mesg)
/**
Print formatted debug message with no newline.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGNF(format, ...)
/// @}
/** @name Message with function signature */ /// @{
/**
Print debug message with function signature.
@param mesg Debug message.
*/
#define DUCT_DEBUGC(mesg)
/**
Print formatted debug message with function signature.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGCF(format, ...)
/**
Print debug message with no newline and function signature.
@param mesg Debug message.
*/
#define DUCT_DEBUGNC(mesg)
/**
Print formatted debug message with no newline and function signature.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGNCF(format, ...)
/// @}
/** @name Message with function signature and pointer */ /// @{
/**
Print debug message with function signature and pointer.
@param mesg Debug message.
@param p Pointer.
*/
#define DUCT_DEBUGCP(p, mesg)
/**
Print formatted debug message with function signature and pointer.
@param p Pointer.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGCPF(p, format, ...)
/**
Print debug message with no newline, function signature, and pointer.
@param p Pointer.
@param mesg Debug message.
*/
#define DUCT_DEBUGNCP(p, mesg)
/**
Print formatted debug message with no newline, function signature,
and pointer.
@param p Pointer.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGNCPF(p, format, ...)
/// @}
/** @name Print function signature */ /// @{
/**
Print function signature.
*/
#define DUCT_DEBUG_CALLED()
/**
Print function signature with pointer.
@param p Pointer.
*/
#define DUCT_DEBUG_CALLEDP(p)
/// @}
/**
@name Debug assertion
@note These route to the non-debug assertion macros.
@sa DUCT_ASSERT(),
DUCT_ASSERTE(),
DUCT_ASSERTF(),
DUCT_ASSERTP(),
DUCT_ASSERTPF()
*/ /// @{
/** @copydoc DUCT_ASSERT() */
#define DUCT_DEBUG_ASSERT(expr, mesg)
/** @copydoc DUCT_ASSERTE() */
#define DUCT_DEBUG_ASSERTE(expr)
/** @copydoc DUCT_ASSERTF() */
#define DUCT_DEBUG_ASSERTF(expr, format, ...)
/** @copydoc DUCT_ASSERTP() */
#define DUCT_DEBUG_ASSERTP(expr, p, mesg)
/** @copydoc DUCT_ASSERTPF() */
#define DUCT_DEBUG_ASSERTPF(expr, p, format, ...)
/// @}
#else
#define DUCT_DEBUG_PREFIX__ "debug: "
// Debug
#define DUCT_DEBUG(mesg) \
std::printf(DUCT_DEBUG_PREFIX__ mesg "\n")
#define DUCT_DEBUGF(format, ...) \
std::printf(DUCT_DEBUG_PREFIX__ format "\n", __VA_ARGS__)
// - no newline
#define DUCT_DEBUGN(mesg) \
std::printf(DUCT_DEBUG_PREFIX__ mesg)
#define DUCT_DEBUGNF(format, ...) \
std::printf(DUCT_DEBUG_PREFIX__ format, __VA_ARGS__)
// - signature
#define DUCT_DEBUGC(mesg) \
DUCT_DEBUGF("in %s: " mesg, DUCT_FUNC_SIG)
#define DUCT_DEBUGCF(format, ...) \
DUCT_DEBUGF("in %s: " format, DUCT_FUNC_SIG, __VA_ARGS__)
// - signature and no newline
#define DUCT_DEBUGNC(mesg) \
DUCT_DEBUGNF("in %s: " mesg, DUCT_FUNC_SIG)
#define DUCT_DEBUGNCF(format, ...) \
DUCT_DEBUGNF("in %s: " format, DUCT_FUNC_SIG, __VA_ARGS__)
// - signature and pointer
#define DUCT_DEBUGCP(p, mesg) \
DUCT_DEBUGF("[%p] in %s: " mesg, (void const* const)p, DUCT_FUNC_SIG)
#define DUCT_DEBUGCPF(p, format, ...) \
DUCT_DEBUGF("[%p] in %s: " format, \
(void const* const)p, DUCT_FUNC_SIG, __VA_ARGS__)
// - signature and pointer and no newline
#define DUCT_DEBUGNCP(p, mesg) \
DUCT_DEBUGNF("[%p] in %s: " mesg, (void const* const)p, DUCT_FUNC_SIG)
#define DUCT_DEBUGNCPF(p, format, ...) \
DUCT_DEBUGNF("[%p] in %s: " format, \
(void const* const)p, DUCT_FUNC_SIG, __VA_ARGS__)
// Call
#define DUCT_DEBUG_CALLED() \
DUCT_DEBUGF("called: %s", DUCT_FUNC_SIG)
#define DUCT_DEBUG_CALLEDP(p) \
DUCT_DEBUGF("called: [%p] %s", (void const* const)p, DUCT_FUNC_SIG)
// Assert
#define DUCT_DEBUG_ASSERT(expr, mesg) \
DUCT_ASSERT(expr, mesg)
// Assert
#define DUCT_DEBUG_ASSERTE(expr) \
DUCT_ASSERTE(expr)
#define DUCT_DEBUG_ASSERTF(expr, format, ...) \
DUCT_ASSERTF(expr, format, __VA_ARGS__)
// - pointer
#define DUCT_DEBUG_ASSERTP(expr, p, mesg) \
DUCT_ASSERTP(expr, p, mesg)
#define DUCT_DEBUG_ASSERTPF(expr, p, format, ...) \
DUCT_ASSERTPF(expr, p, format, __VA_ARGS__)
#endif
/** @} */ // end doc-group debug
} // namespace duct
#endif // DUCT_DEBUG_HPP_
<commit_msg>debug: replaced C casts with C++ casts, doc & style tidy.<commit_after>/**
@file debug.hpp
@brief Debug utilities.
@author Tim Howard
@copyright 2010-2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef DUCT_DEBUG_HPP_
#define DUCT_DEBUG_HPP_
#include "./config.hpp"
#include <cstdlib>
#include <cstdarg>
#include <cassert>
#include <cstdio>
namespace duct {
/**
@addtogroup debug
@{
*/
#ifdef DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI
/**
@ingroup config
When defined, force all #DUCT_DEBUG and #DUCT_DEBUG_ASSERT
macros to be defined (regardless of @c NDEBUG presence).
*/
#define DUCT_CONFIG_FORCE_DEBUG_MACROS
#endif
/**
@name Non-debug assertion
@note These macros mimic @c assert(), and will @c std::abort()
the program if @a expr evaluates to @c false.
@note These macros are always defined.
@sa DUCT_DEBUG_ASSERT(),
DUCT_DEBUG_ASSERTE(),
DUCT_DEBUG_ASSERTF(),
DUCT_DEBUG_ASSERTP(),
DUCT_DEBUG_ASSERTPF()
*/ /// @{
/**
Assertion with message.
@param expr Expression to evaluate.
@param mesg Message.
*/
#define DUCT_ASSERT(expr, mesg) ( \
(expr) ? static_cast<void>(0) : ( \
std::fprintf( \
stderr, "assertion failure: " mesg \
"\n in %s:%d: %s: Assertion: `" #expr "`\n",\
__FILE__, __LINE__, DUCT_FUNC_SIG \
), \
std::abort() \
) \
)
/**
Assertion with expression.
@param expr Expression to evaluate.
*/
#define DUCT_ASSERTE(expr) ( \
(expr) ? static_cast<void>(0) : ( \
std::fprintf( \
stderr, "assertion failure " \
"in %s:%d: %s: `" #expr "`\n", \
__FILE__, __LINE__, DUCT_FUNC_SIG \
), \
std::abort() \
) \
)
/**
Assertion with formatted message.
@param expr Expression to evaluate.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_ASSERTF(expr, format, ...) ( \
(expr) ? static_cast<void>(0) : ( \
std::fprintf( \
stderr, "assertion failure: " format \
"\n in %s:%d: %s: Assertion: `" #expr "`\n", \
__VA_ARGS__, __FILE__, __LINE__, DUCT_FUNC_SIG \
), \
std::abort() \
) \
)
/**
Assertion with pointer and message.
@param expr Expression to evaluate.
@param p Pointer.
@param mesg Message.
*/
#define DUCT_ASSERTP(expr, p, mesg) \
DUCT_ASSERTF(expr, "[%p] " mesg, static_cast<void const* const>(p))
/**
Assertion with pointer and formatted message.
@param expr Expression to evaluate.
@param p Pointer.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_ASSERTPF(expr, p, format, ...) \
DUCT_ASSERTF(expr, "[%p] " format, \
static_cast<void const* const>(p), \
__VA_ARGS__ \
)
/// @}
#if (defined(NDEBUG) && !defined(DUCT_CONFIG_FORCE_DEBUG_MACROS)) \
|| (defined(DOXYGEN_CONSISTS_SOLELY_OF_UNICORNS_AND_CONFETTI))
/** @name Message */ /// @{
/**
Print debug message.
@param mesg Debug message.
*/
#define DUCT_DEBUG(mesg)
/**
Print formatted debug message.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGF(format, ...)
/**
Print debug message with no newline.
@param mesg Debug message.
*/
#define DUCT_DEBUGN(mesg)
/**
Print formatted debug message with no newline.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGNF(format, ...)
/// @}
/** @name Message with function signature */ /// @{
/**
Print debug message with function signature.
@param mesg Debug message.
*/
#define DUCT_DEBUGC(mesg)
/**
Print formatted debug message with function signature.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGCF(format, ...)
/**
Print debug message with no newline and function signature.
@param mesg Debug message.
*/
#define DUCT_DEBUGNC(mesg)
/**
Print formatted debug message with no newline and function
signature.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGNCF(format, ...)
/// @}
/** @name Message with function signature and pointer */ /// @{
/**
Print debug message with function signature and pointer.
@param mesg Debug message.
@param p Pointer.
*/
#define DUCT_DEBUGCP(p, mesg)
/**
Print formatted debug message with function signature and
pointer.
@param p Pointer.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGCPF(p, format, ...)
/**
Print debug message with no newline, function signature, and
pointer.
@param p Pointer.
@param mesg Debug message.
*/
#define DUCT_DEBUGNCP(p, mesg)
/**
Print formatted debug message with no newline, function
signature, and pointer.
@param p Pointer.
@param format Format string.
@param ... Format arguments.
*/
#define DUCT_DEBUGNCPF(p, format, ...)
/// @}
/** @name Print function signature */ /// @{
/**
Print function signature.
*/
#define DUCT_DEBUG_CALLED()
/**
Print function signature with pointer.
@param p Pointer.
*/
#define DUCT_DEBUG_CALLEDP(p)
/// @}
/**
@name Debug assertion
@note These route to the non-debug assertion macros.
@sa DUCT_ASSERT(),
DUCT_ASSERTE(),
DUCT_ASSERTF(),
DUCT_ASSERTP(),
DUCT_ASSERTPF()
*/ /// @{
/** @copydoc DUCT_ASSERT() */
#define DUCT_DEBUG_ASSERT(expr, mesg)
/** @copydoc DUCT_ASSERTE() */
#define DUCT_DEBUG_ASSERTE(expr)
/** @copydoc DUCT_ASSERTF() */
#define DUCT_DEBUG_ASSERTF(expr, format, ...)
/** @copydoc DUCT_ASSERTP() */
#define DUCT_DEBUG_ASSERTP(expr, p, mesg)
/** @copydoc DUCT_ASSERTPF() */
#define DUCT_DEBUG_ASSERTPF(expr, p, format, ...)
/// @}
#else
#define DUCT_DEBUG_PREFIX__ "debug: "
// Debug
#define DUCT_DEBUG(mesg) \
std::printf(DUCT_DEBUG_PREFIX__ mesg "\n")
#define DUCT_DEBUGF(format, ...) \
std::printf(DUCT_DEBUG_PREFIX__ format "\n", __VA_ARGS__)
// - no newline
#define DUCT_DEBUGN(mesg) \
std::printf(DUCT_DEBUG_PREFIX__ mesg)
#define DUCT_DEBUGNF(format, ...) \
std::printf(DUCT_DEBUG_PREFIX__ format, __VA_ARGS__)
// - signature
#define DUCT_DEBUGC(mesg) \
DUCT_DEBUGF("in %s: " mesg, DUCT_FUNC_SIG)
#define DUCT_DEBUGCF(format, ...) \
DUCT_DEBUGF("in %s: " format, \
DUCT_FUNC_SIG, \
__VA_ARGS__ \
)
// - signature and no newline
#define DUCT_DEBUGNC(mesg) \
DUCT_DEBUGNF("in %s: " mesg, DUCT_FUNC_SIG)
#define DUCT_DEBUGNCF(format, ...) \
DUCT_DEBUGNF("in %s: " format, \
DUCT_FUNC_SIG, \
__VA_ARGS__ \
)
// - signature and pointer
#define DUCT_DEBUGCP(p, mesg) \
DUCT_DEBUGF("[%p] in %s: " mesg, \
static_cast<void const* const>(p), \
DUCT_FUNC_SIG \
)
#define DUCT_DEBUGCPF(p, format, ...) \
DUCT_DEBUGF("[%p] in %s: " format, \
static_cast<void const* const>(p), \
DUCT_FUNC_SIG, \
__VA_ARGS__ \
)
// - signature and pointer and no newline
#define DUCT_DEBUGNCP(p, mesg) \
DUCT_DEBUGNF("[%p] in %s: " mesg, \
static_cast<void const* const>(p), \
DUCT_FUNC_SIG \
)
#define DUCT_DEBUGNCPF(p, format, ...) \
DUCT_DEBUGNF("[%p] in %s: " format, \
static_cast<void const* const>(p), \
DUCT_FUNC_SIG, \
__VA_ARGS__ \
)
// Call
#define DUCT_DEBUG_CALLED() \
DUCT_DEBUGF("called: %s", DUCT_FUNC_SIG)
#define DUCT_DEBUG_CALLEDP(p) \
DUCT_DEBUGF("called: [%p] %s", \
static_cast<void const* const>(p), \
DUCT_FUNC_SIG \
)
// Assert
#define DUCT_DEBUG_ASSERT(expr, mesg) \
DUCT_ASSERT(expr, mesg)
// Assert
#define DUCT_DEBUG_ASSERTE(expr) \
DUCT_ASSERTE(expr)
#define DUCT_DEBUG_ASSERTF(expr, format, ...) \
DUCT_ASSERTF(expr, format, __VA_ARGS__)
// - pointer
#define DUCT_DEBUG_ASSERTP(expr, p, mesg) \
DUCT_ASSERTP(expr, p, mesg)
#define DUCT_DEBUG_ASSERTPF(expr, p, format, ...) \
DUCT_ASSERTPF(expr, p, format, __VA_ARGS__)
#endif
/** @} */ // end doc-group debug
} // namespace duct
#endif // DUCT_DEBUG_HPP_
<|endoftext|> |
<commit_before>#include "qutils/ScreenHelper.h"
// Qt
#include <QGuiApplication>
#include <QScreen>
// zmc
#include "qutils/Macros.h"
namespace zmc
{
ScreenHelper::ScreenHelper(QObject *parent)
: QObject(parent)
, m_DPI(QGuiApplication::primaryScreen()->physicalDotsPerInch())
{
}
qreal ScreenHelper::dp(const qreal &size)
{
#if defined(Q_OS_DESKTOP)
return round(size * (m_DPI / 90.0));
#elif defined(Q_OS_ANDROID)
return round(size * (m_DPI / 160.0));
#endif // Platform Check
}
}
<commit_msg>Refactor<commit_after>#include "qutils/ScreenHelper.h"
// Qt
#include <QGuiApplication>
#include <QScreen>
// zmc
#include "qutils/Macros.h"
namespace zmc
{
ScreenHelper::ScreenHelper(QObject *parent)
: QObject(parent)
, m_DPI(QGuiApplication::primaryScreen()->physicalDotsPerInch())
{
}
qreal ScreenHelper::dp(const qreal &size)
{
qreal newSize = size;
#if defined(Q_OS_DESKTOP)
if (m_DPI <= 90) {
newSize = round(size * (m_DPI / 90.0));
}
#elif defined(Q_OS_ANDROID)
newSize = round(size * (m_DPI / 160.0));
#endif // Platform Check
return newSize;
}
}
<|endoftext|> |
<commit_before>/*
* Author: Yevgeniy Kiveish <yevgeniy.kiveisha@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice 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 "jhd1313m1.h"
int
main(int argc, char **argv)
{
//! [Interesting]
// 0x62 RGB_ADDRESS, 0x3E LCD_ADDRESS
upm::Jhd1313m1 *lcd = new upm::Jhd1313m1(0, 0x3E, 0x62);
lcd->setCursor(0,0);
lcd->write("Hello World");
lcd->setCursor(1,2);
lcd->write("Hello World");
delete lcd;
//! [Interesting]
return 0;
}
<commit_msg>lcd: jhd1313m1 example: sleep a bit so we can see the display<commit_after>/*
* Author: Yevgeniy Kiveish <yevgeniy.kiveisha@intel.com>
* Copyright (c) 2014 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice 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 "jhd1313m1.h"
int
main(int argc, char **argv)
{
//! [Interesting]
// 0x62 RGB_ADDRESS, 0x3E LCD_ADDRESS
upm::Jhd1313m1 *lcd = new upm::Jhd1313m1(0, 0x3E, 0x62);
lcd->setCursor(0,0);
lcd->write("Hello World");
lcd->setCursor(1,2);
lcd->write("Hello World");
printf("Sleeping for 5 seconds\n");
sleep(5);
delete lcd;
//! [Interesting]
return 0;
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OgreRenderingModule.h"
#include "Renderer.h"
#include "EC_Placeable.h"
#include "Entity.h"
#include <Ogre.h>
#include <QDebug>
using namespace OgreRenderer;
void SetShowBoundingBoxRecursive(Ogre::SceneNode* node, bool enable)
{
if (!node)
return;
node->showBoundingBox(enable);
int numChildren = node->numChildren();
for (int i = 0; i < numChildren; ++i)
{
Ogre::SceneNode* childNode = dynamic_cast<Ogre::SceneNode*>(node->getChild(i));
if (childNode)
SetShowBoundingBoxRecursive(childNode, enable);
}
}
EC_Placeable::EC_Placeable(IModule* module) :
IComponent(module->GetFramework()),
renderer_(checked_static_cast<OgreRenderingModule*>(module)->GetRenderer()),
scene_node_(0),
link_scene_node_(0),
attached_(false),
select_priority_(0),
transform(this, "Transform"),
drawDebug(this, "Show bounding box", false)
{
RendererPtr renderer = renderer_.lock();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
link_scene_node_ = scene_mgr->createSceneNode();
scene_node_ = scene_mgr->createSceneNode();
link_scene_node_->addChild(scene_node_);
// In case the placeable is used for camera control, set fixed yaw axis
link_scene_node_->setFixedYawAxis(true, Ogre::Vector3::UNIT_Z);
// Hook the transform attribute change
connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
SLOT(HandleAttributeChanged(IAttribute*, AttributeChange::Type)));
connect(this, SIGNAL(ParentEntitySet()), SLOT(RegisterActions()));
AttachNode();
}
EC_Placeable::~EC_Placeable()
{
if (renderer_.expired())
return;
RendererPtr renderer = renderer_.lock();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
if (scene_node_ && link_scene_node_)
{
link_scene_node_->removeChild(scene_node_);
}
if (scene_node_)
{
scene_mgr->destroySceneNode(scene_node_);
scene_node_ = 0;
}
if (link_scene_node_)
{
DetachNode();
scene_mgr->destroySceneNode(link_scene_node_);
link_scene_node_ = 0;
}
}
void EC_Placeable::SetParent(ComponentPtr placeable)
{
if ((placeable.get() != 0) && (!dynamic_cast<EC_Placeable*>(placeable.get())))
{
OgreRenderingModule::LogError("Attempted to set parent placeable which is not " + TypeNameStatic().toStdString());
return;
}
DetachNode();
parent_ = placeable;
AttachNode();
}
Vector3df EC_Placeable::GetPosition() const
{
const Ogre::Vector3& pos = link_scene_node_->getPosition();
return Vector3df(pos.x, pos.y, pos.z);
}
Quaternion EC_Placeable::GetOrientation() const
{
const Ogre::Quaternion& orientation = link_scene_node_->getOrientation();
return Quaternion(orientation.x, orientation.y, orientation.z, orientation.w);
}
Vector3df EC_Placeable::GetScale() const
{
const Ogre::Vector3& scale = scene_node_->getScale();
return Vector3df(scale.x, scale.y, scale.z);
}
Vector3df EC_Placeable::GetLocalXAxis() const
{
const Ogre::Vector3& xaxis = link_scene_node_->getOrientation().xAxis();
return Vector3df(xaxis.x, xaxis.y, xaxis.z);
}
QVector3D EC_Placeable::GetQLocalXAxis() const
{
Vector3df xaxis= GetLocalXAxis();
return QVector3D(xaxis.x, xaxis.y, xaxis.z);
}
Vector3df EC_Placeable::GetLocalYAxis() const
{
const Ogre::Vector3& yaxis = link_scene_node_->getOrientation().yAxis();
return Vector3df(yaxis.x, yaxis.y, yaxis.z);
}
QVector3D EC_Placeable::GetQLocalYAxis() const
{
Vector3df yaxis= GetLocalYAxis();
return QVector3D(yaxis.x, yaxis.y, yaxis.z);
}
Vector3df EC_Placeable::GetLocalZAxis() const
{
const Ogre::Vector3& zaxis = link_scene_node_->getOrientation().zAxis();
return Vector3df(zaxis.x, zaxis.y, zaxis.z);
}
QVector3D EC_Placeable::GetQLocalZAxis() const
{
Vector3df zaxis= GetLocalZAxis();
return QVector3D(zaxis.x, zaxis.y, zaxis.z);
}
void EC_Placeable::SetPosition(const Vector3df& position)
{
link_scene_node_->setPosition(Ogre::Vector3(position.x, position.y, position.z));
}
void EC_Placeable::SetOrientation(const Quaternion& orientation)
{
link_scene_node_->setOrientation(Ogre::Quaternion(orientation.w, orientation.x, orientation.y, orientation.z));
}
void EC_Placeable::LookAt(const Vector3df& look_at)
{
// Don't rely on the stability of the lookat (since it uses previous orientation),
// so start in identity transform
link_scene_node_->setOrientation(Ogre::Quaternion::IDENTITY);
link_scene_node_->lookAt(Ogre::Vector3(look_at.x, look_at.y, look_at.z), Ogre::Node::TS_WORLD);
}
void EC_Placeable::SetYaw(float radians)
{
link_scene_node_->yaw(Ogre::Radian(radians), Ogre::Node::TS_WORLD);
}
void EC_Placeable::SetPitch(float radians)
{
link_scene_node_->pitch(Ogre::Radian(radians));
}
void EC_Placeable::SetRoll(float radians)
{
link_scene_node_->roll(Ogre::Radian(radians));
}
float EC_Placeable::GetYaw() const
{
const Ogre::Quaternion& orientation = link_scene_node_->getOrientation();
return orientation.getYaw().valueRadians();
}
float EC_Placeable::GetPitch() const
{
const Ogre::Quaternion& orientation = link_scene_node_->getOrientation();
return orientation.getPitch().valueRadians();
}
float EC_Placeable::GetRoll() const
{
const Ogre::Quaternion& orientation = link_scene_node_->getOrientation();
return orientation.getRoll().valueRadians();
}
void EC_Placeable::SetScale(const Vector3df& scale)
{
scene_node_->setScale(Ogre::Vector3(scale.x, scale.y, scale.z));
}
void EC_Placeable::AttachNode()
{
if (renderer_.expired())
return;
RendererPtr renderer = renderer_.lock();
if (attached_)
return;
Ogre::SceneNode* parent_node;
if (!parent_)
{
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
parent_node = scene_mgr->getRootSceneNode();
}
else
{
EC_Placeable* parent = checked_static_cast<EC_Placeable*>(parent_.get());
parent_node = parent->GetLinkSceneNode();
}
parent_node->addChild(link_scene_node_);
attached_ = true;
}
void EC_Placeable::DetachNode()
{
if (renderer_.expired())
return;
RendererPtr renderer = renderer_.lock();
if (!attached_)
return;
Ogre::SceneNode* parent_node;
if (!parent_)
{
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
parent_node = scene_mgr->getRootSceneNode();
}
else
{
EC_Placeable* parent = checked_static_cast<EC_Placeable*>(parent_.get());
parent_node = parent->GetLinkSceneNode();
}
parent_node->removeChild(link_scene_node_);
attached_ = false;
}
//experimental QVector3D acessors
QVector3D EC_Placeable::GetQPosition() const
{
//conversions, conversions, all around
//.. if this works, and QVector3D is good, we should consider porting Vector3df for that
Vector3df rexpos = GetPosition();
return QVector3D(rexpos.x, rexpos.y, rexpos.z);
}
void EC_Placeable::SetQPosition(const QVector3D newpos)
{
SetPosition(Vector3df(newpos.x(), newpos.y(), newpos.z()));
}
QQuaternion EC_Placeable::GetQOrientation() const
{
Quaternion rexort = GetOrientation();
return QQuaternion(rexort.w, rexort.x, rexort.y, rexort.z);
}
void EC_Placeable::SetQOrientation(const QQuaternion newort)
{
SetOrientation(Quaternion(newort.x(), newort.y(), newort.z(), newort.scalar()));
}
QVector3D EC_Placeable::GetQScale() const
{
Vector3df rexscale = GetScale();
return QVector3D(rexscale.x, rexscale.y, rexscale.z);
}
void EC_Placeable::SetQScale(const QVector3D newscale)
{
SetScale(Vector3df(newscale.x(), newscale.y(), newscale.z()));
}
QVector3D EC_Placeable::translate(int axis, float amount)
{
Ogre::Matrix3 m;
Ogre::Vector3 v;
float x, y, z;
x = y = z = 0.0;
m.SetColumn(0, link_scene_node_->getOrientation().xAxis());
m.SetColumn(1, link_scene_node_->getOrientation().yAxis());
m.SetColumn(2, link_scene_node_->getOrientation().zAxis());
switch(axis) {
case 0:
x = amount;
break;
case 1:
y = amount;
break;
case 2:
z = amount;
break;
default:
// nothing, don't translate
break;
}
link_scene_node_->translate(m, Ogre::Vector3(x, y, z), Ogre::Node::TS_LOCAL);
const Ogre::Vector3 newpos = link_scene_node_->getPosition();
return QVector3D(newpos.x, newpos.y, newpos.z);
}
void EC_Placeable::HandleAttributeChanged(IAttribute* attribute, AttributeChange::Type change)
{
if (attribute == &transform)
{
if (!link_scene_node_)
return;
const Transform& trans = transform.Get();
link_scene_node_->setPosition(trans.position.x, trans.position.y, trans.position.z);
Quaternion orientation(DEGTORAD * trans.rotation.x,
DEGTORAD * trans.rotation.y,
DEGTORAD * trans.rotation.z);
link_scene_node_->setOrientation(Ogre::Quaternion(orientation.w, orientation.x, orientation.y, orientation.z));
// Prevent Ogre exception from zero scale
Vector3df scale(trans.scale.x, trans.scale.y, trans.scale.z);
if (scale.x < 0.0000001f)
scale.x = 0.0000001f;
if (scale.y < 0.0000001f)
scale.y = 0.0000001f;
if (scale.z < 0.0000001f)
scale.z = 0.0000001f;
link_scene_node_->setScale(scale.x, scale.y, scale.z);
}
else if (attribute == &drawDebug)
{
SetShowBoundingBoxRecursive(link_scene_node_, drawDebug.Get());
}
}
void EC_Placeable::Show()
{
if (!link_scene_node_)
return;
link_scene_node_->setVisible(true);
}
void EC_Placeable::Hide()
{
if (!link_scene_node_)
return;
link_scene_node_->setVisible(false);
}
void EC_Placeable::ToggleVisibility()
{
if (!link_scene_node_)
return;
link_scene_node_->flipVisibility();
}
void EC_Placeable::RegisterActions()
{
Scene::Entity *entity = GetParentEntity();
assert(entity);
if (entity)
{
// Generic actions
entity->ConnectAction("ShowEntity", this, SLOT(Show()));
entity->ConnectAction("HideEntity", this, SLOT(Hide()));
entity->ConnectAction("ToggleEntity", this, SLOT(ToggleVisibility()));
}
}
<commit_msg>Added a check that position cannot be NaN. If it is Ogre will crash.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OgreRenderingModule.h"
#include "Renderer.h"
#include "EC_Placeable.h"
#include "Entity.h"
#include "RexNetworkUtils.h"
#include <Ogre.h>
#include <QDebug>
using namespace OgreRenderer;
void SetShowBoundingBoxRecursive(Ogre::SceneNode* node, bool enable)
{
if (!node)
return;
node->showBoundingBox(enable);
int numChildren = node->numChildren();
for (int i = 0; i < numChildren; ++i)
{
Ogre::SceneNode* childNode = dynamic_cast<Ogre::SceneNode*>(node->getChild(i));
if (childNode)
SetShowBoundingBoxRecursive(childNode, enable);
}
}
EC_Placeable::EC_Placeable(IModule* module) :
IComponent(module->GetFramework()),
renderer_(checked_static_cast<OgreRenderingModule*>(module)->GetRenderer()),
scene_node_(0),
link_scene_node_(0),
attached_(false),
select_priority_(0),
transform(this, "Transform"),
drawDebug(this, "Show bounding box", false)
{
RendererPtr renderer = renderer_.lock();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
link_scene_node_ = scene_mgr->createSceneNode();
scene_node_ = scene_mgr->createSceneNode();
link_scene_node_->addChild(scene_node_);
// In case the placeable is used for camera control, set fixed yaw axis
link_scene_node_->setFixedYawAxis(true, Ogre::Vector3::UNIT_Z);
// Hook the transform attribute change
connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
SLOT(HandleAttributeChanged(IAttribute*, AttributeChange::Type)));
connect(this, SIGNAL(ParentEntitySet()), SLOT(RegisterActions()));
AttachNode();
}
EC_Placeable::~EC_Placeable()
{
if (renderer_.expired())
return;
RendererPtr renderer = renderer_.lock();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
if (scene_node_ && link_scene_node_)
{
link_scene_node_->removeChild(scene_node_);
}
if (scene_node_)
{
scene_mgr->destroySceneNode(scene_node_);
scene_node_ = 0;
}
if (link_scene_node_)
{
DetachNode();
scene_mgr->destroySceneNode(link_scene_node_);
link_scene_node_ = 0;
}
}
void EC_Placeable::SetParent(ComponentPtr placeable)
{
if ((placeable.get() != 0) && (!dynamic_cast<EC_Placeable*>(placeable.get())))
{
OgreRenderingModule::LogError("Attempted to set parent placeable which is not " + TypeNameStatic().toStdString());
return;
}
DetachNode();
parent_ = placeable;
AttachNode();
}
Vector3df EC_Placeable::GetPosition() const
{
const Ogre::Vector3& pos = link_scene_node_->getPosition();
return Vector3df(pos.x, pos.y, pos.z);
}
Quaternion EC_Placeable::GetOrientation() const
{
const Ogre::Quaternion& orientation = link_scene_node_->getOrientation();
return Quaternion(orientation.x, orientation.y, orientation.z, orientation.w);
}
Vector3df EC_Placeable::GetScale() const
{
const Ogre::Vector3& scale = scene_node_->getScale();
return Vector3df(scale.x, scale.y, scale.z);
}
Vector3df EC_Placeable::GetLocalXAxis() const
{
const Ogre::Vector3& xaxis = link_scene_node_->getOrientation().xAxis();
return Vector3df(xaxis.x, xaxis.y, xaxis.z);
}
QVector3D EC_Placeable::GetQLocalXAxis() const
{
Vector3df xaxis= GetLocalXAxis();
return QVector3D(xaxis.x, xaxis.y, xaxis.z);
}
Vector3df EC_Placeable::GetLocalYAxis() const
{
const Ogre::Vector3& yaxis = link_scene_node_->getOrientation().yAxis();
return Vector3df(yaxis.x, yaxis.y, yaxis.z);
}
QVector3D EC_Placeable::GetQLocalYAxis() const
{
Vector3df yaxis= GetLocalYAxis();
return QVector3D(yaxis.x, yaxis.y, yaxis.z);
}
Vector3df EC_Placeable::GetLocalZAxis() const
{
const Ogre::Vector3& zaxis = link_scene_node_->getOrientation().zAxis();
return Vector3df(zaxis.x, zaxis.y, zaxis.z);
}
QVector3D EC_Placeable::GetQLocalZAxis() const
{
Vector3df zaxis= GetLocalZAxis();
return QVector3D(zaxis.x, zaxis.y, zaxis.z);
}
void EC_Placeable::SetPosition(const Vector3df& position)
{
if ( !RexTypes::IsValidPositionVector(position) )
return;
link_scene_node_->setPosition(Ogre::Vector3(position.x, position.y, position.z));
}
void EC_Placeable::SetOrientation(const Quaternion& orientation)
{
link_scene_node_->setOrientation(Ogre::Quaternion(orientation.w, orientation.x, orientation.y, orientation.z));
}
void EC_Placeable::LookAt(const Vector3df& look_at)
{
// Don't rely on the stability of the lookat (since it uses previous orientation),
// so start in identity transform
link_scene_node_->setOrientation(Ogre::Quaternion::IDENTITY);
link_scene_node_->lookAt(Ogre::Vector3(look_at.x, look_at.y, look_at.z), Ogre::Node::TS_WORLD);
}
void EC_Placeable::SetYaw(float radians)
{
link_scene_node_->yaw(Ogre::Radian(radians), Ogre::Node::TS_WORLD);
}
void EC_Placeable::SetPitch(float radians)
{
link_scene_node_->pitch(Ogre::Radian(radians));
}
void EC_Placeable::SetRoll(float radians)
{
link_scene_node_->roll(Ogre::Radian(radians));
}
float EC_Placeable::GetYaw() const
{
const Ogre::Quaternion& orientation = link_scene_node_->getOrientation();
return orientation.getYaw().valueRadians();
}
float EC_Placeable::GetPitch() const
{
const Ogre::Quaternion& orientation = link_scene_node_->getOrientation();
return orientation.getPitch().valueRadians();
}
float EC_Placeable::GetRoll() const
{
const Ogre::Quaternion& orientation = link_scene_node_->getOrientation();
return orientation.getRoll().valueRadians();
}
void EC_Placeable::SetScale(const Vector3df& scale)
{
scene_node_->setScale(Ogre::Vector3(scale.x, scale.y, scale.z));
}
void EC_Placeable::AttachNode()
{
if (renderer_.expired())
return;
RendererPtr renderer = renderer_.lock();
if (attached_)
return;
Ogre::SceneNode* parent_node;
if (!parent_)
{
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
parent_node = scene_mgr->getRootSceneNode();
}
else
{
EC_Placeable* parent = checked_static_cast<EC_Placeable*>(parent_.get());
parent_node = parent->GetLinkSceneNode();
}
parent_node->addChild(link_scene_node_);
attached_ = true;
}
void EC_Placeable::DetachNode()
{
if (renderer_.expired())
return;
RendererPtr renderer = renderer_.lock();
if (!attached_)
return;
Ogre::SceneNode* parent_node;
if (!parent_)
{
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
parent_node = scene_mgr->getRootSceneNode();
}
else
{
EC_Placeable* parent = checked_static_cast<EC_Placeable*>(parent_.get());
parent_node = parent->GetLinkSceneNode();
}
parent_node->removeChild(link_scene_node_);
attached_ = false;
}
//experimental QVector3D acessors
QVector3D EC_Placeable::GetQPosition() const
{
//conversions, conversions, all around
//.. if this works, and QVector3D is good, we should consider porting Vector3df for that
Vector3df rexpos = GetPosition();
return QVector3D(rexpos.x, rexpos.y, rexpos.z);
}
void EC_Placeable::SetQPosition(const QVector3D newpos)
{
SetPosition(Vector3df(newpos.x(), newpos.y(), newpos.z()));
}
QQuaternion EC_Placeable::GetQOrientation() const
{
Quaternion rexort = GetOrientation();
return QQuaternion(rexort.w, rexort.x, rexort.y, rexort.z);
}
void EC_Placeable::SetQOrientation(const QQuaternion newort)
{
SetOrientation(Quaternion(newort.x(), newort.y(), newort.z(), newort.scalar()));
}
QVector3D EC_Placeable::GetQScale() const
{
Vector3df rexscale = GetScale();
return QVector3D(rexscale.x, rexscale.y, rexscale.z);
}
void EC_Placeable::SetQScale(const QVector3D newscale)
{
SetScale(Vector3df(newscale.x(), newscale.y(), newscale.z()));
}
QVector3D EC_Placeable::translate(int axis, float amount)
{
Ogre::Matrix3 m;
Ogre::Vector3 v;
float x, y, z;
x = y = z = 0.0;
m.SetColumn(0, link_scene_node_->getOrientation().xAxis());
m.SetColumn(1, link_scene_node_->getOrientation().yAxis());
m.SetColumn(2, link_scene_node_->getOrientation().zAxis());
switch(axis) {
case 0:
x = amount;
break;
case 1:
y = amount;
break;
case 2:
z = amount;
break;
default:
// nothing, don't translate
break;
}
link_scene_node_->translate(m, Ogre::Vector3(x, y, z), Ogre::Node::TS_LOCAL);
const Ogre::Vector3 newpos = link_scene_node_->getPosition();
return QVector3D(newpos.x, newpos.y, newpos.z);
}
void EC_Placeable::HandleAttributeChanged(IAttribute* attribute, AttributeChange::Type change)
{
if (attribute == &transform)
{
if (!link_scene_node_)
return;
const Transform& trans = transform.Get();
link_scene_node_->setPosition(trans.position.x, trans.position.y, trans.position.z);
Quaternion orientation(DEGTORAD * trans.rotation.x,
DEGTORAD * trans.rotation.y,
DEGTORAD * trans.rotation.z);
link_scene_node_->setOrientation(Ogre::Quaternion(orientation.w, orientation.x, orientation.y, orientation.z));
// Prevent Ogre exception from zero scale
Vector3df scale(trans.scale.x, trans.scale.y, trans.scale.z);
if (scale.x < 0.0000001f)
scale.x = 0.0000001f;
if (scale.y < 0.0000001f)
scale.y = 0.0000001f;
if (scale.z < 0.0000001f)
scale.z = 0.0000001f;
link_scene_node_->setScale(scale.x, scale.y, scale.z);
}
else if (attribute == &drawDebug)
{
SetShowBoundingBoxRecursive(link_scene_node_, drawDebug.Get());
}
}
void EC_Placeable::Show()
{
if (!link_scene_node_)
return;
link_scene_node_->setVisible(true);
}
void EC_Placeable::Hide()
{
if (!link_scene_node_)
return;
link_scene_node_->setVisible(false);
}
void EC_Placeable::ToggleVisibility()
{
if (!link_scene_node_)
return;
link_scene_node_->flipVisibility();
}
void EC_Placeable::RegisterActions()
{
Scene::Entity *entity = GetParentEntity();
assert(entity);
if (entity)
{
// Generic actions
entity->ConnectAction("ShowEntity", this, SLOT(Show()));
entity->ConnectAction("HideEntity", this, SLOT(Hide()));
entity->ConnectAction("ToggleEntity", this, SLOT(ToggleVisibility()));
}
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "XMLRPCConnection.h"
#include "curl/curl.h"
#include <vector>
XMLRPCConnection::XMLRPCConnection(const std::string& address, const std::string& port)
{
Poco::URI uri = Poco::URI(address);
uri.setPort( boost::lexical_cast<int>(port) );
strUrl_ = uri.toString();
}
/**
* Sets server address.
* @param address is server address.
* @param port is server port.
*/
void XMLRPCConnection::SetServerAddress(const std::string& address, const std::string& port)
{
Poco::URI uri = Poco::URI(address);
uri.setPort( boost::lexical_cast<int>(port) );
strUrl_ = uri.toString();
}
/// The writer callback function used by cURL.
size_t WriteCallback(char *data, size_t size, size_t nmemb, std::vector<char> *buffer)
{
if (buffer)
{
buffer->insert(buffer->end(), data, data + size * nmemb);
return size * nmemb;
}
else
return 0;
}
XMLRPC_REQUEST XMLRPCConnection::Send(const char* data)
{
curl_global_init(CURL_GLOBAL_ALL);
CURL *pCurl = curl_easy_init();
if (pCurl == 0)
throw XMLRPCException(std::string("XMLRPCEPI exception in XMLRPCConnection::Send()() error: Curl object was zero pointer"));
CURLcode result;
char curl_error_buffer[CURL_ERROR_SIZE];
curl_httppost* post = 0;
curl_httppost* last = 0;
curl_slist *headers = 0;
std::vector<char> response_data;
const unsigned int cTimeout = 5;
const char *url = strUrl_.c_str();
headers = curl_slist_append(headers, "Accept-Encoding: deflate, gzip");
headers = curl_slist_append(headers, "Content-Type: text/xml"); ///\todo Gets overriden with the default value.
headers = curl_slist_append(headers, "Expect: 100-continue");
headers = curl_slist_append(headers, "");
curl_formadd(&post, &last, CURLFORM_CONTENTHEADER, headers, CURLFORM_END);
curl_easy_setopt(pCurl, CURLOPT_URL, url);
curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, &data[0]);
curl_easy_setopt(pCurl, CURLOPT_POSTFIELDSIZE, strlen(data));
curl_easy_setopt(pCurl, CURLOPT_POST, 1);
curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, &response_data);
curl_easy_setopt(pCurl, CURLOPT_ERRORBUFFER, curl_error_buffer);
curl_easy_setopt(pCurl, CURLOPT_CONNECTTIMEOUT, cTimeout);
result = curl_easy_perform(pCurl);
// Clean up and free memory.
curl_easy_cleanup(pCurl);
curl_slist_free_all(headers);
curl_formfree(post);
if (result != CURLE_OK)
throw XMLRPCException(std::string("XMLRPCEPI exception in XMLRPCConnection::Send() Curl error: ")+ std::string(curl_error_buffer));
if (response_data.size() == 0)
throw XMLRPCException(std::string("XMLRPCEPI exception in XMLRPCConnection::Send() response data size was zero: "));
// Convert the XML string to a XMLRPC reply structure.
return XMLRPC_REQUEST_FromXML(&response_data[0], (int)(response_data.size()), 0);
}
<commit_msg>Add http:// to url begin if there is no protocol specified.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "XMLRPCConnection.h"
#include "curl/curl.h"
#include <vector>
#include <iostream>
XMLRPCConnection::XMLRPCConnection(const std::string& address, const std::string& port)
{
SetServerAddress(address, port);
}
/**
* Sets server address.
* @param address is server address.
* @param port is server port.
*/
void XMLRPCConnection::SetServerAddress(const std::string& address, const std::string& port)
{
std::string address_copy = address;
if (address_copy.find("://") == std::string::npos)
address_copy = "http://" + address_copy;
Poco::URI uri = Poco::URI(address_copy);
uri.setPort( boost::lexical_cast<int>(port) );
strUrl_ = uri.toString();
}
/// The writer callback function used by cURL.
size_t WriteCallback(char *data, size_t size, size_t nmemb, std::vector<char> *buffer)
{
if (buffer)
{
buffer->insert(buffer->end(), data, data + size * nmemb);
return size * nmemb;
}
else
return 0;
}
XMLRPC_REQUEST XMLRPCConnection::Send(const char* data)
{
curl_global_init(CURL_GLOBAL_ALL);
CURL *pCurl = curl_easy_init();
if (pCurl == 0)
throw XMLRPCException(std::string("XMLRPCEPI exception in XMLRPCConnection::Send()() error: Curl object was zero pointer"));
CURLcode result;
char curl_error_buffer[CURL_ERROR_SIZE];
curl_httppost* post = 0;
curl_httppost* last = 0;
curl_slist *headers = 0;
std::vector<char> response_data;
const unsigned int cTimeout = 5;
const char *url = strUrl_.c_str();
headers = curl_slist_append(headers, "Accept-Encoding: deflate, gzip");
headers = curl_slist_append(headers, "Content-Type: text/xml"); ///\todo Gets overriden with the default value.
headers = curl_slist_append(headers, "Expect: 100-continue");
headers = curl_slist_append(headers, "");
curl_formadd(&post, &last, CURLFORM_CONTENTHEADER, headers, CURLFORM_END);
curl_easy_setopt(pCurl, CURLOPT_URL, url);
curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, &data[0]);
curl_easy_setopt(pCurl, CURLOPT_POSTFIELDSIZE, strlen(data));
curl_easy_setopt(pCurl, CURLOPT_POST, 1);
curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, &response_data);
curl_easy_setopt(pCurl, CURLOPT_ERRORBUFFER, curl_error_buffer);
curl_easy_setopt(pCurl, CURLOPT_CONNECTTIMEOUT, cTimeout);
result = curl_easy_perform(pCurl);
// Clean up and free memory.
curl_easy_cleanup(pCurl);
curl_slist_free_all(headers);
curl_formfree(post);
if (result != CURLE_OK)
throw XMLRPCException(std::string("XMLRPCEPI exception in XMLRPCConnection::Send() Curl error: ")+ std::string(curl_error_buffer));
if (response_data.size() == 0)
throw XMLRPCException(std::string("XMLRPCEPI exception in XMLRPCConnection::Send() response data size was zero: "));
// Convert the XML string to a XMLRPC reply structure.
return XMLRPC_REQUEST_FromXML(&response_data[0], (int)(response_data.size()), 0);
}
<|endoftext|> |
<commit_before>#include <cassert>
#include "WorldData.h"
#include "WorldType.h"
#include "../Assets/INFFile.h"
#include "../Assets/MIFFile.h"
#include "../Media/TextureManager.h"
#include "../Rendering/Renderer.h"
WorldData::WorldData(const MIFFile &mif, const INFFile &inf, WorldType type)
{
// Generate levels.
for (const auto &level : mif.getLevels())
{
// Not sure yet how to differentiate a location between "interior" and "exterior".
// All interiors have ceilings except some main quest dungeons which have a 1
// as the third number after *CEILING in their .INF file.
const bool isInterior = [&inf, type, &level]()
{
if (type == WorldType::City)
{
return false;
}
else if (type == WorldType::Interior)
{
return !inf.getCeiling().outdoorDungeon;
}
else
{
return false;
}
}();
this->levels.push_back(LevelData(level, inf,
mif.getWidth(), mif.getDepth(), isInterior));
}
// Convert start points from the old coordinate system to the new one.
for (const auto &point : mif.getStartPoints())
{
this->startPoints.push_back(VoxelGrid::arenaVoxelToNewVoxel(
point, mif.getWidth(), mif.getDepth()));
}
this->currentLevel = mif.getStartingLevelIndex();
this->worldType = worldType;
}
WorldData::WorldData(VoxelGrid &&voxelGrid, EntityManager &&entityManager)
: entityManager(std::move(entityManager))
{
this->levels.push_back(LevelData(std::move(voxelGrid)));
this->currentLevel = 0;
}
WorldData::~WorldData()
{
}
int WorldData::getCurrentLevel() const
{
return this->currentLevel;
}
WorldType WorldData::getWorldType() const
{
return this->worldType;
}
EntityManager &WorldData::getEntityManager()
{
return this->entityManager;
}
const EntityManager &WorldData::getEntityManager() const
{
return this->entityManager;
}
const std::vector<Double2> &WorldData::getStartPoints() const
{
return this->startPoints;
}
std::vector<LevelData> &WorldData::getLevels()
{
return this->levels;
}
const std::vector<LevelData> &WorldData::getLevels() const
{
return this->levels;
}
void WorldData::switchToLevel(int levelIndex, TextureManager &textureManager,
Renderer &renderer)
{
assert(levelIndex < this->levels.size());
this->currentLevel = levelIndex;
// To do: refresh world state, textures, etc..
}
<commit_msg>Swapped grid X and Z dimensions.<commit_after>#include <cassert>
#include "WorldData.h"
#include "WorldType.h"
#include "../Assets/INFFile.h"
#include "../Assets/MIFFile.h"
#include "../Media/TextureManager.h"
#include "../Rendering/Renderer.h"
WorldData::WorldData(const MIFFile &mif, const INFFile &inf, WorldType type)
{
// Generate levels.
for (const auto &level : mif.getLevels())
{
// Not sure yet how to differentiate a location between "interior" and "exterior".
// All interiors have ceilings except some main quest dungeons which have a 1
// as the third number after *CEILING in their .INF file.
const bool isInterior = [&inf, type, &level]()
{
if (type == WorldType::City)
{
return false;
}
else if (type == WorldType::Interior)
{
return !inf.getCeiling().outdoorDungeon;
}
else
{
return false;
}
}();
this->levels.push_back(LevelData(level, inf,
mif.getDepth(), mif.getWidth(), isInterior));
}
// Convert start points from the old coordinate system to the new one.
for (const auto &point : mif.getStartPoints())
{
this->startPoints.push_back(VoxelGrid::arenaVoxelToNewVoxel(
point, mif.getDepth(), mif.getWidth()));
}
this->currentLevel = mif.getStartingLevelIndex();
this->worldType = worldType;
}
WorldData::WorldData(VoxelGrid &&voxelGrid, EntityManager &&entityManager)
: entityManager(std::move(entityManager))
{
this->levels.push_back(LevelData(std::move(voxelGrid)));
this->currentLevel = 0;
}
WorldData::~WorldData()
{
}
int WorldData::getCurrentLevel() const
{
return this->currentLevel;
}
WorldType WorldData::getWorldType() const
{
return this->worldType;
}
EntityManager &WorldData::getEntityManager()
{
return this->entityManager;
}
const EntityManager &WorldData::getEntityManager() const
{
return this->entityManager;
}
const std::vector<Double2> &WorldData::getStartPoints() const
{
return this->startPoints;
}
std::vector<LevelData> &WorldData::getLevels()
{
return this->levels;
}
const std::vector<LevelData> &WorldData::getLevels() const
{
return this->levels;
}
void WorldData::switchToLevel(int levelIndex, TextureManager &textureManager,
Renderer &renderer)
{
assert(levelIndex < this->levels.size());
this->currentLevel = levelIndex;
// To do: refresh world state, textures, etc..
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstring>
#include <cstdlib>
#include "dacloud.h"
using namespace std;
int
main(int argc, char *argv[]) {
if (argc < 3)
return (-1);
string configpath = argv[1];
string useragent = argv[2];
da_cloud_config config;
::memset(&config, 0, sizeof(config));
if (da_cloud_init(&config, configpath.c_str()) == 0) {
da_cloud_header_head head;
da_cloud_property_head phead;
da_cloud_header_init(&head);
da_cloud_header_add(&head, "user-agent", useragent.c_str());
if (da_cloud_detect(&config, &head, &phead) == 0) {
da_cloud_property *p;
SLIST_FOREACH(p, &phead.list, entries) {
da_cloud_property_type type = p->type;
cout << p->name << ": ";
switch (type) {
case DA_CLOUD_LONG:
cout << p->value.l;
break;
case DA_CLOUD_BOOL:
cout << p->value.l > 0 ? "true" : "false";
break;
case DA_CLOUD_STRING:
cout << p->value.s;
break;
}
cout << endl;
}
da_cloud_properties_free(&phead);
}
da_cloud_header_free(&head);
da_cloud_fini(&config);
}
return (0);
}
<commit_msg>parenthesis around ternary expression<commit_after>#include <iostream>
#include <cstring>
#include <cstdlib>
#include "dacloud.h"
using namespace std;
int
main(int argc, char *argv[]) {
if (argc < 3)
return (-1);
string configpath = argv[1];
string useragent = argv[2];
da_cloud_config config;
::memset(&config, 0, sizeof(config));
if (da_cloud_init(&config, configpath.c_str()) == 0) {
da_cloud_header_head head;
da_cloud_property_head phead;
da_cloud_header_init(&head);
da_cloud_header_add(&head, "user-agent", useragent.c_str());
if (da_cloud_detect(&config, &head, &phead) == 0) {
da_cloud_property *p;
SLIST_FOREACH(p, &phead.list, entries) {
da_cloud_property_type type = p->type;
cout << p->name << ": ";
switch (type) {
case DA_CLOUD_LONG:
cout << p->value.l;
break;
case DA_CLOUD_BOOL:
cout << (p->value.l > 0 ? "true" : "false");
break;
case DA_CLOUD_STRING:
cout << p->value.s;
break;
}
cout << endl;
}
da_cloud_properties_free(&phead);
}
da_cloud_header_free(&head);
da_cloud_fini(&config);
}
return (0);
}
<|endoftext|> |
<commit_before>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,image->t(), image->s(),0.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,0.0f, 1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
if (imagestream) imagestream->play();
if (image)
{
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
pos.z() += image->t()*1.5f;
}
else
{
std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
}
}
}
if (geode->getNumDrawables()==0)
{
// nothing loaded.
return 1;
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode.get());
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
// set the scene to render
viewer.setSceneData(geode.get());
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Removed the use of the post swap callback<commit_after>// -*-c++-*-
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/StateSet>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/TextureRectangle>
#include <osg/TexMat>
#include <osg/CullFace>
#include <osg/ImageStream>
#include <osgGA/TrackballManipulator>
osg::ImageStream* s_imageStream = 0;
class PostSwapFinishCallback : public Producer::Camera::Callback
{
public:
PostSwapFinishCallback() {}
virtual void operator()(const Producer::Camera& camera)
{
// osg::Timer_t start_tick = osg::Timer::instance()->tick();
osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));
if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));
// glFinish();
//osg::notify(osg::NOTICE)<<"callback after PBO "<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<"ms"<<std::endl;
}
};
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler() {}
void set(osg::Node* node);
virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='s')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
return true;
}
else if (ea.getKey()=='r')
{
return true;
}
else if (ea.getKey()=='l')
{
return true;
}
return false;
}
default:
return false;
}
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Pause movie");
usage.addKeyboardMouseBinding("s","Play movie");
usage.addKeyboardMouseBinding("r","Start movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image)
{
bool useTextureRectangle = true;
if (useTextureRectangle)
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,image->t(), image->s(),0.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::TextureRectangle(image),
osg::StateAttribute::ON);
return pictureQuad;
}
else
{
osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,
osg::Vec3(width,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,height),
0.0f,0.0f, 1.0f,1.0f);
pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,
new osg::Texture2D(image),
osg::StateAttribute::ON);
return pictureQuad;
}
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
// register the handler to add keyboard and mosue handling.
MovieEventHandler* meh = new MovieEventHandler();
viewer.getEventHandlerList().push_front(meh);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
osg::Vec3 pos(0.0f,0.0f,0.0f);
for(int i=1;i<arguments.argc();++i)
{
if (arguments.isString(i))
{
osg::Image* image = osgDB::readImageFile(arguments[i]);
osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);
if (imagestream) imagestream->play();
if (image)
{
geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image));
geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
pos.z() += image->t()*1.5f;
}
else
{
std::cout<<"Unable to read file "<<arguments[i]<<std::endl;
}
}
}
if (geode->getNumDrawables()==0)
{
// nothing loaded.
return 1;
}
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
meh->set(geode.get());
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
if (arguments.argc()<=1)
{
arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
}
/*
// set up a post swap callback to flush deleted GL objects and compile new GL objects
for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)
{
Producer::Camera* camera=viewer.getCamera(cameraNum);
camera->addPostSwapCallback(new PostSwapFinishCallback());
}
*/
// set the scene to render
viewer.setSceneData(geode.get());
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "base/assert.hpp"
#include "base/cancellable.hpp"
#include "base/logging.hpp"
#include "routing/base/graph.hpp"
#include "std/algorithm.hpp"
#include "std/functional.hpp"
#include "std/iostream.hpp"
#include "std/map.hpp"
#include "std/queue.hpp"
#include "std/vector.hpp"
namespace routing
{
template <typename TGraph>
class AStarAlgorithm : public my::Cancellable
{
public:
using TGraphType = TGraph;
using TVertexType = typename TGraphType::TVertexType;
using TEdgeType = typename TGraphType::TEdgeType;
static uint32_t const kCancelledPollPeriod;
static uint32_t const kQueueSwitchPeriod;
static uint32_t const kVisitedVerticesPeriod;
static double const kEpsilon;
enum class Result
{
OK,
NoPath,
Cancelled
};
friend ostream & operator<<(ostream & os, Result const & result)
{
switch (result)
{
case Result::OK:
os << "OK";
break;
case Result::NoPath:
os << "NoPath";
break;
case Result::Cancelled:
os << "Cancelled";
break;
}
return os;
}
AStarAlgorithm() : m_graph(nullptr) {}
using OnVisitedVertexCallback = std::function<void(TVertexType const&)>;
Result FindPath(TVertexType const & startVertex, TVertexType const & finalVertex,
vector<TVertexType> & path,
OnVisitedVertexCallback onVisitedVertexCallback = nullptr) const;
Result FindPathBidirectional(TVertexType const & startVertex, TVertexType const & finalVertex,
vector<TVertexType> & path,
OnVisitedVertexCallback onVisitedVertexCallback = nullptr) const;
void SetGraph(TGraph const & graph) { m_graph = &graph; }
private:
// State is what is going to be put in the priority queue. See the
// comment for FindPath for more information.
struct State
{
State(TVertexType const & vertex, double distance) : vertex(vertex), distance(distance) {}
inline bool operator>(State const & rhs) const { return distance > rhs.distance; }
TVertexType vertex;
double distance;
};
// BidirectionalStepContext keeps all the information that is needed to
// search starting from one of the two directions. Its main
// purpose is to make the code that changes directions more readable.
struct BidirectionalStepContext
{
BidirectionalStepContext(bool forward, TVertexType const & startVertex,
TVertexType const & finalVertex, TGraphType const & graph)
: forward(forward), startVertex(startVertex), finalVertex(finalVertex), graph(graph)
{
bestVertex = forward ? startVertex : finalVertex;
pS = ConsistentHeuristic(startVertex);
}
double TopDistance() const
{
ASSERT(!queue.empty(), ());
return bestDistance.at(queue.top().vertex);
}
// p_f(v) = 0.5*(π_f(v) - π_r(v)) + 0.5*π_r(t)
// p_r(v) = 0.5*(π_r(v) - π_f(v)) + 0.5*π_f(s)
// p_r(v) + p_f(v) = const. Note: this condition is called consistence.
double ConsistentHeuristic(TVertexType const & v) const
{
double piF = graph.HeuristicCostEstimate(v, finalVertex);
double piR = graph.HeuristicCostEstimate(v, startVertex);
double const piRT = graph.HeuristicCostEstimate(finalVertex, startVertex);
double const piFS = graph.HeuristicCostEstimate(startVertex, finalVertex);
if (forward)
{
/// @todo careful: with this "return" here and below in the Backward case
/// the heuristic becomes inconsistent but still seems to work.
/// return HeuristicCostEstimate(v, finalVertex);
return 0.5 * (piF - piR + piRT);
}
else
{
// return HeuristicCostEstimate(v, startVertex);
return 0.5 * (piR - piF + piFS);
}
}
void GetAdjacencyList(TVertexType const & v, vector<TEdgeType> & adj)
{
if (forward)
graph.GetOutgoingEdgesList(v, adj);
else
graph.GetIngoingEdgesList(v, adj);
}
bool const forward;
TVertexType const & startVertex;
TVertexType const & finalVertex;
TGraph const & graph;
priority_queue<State, vector<State>, greater<State>> queue;
map<TVertexType, double> bestDistance;
map<TVertexType, TVertexType> parent;
TVertexType bestVertex;
double pS;
};
static void ReconstructPath(TVertexType const & v, map<TVertexType, TVertexType> const & parent,
vector<TVertexType> & path);
static void ReconstructPathBidirectional(TVertexType const & v, TVertexType const & w,
map<TVertexType, TVertexType> const & parentV,
map<TVertexType, TVertexType> const & parentW,
vector<TVertexType> & path);
TGraphType const * m_graph;
};
// static
template <typename TGraph>
uint32_t const AStarAlgorithm<TGraph>::kCancelledPollPeriod = 128;
// static
template <typename TGraph>
uint32_t const AStarAlgorithm<TGraph>::kQueueSwitchPeriod = 128;
// static
template <typename TGraph>
uint32_t const AStarAlgorithm<TGraph>::kVisitedVerticesPeriod = 4;
// static
template <typename TGraph>
double const AStarAlgorithm<TGraph>::kEpsilon = 1e-6;
// This implementation is based on the view that the A* algorithm
// is equivalent to Dijkstra's algorithm that is run on a reweighted
// version of the graph. If an edge (v, w) has length l(v, w), its reduced
// cost is l_r(v, w) = l(v, w) + pi(w) - pi(v), where pi() is any function
// that ensures l_r(v, w) >= 0 for every edge. We set pi() to calculate
// the shortest possible distance to a goal node, and this is a common
// heuristic that people use in A*.
// Refer to this paper for more information:
// http://research.microsoft.com/pubs/154937/soda05.pdf
//
// The vertices of the graph are of type RoadPos.
// The edges of the graph are of type PossibleTurn.
template <typename TGraph>
typename AStarAlgorithm<TGraph>::Result AStarAlgorithm<TGraph>::FindPath(
TVertexType const & startVertex, TVertexType const & finalVertex,
vector<TVertexType> & path,
OnVisitedVertexCallback onVisitedVertexCallback) const
{
ASSERT(m_graph, ());
if (nullptr == onVisitedVertexCallback)
onVisitedVertexCallback = [](TVertexType const &){};
map<TVertexType, double> bestDistance;
priority_queue<State, vector<State>, greater<State>> queue;
map<TVertexType, TVertexType> parent;
bestDistance[finalVertex] = 0.0;
queue.push(State(finalVertex, 0.0));
vector<TEdgeType> adj;
uint32_t steps = 0;
while (!queue.empty())
{
++steps;
if (steps % kCancelledPollPeriod == 0 && IsCancelled())
return Result::Cancelled;
State const stateV = queue.top();
queue.pop();
if (stateV.distance > bestDistance[stateV.vertex])
continue;
if (steps % kVisitedVerticesPeriod == 0)
onVisitedVertexCallback(stateV.vertex);
if (stateV.vertex == startVertex)
{
ReconstructPath(stateV.vertex, parent, path);
return Result::OK;
}
m_graph->GetIngoingEdgesList(stateV.vertex, adj);
for (auto const & edge : adj)
{
State stateW(edge.GetTarget(), 0.0);
if (stateV.vertex == stateW.vertex)
continue;
double const len = edge.GetWeight();
double const piV = m_graph->HeuristicCostEstimate(stateV.vertex, startVertex);
double const piW = m_graph->HeuristicCostEstimate(stateW.vertex, startVertex);
double const reducedLen = len + piW - piV;
CHECK(reducedLen >= -kEpsilon, ("Invariant violated:", reducedLen, "<", -kEpsilon));
double const newReducedDist = stateV.distance + max(reducedLen, 0.0);
auto const t = bestDistance.find(stateW.vertex);
if (t != bestDistance.end() && newReducedDist >= t->second - kEpsilon)
continue;
stateW.distance = newReducedDist;
bestDistance[stateW.vertex] = newReducedDist;
parent[stateW.vertex] = stateV.vertex;
queue.push(stateW);
}
}
return Result::NoPath;
}
template <typename TGraph>
typename AStarAlgorithm<TGraph>::Result AStarAlgorithm<TGraph>::FindPathBidirectional(
TVertexType const & startVertex, TVertexType const & finalVertex,
vector<TVertexType> & path,
OnVisitedVertexCallback onVisitedVertexCallback) const
{
ASSERT(m_graph, ());
if (nullptr == onVisitedVertexCallback)
onVisitedVertexCallback = [](TVertexType const &){};
BidirectionalStepContext forward(true /* forward */, startVertex, finalVertex, *m_graph);
BidirectionalStepContext backward(false /* forward */, startVertex, finalVertex, *m_graph);
bool foundAnyPath = false;
double bestPathLength = 0.0;
forward.bestDistance[startVertex] = 0.0;
forward.queue.push(State(startVertex, 0.0 /* distance */));
backward.bestDistance[finalVertex] = 0.0;
backward.queue.push(State(finalVertex, 0.0 /* distance */));
// To use the search code both for backward and forward directions
// we keep the pointers to everything related to the search in the
// 'current' and 'next' directions. Swapping these pointers indicates
// changing the end we are searching from.
BidirectionalStepContext * cur = &forward;
BidirectionalStepContext * nxt = &backward;
vector<TEdgeType> adj;
// It is not necessary to check emptiness for both queues here
// because if we have not found a path by the time one of the
// queues is exhausted, we never will.
uint32_t steps = 0;
while (!cur->queue.empty() && !nxt->queue.empty())
{
++steps;
if (steps % kCancelledPollPeriod == 0 && IsCancelled())
return Result::Cancelled;
if (steps % kQueueSwitchPeriod == 0)
swap(cur, nxt);
double const curTop = cur->TopDistance();
double const nxtTop = nxt->TopDistance();
double const pTopV = cur->ConsistentHeuristic(cur->queue.top().vertex);
double const pTopW = nxt->ConsistentHeuristic(nxt->queue.top().vertex);
// The intuition behind this is that we cannot obtain a path shorter
// than the left side of the inequality because that is how any path we find
// will look like (see comment for curPathLength below).
// We do not yet have the proof that we will not miss a good path by doing so.
if (foundAnyPath &&
curTop + nxtTop - pTopV + cur->pS - pTopW + nxt->pS >= bestPathLength - kEpsilon)
{
ReconstructPathBidirectional(cur->bestVertex, nxt->bestVertex, cur->parent, nxt->parent,
path);
CHECK(!path.empty(), ());
if (!cur->forward)
reverse(path.begin(), path.end());
return Result::OK;
}
State const stateV = cur->queue.top();
cur->queue.pop();
if (stateV.distance > cur->bestDistance[stateV.vertex])
continue;
if (steps % kVisitedVerticesPeriod == 0)
onVisitedVertexCallback(stateV.vertex);
cur->GetAdjacencyList(stateV.vertex, adj);
for (auto const & edge : adj)
{
State stateW(edge.GetTarget(), 0.0);
if (stateV.vertex == stateW.vertex)
continue;
double const len = edge.GetWeight();
double const pV = cur->ConsistentHeuristic(stateV.vertex);
double const pW = cur->ConsistentHeuristic(stateW.vertex);
double const reducedLen = len + pW - pV;
double const pRW = nxt->ConsistentHeuristic(stateW.vertex);
CHECK(reducedLen >= -kEpsilon, ("Invariant violated:", reducedLen, "<", -kEpsilon));
double const newReducedDist = stateV.distance + max(reducedLen, 0.0);
auto const itCur = cur->bestDistance.find(stateW.vertex);
if (itCur != cur->bestDistance.end() && newReducedDist >= itCur->second - kEpsilon)
continue;
auto const itNxt = nxt->bestDistance.find(stateW.vertex);
if (itNxt != nxt->bestDistance.end())
{
double const distW = itNxt->second;
// Length that the path we've just found has in the original graph:
// find the length of the path's parts in the reduced forward and backward
// graphs and remove the heuristic adjustments.
double const curPathLength = newReducedDist + distW - pW + cur->pS - pRW + nxt->pS;
// No epsilon here: it is ok to overshoot slightly.
if (!foundAnyPath || bestPathLength > curPathLength)
{
bestPathLength = curPathLength;
foundAnyPath = true;
cur->bestVertex = stateV.vertex;
nxt->bestVertex = stateW.vertex;
}
}
stateW.distance = newReducedDist;
cur->bestDistance[stateW.vertex] = newReducedDist;
cur->parent[stateW.vertex] = stateV.vertex;
cur->queue.push(stateW);
}
}
return Result::NoPath;
}
// static
template <typename TGraph>
void AStarAlgorithm<TGraph>::ReconstructPath(TVertexType const & v,
map<TVertexType, TVertexType> const & parent,
vector<TVertexType> & path)
{
path.clear();
TVertexType cur = v;
while (true)
{
path.push_back(cur);
auto it = parent.find(cur);
if (it == parent.end())
break;
cur = it->second;
}
}
// static
template <typename TGraph>
void AStarAlgorithm<TGraph>::ReconstructPathBidirectional(
TVertexType const & v, TVertexType const & w, map<TVertexType, TVertexType> const & parentV,
map<TVertexType, TVertexType> const & parentW, vector<TVertexType> & path)
{
vector<TVertexType> pathV;
ReconstructPath(v, parentV, pathV);
vector<TVertexType> pathW;
ReconstructPath(w, parentW, pathW);
path.clear();
path.reserve(pathV.size() + pathW.size());
path.insert(path.end(), pathV.rbegin(), pathV.rend());
path.insert(path.end(), pathW.begin(), pathW.end());
}
} // namespace routing
<commit_msg>Fixed heuristic for the wave start point<commit_after>#pragma once
#include "base/assert.hpp"
#include "base/cancellable.hpp"
#include "base/logging.hpp"
#include "routing/base/graph.hpp"
#include "std/algorithm.hpp"
#include "std/functional.hpp"
#include "std/iostream.hpp"
#include "std/map.hpp"
#include "std/queue.hpp"
#include "std/vector.hpp"
namespace routing
{
template <typename TGraph>
class AStarAlgorithm : public my::Cancellable
{
public:
using TGraphType = TGraph;
using TVertexType = typename TGraphType::TVertexType;
using TEdgeType = typename TGraphType::TEdgeType;
static uint32_t const kCancelledPollPeriod;
static uint32_t const kQueueSwitchPeriod;
static uint32_t const kVisitedVerticesPeriod;
static double const kEpsilon;
enum class Result
{
OK,
NoPath,
Cancelled
};
friend ostream & operator<<(ostream & os, Result const & result)
{
switch (result)
{
case Result::OK:
os << "OK";
break;
case Result::NoPath:
os << "NoPath";
break;
case Result::Cancelled:
os << "Cancelled";
break;
}
return os;
}
AStarAlgorithm() : m_graph(nullptr) {}
using OnVisitedVertexCallback = std::function<void(TVertexType const&)>;
Result FindPath(TVertexType const & startVertex, TVertexType const & finalVertex,
vector<TVertexType> & path,
OnVisitedVertexCallback onVisitedVertexCallback = nullptr) const;
Result FindPathBidirectional(TVertexType const & startVertex, TVertexType const & finalVertex,
vector<TVertexType> & path,
OnVisitedVertexCallback onVisitedVertexCallback = nullptr) const;
void SetGraph(TGraph const & graph) { m_graph = &graph; }
private:
// State is what is going to be put in the priority queue. See the
// comment for FindPath for more information.
struct State
{
State(TVertexType const & vertex, double distance) : vertex(vertex), distance(distance) {}
inline bool operator>(State const & rhs) const { return distance > rhs.distance; }
TVertexType vertex;
double distance;
};
// BidirectionalStepContext keeps all the information that is needed to
// search starting from one of the two directions. Its main
// purpose is to make the code that changes directions more readable.
struct BidirectionalStepContext
{
BidirectionalStepContext(bool forward, TVertexType const & startVertex,
TVertexType const & finalVertex, TGraphType const & graph)
: forward(forward), startVertex(startVertex), finalVertex(finalVertex), graph(graph)
{
bestVertex = forward ? startVertex : finalVertex;
pS = ConsistentHeuristic(bestVertex);
}
double TopDistance() const
{
ASSERT(!queue.empty(), ());
return bestDistance.at(queue.top().vertex);
}
// p_f(v) = 0.5*(π_f(v) - π_r(v)) + 0.5*π_r(t)
// p_r(v) = 0.5*(π_r(v) - π_f(v)) + 0.5*π_f(s)
// p_r(v) + p_f(v) = const. Note: this condition is called consistence.
double ConsistentHeuristic(TVertexType const & v) const
{
double const piF = graph.HeuristicCostEstimate(v, finalVertex);
double const piR = graph.HeuristicCostEstimate(v, startVertex);
double const piRT = graph.HeuristicCostEstimate(finalVertex, startVertex);
double const piFS = graph.HeuristicCostEstimate(startVertex, finalVertex);
if (forward)
{
/// @todo careful: with this "return" here and below in the Backward case
/// the heuristic becomes inconsistent but still seems to work.
/// return HeuristicCostEstimate(v, finalVertex);
return 0.5 * (piF - piR + piRT);
}
else
{
// return HeuristicCostEstimate(v, startVertex);
return 0.5 * (piR - piF + piFS);
}
}
void GetAdjacencyList(TVertexType const & v, vector<TEdgeType> & adj)
{
if (forward)
graph.GetOutgoingEdgesList(v, adj);
else
graph.GetIngoingEdgesList(v, adj);
}
bool const forward;
TVertexType const & startVertex;
TVertexType const & finalVertex;
TGraph const & graph;
priority_queue<State, vector<State>, greater<State>> queue;
map<TVertexType, double> bestDistance;
map<TVertexType, TVertexType> parent;
TVertexType bestVertex;
double pS;
};
static void ReconstructPath(TVertexType const & v, map<TVertexType, TVertexType> const & parent,
vector<TVertexType> & path);
static void ReconstructPathBidirectional(TVertexType const & v, TVertexType const & w,
map<TVertexType, TVertexType> const & parentV,
map<TVertexType, TVertexType> const & parentW,
vector<TVertexType> & path);
TGraphType const * m_graph;
};
// static
template <typename TGraph>
uint32_t const AStarAlgorithm<TGraph>::kCancelledPollPeriod = 128;
// static
template <typename TGraph>
uint32_t const AStarAlgorithm<TGraph>::kQueueSwitchPeriod = 128;
// static
template <typename TGraph>
uint32_t const AStarAlgorithm<TGraph>::kVisitedVerticesPeriod = 4;
// static
template <typename TGraph>
double const AStarAlgorithm<TGraph>::kEpsilon = 1e-6;
// This implementation is based on the view that the A* algorithm
// is equivalent to Dijkstra's algorithm that is run on a reweighted
// version of the graph. If an edge (v, w) has length l(v, w), its reduced
// cost is l_r(v, w) = l(v, w) + pi(w) - pi(v), where pi() is any function
// that ensures l_r(v, w) >= 0 for every edge. We set pi() to calculate
// the shortest possible distance to a goal node, and this is a common
// heuristic that people use in A*.
// Refer to this paper for more information:
// http://research.microsoft.com/pubs/154937/soda05.pdf
//
// The vertices of the graph are of type RoadPos.
// The edges of the graph are of type PossibleTurn.
template <typename TGraph>
typename AStarAlgorithm<TGraph>::Result AStarAlgorithm<TGraph>::FindPath(
TVertexType const & startVertex, TVertexType const & finalVertex,
vector<TVertexType> & path,
OnVisitedVertexCallback onVisitedVertexCallback) const
{
ASSERT(m_graph, ());
if (nullptr == onVisitedVertexCallback)
onVisitedVertexCallback = [](TVertexType const &){};
map<TVertexType, double> bestDistance;
priority_queue<State, vector<State>, greater<State>> queue;
map<TVertexType, TVertexType> parent;
bestDistance[finalVertex] = 0.0;
queue.push(State(finalVertex, 0.0));
vector<TEdgeType> adj;
uint32_t steps = 0;
while (!queue.empty())
{
++steps;
if (steps % kCancelledPollPeriod == 0 && IsCancelled())
return Result::Cancelled;
State const stateV = queue.top();
queue.pop();
if (stateV.distance > bestDistance[stateV.vertex])
continue;
if (steps % kVisitedVerticesPeriod == 0)
onVisitedVertexCallback(stateV.vertex);
if (stateV.vertex == startVertex)
{
ReconstructPath(stateV.vertex, parent, path);
return Result::OK;
}
m_graph->GetIngoingEdgesList(stateV.vertex, adj);
for (auto const & edge : adj)
{
State stateW(edge.GetTarget(), 0.0);
if (stateV.vertex == stateW.vertex)
continue;
double const len = edge.GetWeight();
double const piV = m_graph->HeuristicCostEstimate(stateV.vertex, startVertex);
double const piW = m_graph->HeuristicCostEstimate(stateW.vertex, startVertex);
double const reducedLen = len + piW - piV;
CHECK(reducedLen >= -kEpsilon, ("Invariant violated:", reducedLen, "<", -kEpsilon));
double const newReducedDist = stateV.distance + max(reducedLen, 0.0);
auto const t = bestDistance.find(stateW.vertex);
if (t != bestDistance.end() && newReducedDist >= t->second - kEpsilon)
continue;
stateW.distance = newReducedDist;
bestDistance[stateW.vertex] = newReducedDist;
parent[stateW.vertex] = stateV.vertex;
queue.push(stateW);
}
}
return Result::NoPath;
}
template <typename TGraph>
typename AStarAlgorithm<TGraph>::Result AStarAlgorithm<TGraph>::FindPathBidirectional(
TVertexType const & startVertex, TVertexType const & finalVertex,
vector<TVertexType> & path,
OnVisitedVertexCallback onVisitedVertexCallback) const
{
ASSERT(m_graph, ());
if (nullptr == onVisitedVertexCallback)
onVisitedVertexCallback = [](TVertexType const &){};
BidirectionalStepContext forward(true /* forward */, startVertex, finalVertex, *m_graph);
BidirectionalStepContext backward(false /* forward */, startVertex, finalVertex, *m_graph);
bool foundAnyPath = false;
double bestPathLength = 0.0;
forward.bestDistance[startVertex] = 0.0;
forward.queue.push(State(startVertex, 0.0 /* distance */));
backward.bestDistance[finalVertex] = 0.0;
backward.queue.push(State(finalVertex, 0.0 /* distance */));
// To use the search code both for backward and forward directions
// we keep the pointers to everything related to the search in the
// 'current' and 'next' directions. Swapping these pointers indicates
// changing the end we are searching from.
BidirectionalStepContext * cur = &forward;
BidirectionalStepContext * nxt = &backward;
vector<TEdgeType> adj;
// It is not necessary to check emptiness for both queues here
// because if we have not found a path by the time one of the
// queues is exhausted, we never will.
uint32_t steps = 0;
while (!cur->queue.empty() && !nxt->queue.empty())
{
++steps;
if (steps % kCancelledPollPeriod == 0 && IsCancelled())
return Result::Cancelled;
if (steps % kQueueSwitchPeriod == 0)
swap(cur, nxt);
double const curTop = cur->TopDistance();
double const nxtTop = nxt->TopDistance();
double const pTopV = cur->ConsistentHeuristic(cur->queue.top().vertex);
double const pTopW = nxt->ConsistentHeuristic(nxt->queue.top().vertex);
// The intuition behind this is that we cannot obtain a path shorter
// than the left side of the inequality because that is how any path we find
// will look like (see comment for curPathLength below).
// We do not yet have the proof that we will not miss a good path by doing so.
if (foundAnyPath &&
curTop + nxtTop - pTopV + cur->pS - pTopW + nxt->pS >= bestPathLength - kEpsilon)
{
ReconstructPathBidirectional(cur->bestVertex, nxt->bestVertex, cur->parent, nxt->parent,
path);
CHECK(!path.empty(), ());
if (!cur->forward)
reverse(path.begin(), path.end());
return Result::OK;
}
State const stateV = cur->queue.top();
cur->queue.pop();
if (stateV.distance > cur->bestDistance[stateV.vertex])
continue;
if (steps % kVisitedVerticesPeriod == 0)
onVisitedVertexCallback(stateV.vertex);
cur->GetAdjacencyList(stateV.vertex, adj);
for (auto const & edge : adj)
{
State stateW(edge.GetTarget(), 0.0);
if (stateV.vertex == stateW.vertex)
continue;
double const len = edge.GetWeight();
double const pV = cur->ConsistentHeuristic(stateV.vertex);
double const pW = cur->ConsistentHeuristic(stateW.vertex);
double const reducedLen = len + pW - pV;
CHECK(reducedLen >= -kEpsilon, ("Invariant violated:", reducedLen, "<", -kEpsilon));
double const newReducedDist = stateV.distance + max(reducedLen, 0.0);
auto const itCur = cur->bestDistance.find(stateW.vertex);
if (itCur != cur->bestDistance.end() && newReducedDist >= itCur->second - kEpsilon)
continue;
auto const itNxt = nxt->bestDistance.find(stateW.vertex);
if (itNxt != nxt->bestDistance.end())
{
double const pRW = nxt->ConsistentHeuristic(stateW.vertex);
double const distW = itNxt->second;
// Length that the path we've just found has in the original graph:
// find the length of the path's parts in the reduced forward and backward
// graphs and remove the heuristic adjustments.
double const curPathLength = newReducedDist + distW - pW + cur->pS - pRW + nxt->pS;
// No epsilon here: it is ok to overshoot slightly.
if (!foundAnyPath || bestPathLength > curPathLength)
{
bestPathLength = curPathLength;
foundAnyPath = true;
cur->bestVertex = stateV.vertex;
nxt->bestVertex = stateW.vertex;
}
}
stateW.distance = newReducedDist;
cur->bestDistance[stateW.vertex] = newReducedDist;
cur->parent[stateW.vertex] = stateV.vertex;
cur->queue.push(stateW);
}
}
return Result::NoPath;
}
// static
template <typename TGraph>
void AStarAlgorithm<TGraph>::ReconstructPath(TVertexType const & v,
map<TVertexType, TVertexType> const & parent,
vector<TVertexType> & path)
{
path.clear();
TVertexType cur = v;
while (true)
{
path.push_back(cur);
auto it = parent.find(cur);
if (it == parent.end())
break;
cur = it->second;
}
}
// static
template <typename TGraph>
void AStarAlgorithm<TGraph>::ReconstructPathBidirectional(
TVertexType const & v, TVertexType const & w, map<TVertexType, TVertexType> const & parentV,
map<TVertexType, TVertexType> const & parentW, vector<TVertexType> & path)
{
vector<TVertexType> pathV;
ReconstructPath(v, parentV, pathV);
vector<TVertexType> pathW;
ReconstructPath(w, parentW, pathW);
path.clear();
path.reserve(pathV.size() + pathW.size());
path.insert(path.end(), pathV.rbegin(), pathV.rend());
path.insert(path.end(), pathW.begin(), pathW.end());
}
} // namespace routing
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Symbols.h"
#include <fstream>
Symbols::Symbols( ) :
m_bInitialized( FALSE )
{
ResolveSearchPath( );
if (!WriteSymSrvDll( ))
throw std::exception( "WriteSymSrvDll_failed" );
if (!Init( ))
throw std::exception( "init_failed" );
ntdll::RtlInitializeCriticalSection( &m_CriticalSection );
}
Symbols::~Symbols( )
{
ntdll::RtlDeleteCriticalSection( &m_CriticalSection );
Cleanup( );
DeleteFile( _T( "symsrv.dll" ) );
}
void Symbols::ResolveSearchPath( )
{
CString searchPath;
LRESULT lRet;
HKEY hKey = NULL;
//C:\Users\User\AppData\Local\Temp\SymbolCache
for (int i = 14; i >= 8; i--)
{
CString regPath = _T( "Software\\Microsoft\\VisualStudio\\" );
wchar_t version[4];
_itow_s( i, version, 10 );
#ifdef UNICODE
regPath.Append( version );
#else
regPath.Append( CW2A( version ) );
#endif
regPath.Append( _T( ".0\\Debugger" ) );
lRet = RegOpenKeyEx( HKEY_CURRENT_USER, regPath.GetString( ), 0, KEY_READ, &hKey );
if (hKey)
{
TCHAR szBuffer[MAX_PATH];
DWORD dwBufferSize = MAX_PATH;
lRet = RegQueryValueEx( hKey, _T( "SymbolCacheDir" ), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize );
if (lRet == ERROR_SUCCESS && szBuffer)
{
searchPath = szBuffer;
RegCloseKey( hKey );
break;
}
RegCloseKey( hKey );
}
}
if (!searchPath.IsEmpty( ))
{
m_strSearchPath.Format( _T( "srv*%s*http://msdl.microsoft.com/download/symbols" ), searchPath.GetString( ) );
PrintOut( _T( "Symbol server path found from Visual Studio config: %s" ), searchPath.GetString( ) );
}
else
{
TCHAR szWindowsDir[MAX_PATH];
GetCurrentDirectory( MAX_PATH, szWindowsDir );
m_strSearchPath.Format( _T( "srv*%s\\symbols*http://msdl.microsoft.com/download/symbols" ), szWindowsDir );
PrintOut( _T( "Symbol server path not found, using windows dir: %s" ), szWindowsDir );
}
}
BOOLEAN Symbols::WriteSymSrvDll( )
{
HRSRC hSymSrvRes = NULL;
HGLOBAL hGlobal = NULL;
LPVOID pSymSrvData = NULL;
DWORD dwSymSrvDataSize = 0;
#ifdef _WIN64
hSymSrvRes = FindResource( NULL, MAKEINTRESOURCE( IDR_RCDATA_SYMSRV64 ), RT_RCDATA );
#else
hSymSrvRes = FindResource( NULL, MAKEINTRESOURCE( IDR_RCDATA_SYMSRV32 ), RT_RCDATA );
#endif
if (hSymSrvRes != NULL)
{
hGlobal = LoadResource( NULL, hSymSrvRes );
if (hGlobal != NULL)
{
pSymSrvData = LockResource( hGlobal );
dwSymSrvDataSize = SizeofResource( NULL, hSymSrvRes );
if (pSymSrvData != NULL)
{
std::ofstream fSymSrvDll( _T( "symsrv.dll" ), std::ios::binary );
if (fSymSrvDll)
{
fSymSrvDll.write( (const char*)pSymSrvData, dwSymSrvDataSize );
fSymSrvDll.close( );
UnlockResource( hGlobal );
FreeResource( hGlobal );
return TRUE;
}
}
}
UnlockResource( hGlobal );
FreeResource( hGlobal );
}
return FALSE;
}
void Symbols::Cleanup( )
{
if (m_bInitialized == TRUE)
{
for (auto it = m_SymbolAddresses.begin( ); it != m_SymbolAddresses.end( ); ++it)
delete it->second;
m_SymbolAddresses.clear( );
for (auto it = m_SymbolNames.begin( ); it != m_SymbolNames.end( ); ++it)
delete it->second;
m_SymbolNames.clear( );
CoUninitialize( );
m_bInitialized = FALSE;
}
}
BOOLEAN Symbols::Init( )
{
if (m_bInitialized == FALSE)
{
HRESULT hr = S_OK;
hr = CoInitialize( NULL );
if (FAILED( hr ))
{
PrintOut( _T( "[Symbols::Init] CoInitialize failed - HRESULT = %08X" ), hr );
return FALSE;
}
m_bInitialized = TRUE;
}
return TRUE;
}
BOOLEAN Symbols::LoadSymbolsForModule( CString ModulePath, ULONG_PTR ModuleBaseAddress, ULONG SizeOfModule )
{
int idx = -1;
CString ModuleName;
const TCHAR* szSearchPath = NULL;
SymbolReader* reader = NULL;
BOOLEAN bSucc = FALSE;
idx = ModulePath.ReverseFind( '/' );
if (idx == -1)
idx = ModulePath.ReverseFind( '\\' );
ModuleName = ModulePath.Mid( ++idx );
if (!m_strSearchPath.IsEmpty( ))
szSearchPath = m_strSearchPath.GetString( );
reader = new SymbolReader( );
//ntdll::RtlEnterCriticalSection( &m_CriticalSection );
bSucc = reader->LoadFile( ModuleName, ModulePath, ModuleBaseAddress, SizeOfModule, szSearchPath );
//ntdll::RtlLeaveCriticalSection( &m_CriticalSection );
if (bSucc)
{
PrintOut( _T( "[Symbols::LoadSymbolsForModule] Symbols for module %s loaded" ), ModuleName.GetString( ) );
m_SymbolAddresses.insert( std::make_pair( ModuleBaseAddress, reader ) );
return TRUE;
}
delete reader;
return FALSE;
}
BOOLEAN Symbols::LoadSymbolsForPdb( CString PdbPath )
{
int idx = -1;
CString PdbFileName;
const TCHAR* szSearchPath = NULL;
SymbolReader* reader = NULL;
BOOLEAN bSucc = FALSE;
idx = PdbPath.ReverseFind( '/' );
if (idx == -1)
idx = PdbPath.ReverseFind( '\\' );
PdbFileName = PdbPath.Mid( ++idx );
if (!m_strSearchPath.IsEmpty( ))
szSearchPath = m_strSearchPath.GetString( );
reader = new SymbolReader( );
ntdll::RtlEnterCriticalSection( &m_CriticalSection );
bSucc = reader->LoadFile( PdbFileName, PdbPath, 0, 0, szSearchPath );
ntdll::RtlLeaveCriticalSection( &m_CriticalSection );
if (bSucc)
{
PrintOut( _T( "[Symbols::LoadSymbolsForPdb] Symbols for module %s loaded" ), PdbFileName.GetString( ) );
m_SymbolNames.insert( std::make_pair( PdbFileName, reader ) );
return TRUE;
}
delete reader;
return FALSE;
}
//void Symbols::LoadModuleSymbols()
//{
// PPROCESS_BASIC_INFORMATION pbi = NULL;
// PEB peb;
// PEB_LDR_DATA peb_ldr;
//
// // Try to allocate buffer
// HANDLE hHeap = GetProcessHeap();
// DWORD dwSize = sizeof(PROCESS_BASIC_INFORMATION);
// pbi = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwSize);
//
// ULONG dwSizeNeeded = 0;
// NTSTATUS dwStatus = ntdll::NtQueryInformationProcess(g_hProcess, ProcessBasicInformation, pbi, dwSize, &dwSizeNeeded);
// if (NT_SUCCESS(dwStatus) && dwSize < dwSizeNeeded)
// {
// if (pbi)
// HeapFree(hHeap, 0, pbi);
//
// pbi = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwSizeNeeded);
// if (!pbi) {
// _tprintf(_T("[LoadModuleSymbols] Couldn't allocate heap buffer!\n"));
// return;
// }
//
// dwStatus = ntdll::NtQueryInformationProcess(g_hProcess, ProcessBasicInformation, pbi, dwSizeNeeded, &dwSizeNeeded);
// }
//
// // Did we successfully get basic info on process
// if (NT_SUCCESS(dwStatus))
// {
// // Read Process Environment Block (PEB)
// if (pbi->PebBaseAddress)
// {
// SIZE_T dwBytesRead = 0;
// if (ReClassReadMemory(pbi->PebBaseAddress, &peb, sizeof(peb), &dwBytesRead))
// {
// dwBytesRead = 0;
// if (ReClassReadMemory(peb.Ldr, &peb_ldr, sizeof(peb_ldr), &dwBytesRead))
// {
// ULONG numOfEntries = peb_ldr.Length;
// ULONG currentEntryNum = 0;
// LIST_ENTRY *pLdrListHead = (LIST_ENTRY *)peb_ldr.InMemoryOrderModuleList.Flink;
// LIST_ENTRY *pLdrCurrentNode = peb_ldr.InMemoryOrderModuleList.Flink;
// do
// {
// LDR_DATA_TABLE_ENTRY lstEntry = { 0 };
// dwBytesRead = 0;
// if (!ReClassReadMemory((LPVOID)pLdrCurrentNode, &lstEntry, sizeof(LDR_DATA_TABLE_ENTRY), &dwBytesRead))
// {
// _tprintf(_T("[LoadModuleSymbols] Could not read list entry from LDR list. Error: %s\n"), Utils::GetLastErrorAsString().c_str());
// if (pbi)
// HeapFree(hHeap, 0, pbi);
// return;
// }
//
// pLdrCurrentNode = lstEntry.InLoadOrderLinks.Flink;
//
// wchar_t wcsFullDllName[MAX_PATH] = { 0 };
// if (lstEntry.FullDllName.Buffer && lstEntry.FullDllName.Length > 0)
// {
// dwBytesRead = 0;
// if (!ReClassReadMemory((LPVOID)lstEntry.FullDllName.Buffer, &wcsFullDllName, lstEntry.FullDllName.Length, &dwBytesRead))
// {
// _tprintf(_T("[LoadModuleSymbols] Could not read list entry DLL name. Error: %s\n"), Utils::GetLastErrorAsString().c_str());
// if (pbi)
// HeapFree(hHeap, 0, pbi);
// return;
// }
// }
//
// if (lstEntry.DllBase != 0 && lstEntry.SizeOfImage != 0)
// {
// if (LoadSymbolsForModule(wcsFullDllName, (size_t)lstEntry.DllBase, lstEntry.SizeOfImage)) {
// PrintOut(_T("Symbol module %ls loaded"), wcsFullDllName);
// }
// currentEntryNum++;
// float progress = ((float)currentEntryNum / (float)numOfEntries) * 100;
// printf("[%d/%d] progress: %f\n", currentEntryNum, numOfEntries, progress);
// }
// } while (pLdrListHead != pLdrCurrentNode);
//
// } // Get Ldr
// } // Read PEB
// } // Check for PEB
// }
//
// if (pbi)
// HeapFree(hHeap, 0, pbi);
//}
SymbolReader* Symbols::GetSymbolsForModuleAddress( ULONG_PTR ModuleAddress )
{
SymbolReader* script = NULL;
auto iter = m_SymbolAddresses.find( ModuleAddress );
if (iter != m_SymbolAddresses.end( ))
script = iter->second;
return script;
}
SymbolReader* Symbols::GetSymbolsForModuleName( CString ModuleName )
{
SymbolReader* script = NULL;
auto iter = m_SymbolNames.find( ModuleName );
if (iter != m_SymbolNames.end( ))
script = iter->second;
return script;
}
typedef void*( CDECL * Alloc_t )(unsigned int);
typedef void( CDECL * Free_t )(void *);
typedef PCHAR( CDECL *PUNDNAME )(char *, const char *, int, Alloc_t, Free_t, unsigned short);
void *CDECL AllocIt( unsigned int cb ) { return HeapAlloc( GetProcessHeap( ), 0, cb ); }
void CDECL FreeIt( void * p ) { HeapFree( GetProcessHeap( ), 0, p ); }
DWORD
WINAPI
UndecorateSymbolName(
LPCSTR name,
LPSTR outputString,
DWORD maxStringLength,
DWORD flags
)
{
static HMODULE hMsvcrt = NULL;
static PUNDNAME pfUnDname = NULL;
DWORD rc;
if (!hMsvcrt)
{
hMsvcrt = (HMODULE)Utils::GetLocalModuleBase( _T( "msvcrt.dll" ) );
if (hMsvcrt)
pfUnDname = (PUNDNAME)Utils::GetLocalProcAddress( hMsvcrt, _T( "__unDName" ) );
}
rc = 0;
if (pfUnDname)
{
if (name && outputString && maxStringLength >= 2)
{
if (pfUnDname( outputString, name, maxStringLength - 1, AllocIt, FreeIt, (USHORT)flags ))
{
rc = strlen( outputString );
}
}
}
else
{
strncpy_s( outputString, maxStringLength, "Unable to load msvcrt!__unDName", maxStringLength );
rc = strlen( outputString );
SetLastError( ERROR_MOD_NOT_FOUND );
}
if (!rc)
SetLastError( ERROR_INVALID_PARAMETER );
return rc;
}
DWORD
WINAPI
UndecorateSymbolNameUnicode(
LPCWSTR name,
LPWSTR outputString,
DWORD maxStringLength,
DWORD flags
)
{
LPSTR AnsiName;
LPSTR AnsiOutputString;
int AnsiNameLength;
DWORD rc;
AnsiNameLength = WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_SEPCHARS, name, -1, NULL, 0, NULL, NULL );
if (!AnsiNameLength)
return 0;
AnsiName = (char *)AllocIt( AnsiNameLength );
if (!AnsiName)
{
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
return 0;
}
ZeroMemory( AnsiName, 0, AnsiNameLength );
if (!WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_SEPCHARS, name, -1, AnsiName, AnsiNameLength, NULL, NULL ))
{
FreeIt( AnsiName );
return 0;
}
AnsiOutputString = (LPSTR)AllocIt( maxStringLength + 1 );
if (!AnsiOutputString)
{
FreeIt( AnsiName );
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
return 0;
}
*AnsiOutputString = '\0';
rc = UndecorateSymbolName( AnsiName, AnsiOutputString, maxStringLength, flags );
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, AnsiOutputString, -1, outputString, maxStringLength );
FreeIt( AnsiName );
FreeIt( AnsiOutputString );
return rc;
}
<commit_msg>Fixed too many actual parameters for ZeroMemory.<commit_after>#include "stdafx.h"
#include "Symbols.h"
#include <fstream>
Symbols::Symbols( ) :
m_bInitialized( FALSE )
{
ResolveSearchPath( );
if (!WriteSymSrvDll( ))
throw std::exception( "WriteSymSrvDll_failed" );
if (!Init( ))
throw std::exception( "init_failed" );
ntdll::RtlInitializeCriticalSection( &m_CriticalSection );
}
Symbols::~Symbols( )
{
ntdll::RtlDeleteCriticalSection( &m_CriticalSection );
Cleanup( );
DeleteFile( _T( "symsrv.dll" ) );
}
void Symbols::ResolveSearchPath( )
{
CString searchPath;
LRESULT lRet;
HKEY hKey = NULL;
//C:\Users\User\AppData\Local\Temp\SymbolCache
for (int i = 14; i >= 8; i--)
{
CString regPath = _T( "Software\\Microsoft\\VisualStudio\\" );
wchar_t version[4];
_itow_s( i, version, 10 );
#ifdef UNICODE
regPath.Append( version );
#else
regPath.Append( CW2A( version ) );
#endif
regPath.Append( _T( ".0\\Debugger" ) );
lRet = RegOpenKeyEx( HKEY_CURRENT_USER, regPath.GetString( ), 0, KEY_READ, &hKey );
if (hKey)
{
TCHAR szBuffer[MAX_PATH];
DWORD dwBufferSize = MAX_PATH;
lRet = RegQueryValueEx( hKey, _T( "SymbolCacheDir" ), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize );
if (lRet == ERROR_SUCCESS && szBuffer)
{
searchPath = szBuffer;
RegCloseKey( hKey );
break;
}
RegCloseKey( hKey );
}
}
if (!searchPath.IsEmpty( ))
{
m_strSearchPath.Format( _T( "srv*%s*http://msdl.microsoft.com/download/symbols" ), searchPath.GetString( ) );
PrintOut( _T( "Symbol server path found from Visual Studio config: %s" ), searchPath.GetString( ) );
}
else
{
TCHAR szWindowsDir[MAX_PATH];
GetCurrentDirectory( MAX_PATH, szWindowsDir );
m_strSearchPath.Format( _T( "srv*%s\\symbols*http://msdl.microsoft.com/download/symbols" ), szWindowsDir );
PrintOut( _T( "Symbol server path not found, using windows dir: %s" ), szWindowsDir );
}
}
BOOLEAN Symbols::WriteSymSrvDll( )
{
HRSRC hSymSrvRes = NULL;
HGLOBAL hGlobal = NULL;
LPVOID pSymSrvData = NULL;
DWORD dwSymSrvDataSize = 0;
#ifdef _WIN64
hSymSrvRes = FindResource( NULL, MAKEINTRESOURCE( IDR_RCDATA_SYMSRV64 ), RT_RCDATA );
#else
hSymSrvRes = FindResource( NULL, MAKEINTRESOURCE( IDR_RCDATA_SYMSRV32 ), RT_RCDATA );
#endif
if (hSymSrvRes != NULL)
{
hGlobal = LoadResource( NULL, hSymSrvRes );
if (hGlobal != NULL)
{
pSymSrvData = LockResource( hGlobal );
dwSymSrvDataSize = SizeofResource( NULL, hSymSrvRes );
if (pSymSrvData != NULL)
{
std::ofstream fSymSrvDll( _T( "symsrv.dll" ), std::ios::binary );
if (fSymSrvDll)
{
fSymSrvDll.write( (const char*)pSymSrvData, dwSymSrvDataSize );
fSymSrvDll.close( );
UnlockResource( hGlobal );
FreeResource( hGlobal );
return TRUE;
}
}
}
UnlockResource( hGlobal );
FreeResource( hGlobal );
}
return FALSE;
}
void Symbols::Cleanup( )
{
if (m_bInitialized == TRUE)
{
for (auto it = m_SymbolAddresses.begin( ); it != m_SymbolAddresses.end( ); ++it)
delete it->second;
m_SymbolAddresses.clear( );
for (auto it = m_SymbolNames.begin( ); it != m_SymbolNames.end( ); ++it)
delete it->second;
m_SymbolNames.clear( );
CoUninitialize( );
m_bInitialized = FALSE;
}
}
BOOLEAN Symbols::Init( )
{
if (m_bInitialized == FALSE)
{
HRESULT hr = S_OK;
hr = CoInitialize( NULL );
if (FAILED( hr ))
{
PrintOut( _T( "[Symbols::Init] CoInitialize failed - HRESULT = %08X" ), hr );
return FALSE;
}
m_bInitialized = TRUE;
}
return TRUE;
}
BOOLEAN Symbols::LoadSymbolsForModule( CString ModulePath, ULONG_PTR ModuleBaseAddress, ULONG SizeOfModule )
{
int idx = -1;
CString ModuleName;
const TCHAR* szSearchPath = NULL;
SymbolReader* reader = NULL;
BOOLEAN bSucc = FALSE;
idx = ModulePath.ReverseFind( '/' );
if (idx == -1)
idx = ModulePath.ReverseFind( '\\' );
ModuleName = ModulePath.Mid( ++idx );
if (!m_strSearchPath.IsEmpty( ))
szSearchPath = m_strSearchPath.GetString( );
reader = new SymbolReader( );
//ntdll::RtlEnterCriticalSection( &m_CriticalSection );
bSucc = reader->LoadFile( ModuleName, ModulePath, ModuleBaseAddress, SizeOfModule, szSearchPath );
//ntdll::RtlLeaveCriticalSection( &m_CriticalSection );
if (bSucc)
{
PrintOut( _T( "[Symbols::LoadSymbolsForModule] Symbols for module %s loaded" ), ModuleName.GetString( ) );
m_SymbolAddresses.insert( std::make_pair( ModuleBaseAddress, reader ) );
return TRUE;
}
delete reader;
return FALSE;
}
BOOLEAN Symbols::LoadSymbolsForPdb( CString PdbPath )
{
int idx = -1;
CString PdbFileName;
const TCHAR* szSearchPath = NULL;
SymbolReader* reader = NULL;
BOOLEAN bSucc = FALSE;
idx = PdbPath.ReverseFind( '/' );
if (idx == -1)
idx = PdbPath.ReverseFind( '\\' );
PdbFileName = PdbPath.Mid( ++idx );
if (!m_strSearchPath.IsEmpty( ))
szSearchPath = m_strSearchPath.GetString( );
reader = new SymbolReader( );
ntdll::RtlEnterCriticalSection( &m_CriticalSection );
bSucc = reader->LoadFile( PdbFileName, PdbPath, 0, 0, szSearchPath );
ntdll::RtlLeaveCriticalSection( &m_CriticalSection );
if (bSucc)
{
PrintOut( _T( "[Symbols::LoadSymbolsForPdb] Symbols for module %s loaded" ), PdbFileName.GetString( ) );
m_SymbolNames.insert( std::make_pair( PdbFileName, reader ) );
return TRUE;
}
delete reader;
return FALSE;
}
//void Symbols::LoadModuleSymbols()
//{
// PPROCESS_BASIC_INFORMATION pbi = NULL;
// PEB peb;
// PEB_LDR_DATA peb_ldr;
//
// // Try to allocate buffer
// HANDLE hHeap = GetProcessHeap();
// DWORD dwSize = sizeof(PROCESS_BASIC_INFORMATION);
// pbi = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwSize);
//
// ULONG dwSizeNeeded = 0;
// NTSTATUS dwStatus = ntdll::NtQueryInformationProcess(g_hProcess, ProcessBasicInformation, pbi, dwSize, &dwSizeNeeded);
// if (NT_SUCCESS(dwStatus) && dwSize < dwSizeNeeded)
// {
// if (pbi)
// HeapFree(hHeap, 0, pbi);
//
// pbi = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwSizeNeeded);
// if (!pbi) {
// _tprintf(_T("[LoadModuleSymbols] Couldn't allocate heap buffer!\n"));
// return;
// }
//
// dwStatus = ntdll::NtQueryInformationProcess(g_hProcess, ProcessBasicInformation, pbi, dwSizeNeeded, &dwSizeNeeded);
// }
//
// // Did we successfully get basic info on process
// if (NT_SUCCESS(dwStatus))
// {
// // Read Process Environment Block (PEB)
// if (pbi->PebBaseAddress)
// {
// SIZE_T dwBytesRead = 0;
// if (ReClassReadMemory(pbi->PebBaseAddress, &peb, sizeof(peb), &dwBytesRead))
// {
// dwBytesRead = 0;
// if (ReClassReadMemory(peb.Ldr, &peb_ldr, sizeof(peb_ldr), &dwBytesRead))
// {
// ULONG numOfEntries = peb_ldr.Length;
// ULONG currentEntryNum = 0;
// LIST_ENTRY *pLdrListHead = (LIST_ENTRY *)peb_ldr.InMemoryOrderModuleList.Flink;
// LIST_ENTRY *pLdrCurrentNode = peb_ldr.InMemoryOrderModuleList.Flink;
// do
// {
// LDR_DATA_TABLE_ENTRY lstEntry = { 0 };
// dwBytesRead = 0;
// if (!ReClassReadMemory((LPVOID)pLdrCurrentNode, &lstEntry, sizeof(LDR_DATA_TABLE_ENTRY), &dwBytesRead))
// {
// _tprintf(_T("[LoadModuleSymbols] Could not read list entry from LDR list. Error: %s\n"), Utils::GetLastErrorAsString().c_str());
// if (pbi)
// HeapFree(hHeap, 0, pbi);
// return;
// }
//
// pLdrCurrentNode = lstEntry.InLoadOrderLinks.Flink;
//
// wchar_t wcsFullDllName[MAX_PATH] = { 0 };
// if (lstEntry.FullDllName.Buffer && lstEntry.FullDllName.Length > 0)
// {
// dwBytesRead = 0;
// if (!ReClassReadMemory((LPVOID)lstEntry.FullDllName.Buffer, &wcsFullDllName, lstEntry.FullDllName.Length, &dwBytesRead))
// {
// _tprintf(_T("[LoadModuleSymbols] Could not read list entry DLL name. Error: %s\n"), Utils::GetLastErrorAsString().c_str());
// if (pbi)
// HeapFree(hHeap, 0, pbi);
// return;
// }
// }
//
// if (lstEntry.DllBase != 0 && lstEntry.SizeOfImage != 0)
// {
// if (LoadSymbolsForModule(wcsFullDllName, (size_t)lstEntry.DllBase, lstEntry.SizeOfImage)) {
// PrintOut(_T("Symbol module %ls loaded"), wcsFullDllName);
// }
// currentEntryNum++;
// float progress = ((float)currentEntryNum / (float)numOfEntries) * 100;
// printf("[%d/%d] progress: %f\n", currentEntryNum, numOfEntries, progress);
// }
// } while (pLdrListHead != pLdrCurrentNode);
//
// } // Get Ldr
// } // Read PEB
// } // Check for PEB
// }
//
// if (pbi)
// HeapFree(hHeap, 0, pbi);
//}
SymbolReader* Symbols::GetSymbolsForModuleAddress( ULONG_PTR ModuleAddress )
{
SymbolReader* script = NULL;
auto iter = m_SymbolAddresses.find( ModuleAddress );
if (iter != m_SymbolAddresses.end( ))
script = iter->second;
return script;
}
SymbolReader* Symbols::GetSymbolsForModuleName( CString ModuleName )
{
SymbolReader* script = NULL;
auto iter = m_SymbolNames.find( ModuleName );
if (iter != m_SymbolNames.end( ))
script = iter->second;
return script;
}
typedef void*( CDECL * Alloc_t )(unsigned int);
typedef void( CDECL * Free_t )(void *);
typedef PCHAR( CDECL *PUNDNAME )(char *, const char *, int, Alloc_t, Free_t, unsigned short);
void *CDECL AllocIt( unsigned int cb ) { return HeapAlloc( GetProcessHeap( ), 0, cb ); }
void CDECL FreeIt( void * p ) { HeapFree( GetProcessHeap( ), 0, p ); }
DWORD
WINAPI
UndecorateSymbolName(
LPCSTR name,
LPSTR outputString,
DWORD maxStringLength,
DWORD flags
)
{
static HMODULE hMsvcrt = NULL;
static PUNDNAME pfUnDname = NULL;
DWORD rc;
if (!hMsvcrt)
{
hMsvcrt = (HMODULE)Utils::GetLocalModuleBase( _T( "msvcrt.dll" ) );
if (hMsvcrt)
pfUnDname = (PUNDNAME)Utils::GetLocalProcAddress( hMsvcrt, _T( "__unDName" ) );
}
rc = 0;
if (pfUnDname)
{
if (name && outputString && maxStringLength >= 2)
{
if (pfUnDname( outputString, name, maxStringLength - 1, AllocIt, FreeIt, (USHORT)flags ))
{
rc = strlen( outputString );
}
}
}
else
{
strncpy_s( outputString, maxStringLength, "Unable to load msvcrt!__unDName", maxStringLength );
rc = strlen( outputString );
SetLastError( ERROR_MOD_NOT_FOUND );
}
if (!rc)
SetLastError( ERROR_INVALID_PARAMETER );
return rc;
}
DWORD
WINAPI
UndecorateSymbolNameUnicode(
LPCWSTR name,
LPWSTR outputString,
DWORD maxStringLength,
DWORD flags
)
{
LPSTR AnsiName;
LPSTR AnsiOutputString;
int AnsiNameLength;
DWORD rc;
AnsiNameLength = WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_SEPCHARS, name, -1, NULL, 0, NULL, NULL );
if (!AnsiNameLength)
return 0;
AnsiName = (char *)AllocIt( AnsiNameLength );
if (!AnsiName)
{
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
return 0;
}
ZeroMemory( AnsiName, AnsiNameLength );
if (!WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_SEPCHARS, name, -1, AnsiName, AnsiNameLength, NULL, NULL ))
{
FreeIt( AnsiName );
return 0;
}
AnsiOutputString = (LPSTR)AllocIt( maxStringLength + 1 );
if (!AnsiOutputString)
{
FreeIt( AnsiName );
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
return 0;
}
*AnsiOutputString = '\0';
rc = UndecorateSymbolName( AnsiName, AnsiOutputString, maxStringLength, flags );
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, AnsiOutputString, -1, outputString, maxStringLength );
FreeIt( AnsiName );
FreeIt( AnsiOutputString );
return rc;
}
<|endoftext|> |
<commit_before>#include "StmtCompiler.h"
#include "CodeGen.h"
#include "CodeGen_X86.h"
#include "CodeGen_GPU_Host.h"
#include "CodeGen_ARM.h"
#include <iostream>
namespace Halide {
using std::string;
using std::vector;
namespace {
#ifndef __arm__
#ifdef _MSC_VER
static void cpuid(int info[4], int infoType, int extra) {
_asm {
mov edi, info;
mov eax, infoType;
mov ecx, extra;
cpuid;
mov [edi], eax;
mov [edi+4], ebx;
mov [edi+8], ecx;
mov [edi+12], edx;
}
}
#else
// CPU feature detection code taken from ispc
// (https://github.com/ispc/ispc/blob/master/builtins/dispatch.ll)
static void cpuid(int info[4], int infoType, int extra) {
// We save %ebx in case it's the PIC register
__asm__ __volatile__ (
"xchg{l}\t{%%}ebx, %1 \n\t"
"cpuid \n\t"
"xchg{l}\t{%%}ebx, %1 \n\t"
: "=a" (info[0]), "=r" (info[1]), "=c" (info[2]), "=d" (info[3])
: "0" (infoType), "2" (extra));
}
#endif
#endif
}
string get_native_target() {
#ifdef __arm__
return "arm";
#else
int info[4];
cpuid(info, 1, 0);
bool use_64_bits = (sizeof(size_t) == 8);
bool have_sse41 = info[2] & (1 << 19);
bool have_sse2 = info[3] & (1 << 26);
bool have_avx = info[2] & (1 << 28);
bool have_f16 = info[2] & (1 << 29);
bool have_rdrand = info[2] & (1 << 30);
/* NOTE: the values returned below must be the same as the
corresponding enumerant values in Target::ISA. */
if (use_64_bits) {
if (have_avx) {
if (have_f16 && have_rdrand) {
// So far, so good. AVX2?
// Call cpuid with eax=7, ecx=0
int info2[4];
cpuid(info2, 7, 0);
bool have_avx2 = info[2] & (1 << 5);
if (have_avx2) {
// AVX 2
// For now we just return avx.
return "x86-64-avx";
} else {
// AVX with float16 and rdrand
// For now we just return avx.
return "x86-64-avx";
}
}
// Regular AVX
return "x86-64-avx";
} else if (have_sse41) {
// SSE4.1
return "x86-64-sse41";
} else if (have_sse2) {
// SSE2
return "x86-64";
} else {
}
} else {
// 32-bit targets
if ((info[2] & (1 << 19)) != 0) {
// SSE4.1
return "x86-32-sse41";
} else if ((info[3] & (1 << 26)) != 0) {
// SSE2
return "x86-32";
}
}
std::cerr << "cpuid instruction returned " << std::hex
<< info[0] << ", "
<< info[1] << ", "
<< info[2] << ", "
<< info[3] << "\n";
assert(false && "No SSE2 support, or failed to correctly interpret the result of cpuid.");
return "";
#endif
}
string get_target() {
string native = get_native_target();
#ifdef _WIN32
char target[128];
size_t read = 0;
getenv_s(&read, target, "HL_TARGET");
if (read) return target;
else return native;
#else
char *target = getenv("HL_TARGET");
if (target) return target;
else return native;
#endif
}
namespace Internal {
StmtCompiler::StmtCompiler(string arch) {
string native = get_native_target();
if (arch == "native") {
arch = get_native_target();
} else if (arch.empty()) {
// Use HL_TARGET.
arch = get_target();
}
if (arch == "x86-32") {
contents = new CodeGen_X86();
} else if (arch == "x86-32-sse41") {
contents = new CodeGen_X86(X86_SSE41);
} else if (arch == "x86-64") {
// Lowest-common-denominator for 64-bit x86, including those
// without SSE4.1 (e.g. Clovertown) or SSSE3 (e.g. early AMD parts)...
// essentially, just SSE2.
contents = new CodeGen_X86(X86_64Bit);
} else if (arch == "x86-64-sse41") {
contents = new CodeGen_X86(X86_64Bit | X86_SSE41);
} else if (arch == "x86-64-avx") {
contents = new CodeGen_X86(X86_64Bit | X86_SSE41 | X86_AVX);
} else if (arch == "x86-32-nacl") {
contents = new CodeGen_X86(X86_NaCl);
} else if (arch == "x86-32-sse41-nacl") {
contents = new CodeGen_X86(X86_SSE41 | X86_NaCl);
} else if (arch == "x86-64-nacl") {
contents = new CodeGen_X86(X86_64Bit | X86_NaCl);
} else if (arch == "x86-64-sse41-nacl") {
contents = new CodeGen_X86(X86_64Bit | X86_SSE41 | X86_NaCl);
} else if (arch == "x86-64-avx-nacl") {
contents = new CodeGen_X86(X86_64Bit | X86_SSE41 | X86_AVX | X86_NaCl);
}
#ifndef _WIN32 // I've temporarily disabled ARM on Windows since it leads to a linking error on halide_internal_initmod_arm stuff (kwampler@adobe.com)
else if (arch == "arm") {
contents = new CodeGen_ARM();
} else if (arch == "arm-android") {
contents = new CodeGen_ARM(ARM_Android);
} else if (arch == "arm-ios") {
contents = new CodeGen_ARM(ARM_IOS);
} else if (arch == "arm-nacl") {
contents = new CodeGen_ARM(ARM_NaCl);
}
// GPU backends are disabled on Windows until I'm sure it links, too (@jrk)
else if (arch == "ptx") {
// equivalent to "x86" on the host side, i.e. x86_64, no AVX
contents = new CodeGen_GPU_Host(X86_64Bit | X86_SSE41 | GPU_PTX);
} else if (arch == "ptx-debug") {
contents = new CodeGen_GPU_Host(X86_64Bit | X86_SSE41 | GPU_PTX | GPU_debug);
} else if (arch == "opencl") {
// equivalent to "x86" on the host side, i.e. x86_64, no AVX
contents = new CodeGen_GPU_Host(X86_64Bit | X86_SSE41 | GPU_OpenCL);
}
#endif // _WIN32
else {
std::cerr << "Unknown target \"" << arch << "\"\n"
<< "Known targets are: "
<< "x86-32 x86-32-sse41 "
<< "x86-64 x86-64-sse41 x86-64-avx "
<< "x86-32-nacl x86-32-sse41-nacl "
<< "x86-64-nacl x86-64-sse41-nacl x86-64-avx-nacl "
<< "arm arm-android arm-ios arm-nacl"
<< "ptx ptx-debug opencl"
<< "native"
<< "\n"
<< "On this machine, native means " << native << "\n";
assert(false);
}
}
void StmtCompiler::compile(Stmt stmt, string name, const vector<Argument> &args) {
contents.ptr->compile(stmt, name, args);
}
void StmtCompiler::compile_to_bitcode(const string &filename) {
contents.ptr->compile_to_bitcode(filename);
}
void StmtCompiler::compile_to_native(const string &filename, bool assembly) {
contents.ptr->compile_to_native(filename, assembly);
}
JITCompiledModule StmtCompiler::compile_to_function_pointers() {
return contents.ptr->compile_to_function_pointers();
}
}
}
<commit_msg>Added some spaces to the list of targets we print.<commit_after>#include "StmtCompiler.h"
#include "CodeGen.h"
#include "CodeGen_X86.h"
#include "CodeGen_GPU_Host.h"
#include "CodeGen_ARM.h"
#include <iostream>
namespace Halide {
using std::string;
using std::vector;
namespace {
#ifndef __arm__
#ifdef _MSC_VER
static void cpuid(int info[4], int infoType, int extra) {
_asm {
mov edi, info;
mov eax, infoType;
mov ecx, extra;
cpuid;
mov [edi], eax;
mov [edi+4], ebx;
mov [edi+8], ecx;
mov [edi+12], edx;
}
}
#else
// CPU feature detection code taken from ispc
// (https://github.com/ispc/ispc/blob/master/builtins/dispatch.ll)
static void cpuid(int info[4], int infoType, int extra) {
// We save %ebx in case it's the PIC register
__asm__ __volatile__ (
"xchg{l}\t{%%}ebx, %1 \n\t"
"cpuid \n\t"
"xchg{l}\t{%%}ebx, %1 \n\t"
: "=a" (info[0]), "=r" (info[1]), "=c" (info[2]), "=d" (info[3])
: "0" (infoType), "2" (extra));
}
#endif
#endif
}
string get_native_target() {
#ifdef __arm__
return "arm";
#else
int info[4];
cpuid(info, 1, 0);
bool use_64_bits = (sizeof(size_t) == 8);
bool have_sse41 = info[2] & (1 << 19);
bool have_sse2 = info[3] & (1 << 26);
bool have_avx = info[2] & (1 << 28);
bool have_f16 = info[2] & (1 << 29);
bool have_rdrand = info[2] & (1 << 30);
/* NOTE: the values returned below must be the same as the
corresponding enumerant values in Target::ISA. */
if (use_64_bits) {
if (have_avx) {
if (have_f16 && have_rdrand) {
// So far, so good. AVX2?
// Call cpuid with eax=7, ecx=0
int info2[4];
cpuid(info2, 7, 0);
bool have_avx2 = info[2] & (1 << 5);
if (have_avx2) {
// AVX 2
// For now we just return avx.
return "x86-64-avx";
} else {
// AVX with float16 and rdrand
// For now we just return avx.
return "x86-64-avx";
}
}
// Regular AVX
return "x86-64-avx";
} else if (have_sse41) {
// SSE4.1
return "x86-64-sse41";
} else if (have_sse2) {
// SSE2
return "x86-64";
} else {
}
} else {
// 32-bit targets
if ((info[2] & (1 << 19)) != 0) {
// SSE4.1
return "x86-32-sse41";
} else if ((info[3] & (1 << 26)) != 0) {
// SSE2
return "x86-32";
}
}
std::cerr << "cpuid instruction returned " << std::hex
<< info[0] << ", "
<< info[1] << ", "
<< info[2] << ", "
<< info[3] << "\n";
assert(false && "No SSE2 support, or failed to correctly interpret the result of cpuid.");
return "";
#endif
}
string get_target() {
string native = get_native_target();
#ifdef _WIN32
char target[128];
size_t read = 0;
getenv_s(&read, target, "HL_TARGET");
if (read) return target;
else return native;
#else
char *target = getenv("HL_TARGET");
if (target) return target;
else return native;
#endif
}
namespace Internal {
StmtCompiler::StmtCompiler(string arch) {
string native = get_native_target();
if (arch == "native") {
arch = get_native_target();
} else if (arch.empty()) {
// Use HL_TARGET.
arch = get_target();
}
if (arch == "x86-32") {
contents = new CodeGen_X86();
} else if (arch == "x86-32-sse41") {
contents = new CodeGen_X86(X86_SSE41);
} else if (arch == "x86-64") {
// Lowest-common-denominator for 64-bit x86, including those
// without SSE4.1 (e.g. Clovertown) or SSSE3 (e.g. early AMD parts)...
// essentially, just SSE2.
contents = new CodeGen_X86(X86_64Bit);
} else if (arch == "x86-64-sse41") {
contents = new CodeGen_X86(X86_64Bit | X86_SSE41);
} else if (arch == "x86-64-avx") {
contents = new CodeGen_X86(X86_64Bit | X86_SSE41 | X86_AVX);
} else if (arch == "x86-32-nacl") {
contents = new CodeGen_X86(X86_NaCl);
} else if (arch == "x86-32-sse41-nacl") {
contents = new CodeGen_X86(X86_SSE41 | X86_NaCl);
} else if (arch == "x86-64-nacl") {
contents = new CodeGen_X86(X86_64Bit | X86_NaCl);
} else if (arch == "x86-64-sse41-nacl") {
contents = new CodeGen_X86(X86_64Bit | X86_SSE41 | X86_NaCl);
} else if (arch == "x86-64-avx-nacl") {
contents = new CodeGen_X86(X86_64Bit | X86_SSE41 | X86_AVX | X86_NaCl);
}
#ifndef _WIN32 // I've temporarily disabled ARM on Windows since it leads to a linking error on halide_internal_initmod_arm stuff (kwampler@adobe.com)
else if (arch == "arm") {
contents = new CodeGen_ARM();
} else if (arch == "arm-android") {
contents = new CodeGen_ARM(ARM_Android);
} else if (arch == "arm-ios") {
contents = new CodeGen_ARM(ARM_IOS);
} else if (arch == "arm-nacl") {
contents = new CodeGen_ARM(ARM_NaCl);
}
// GPU backends are disabled on Windows until I'm sure it links, too (@jrk)
else if (arch == "ptx") {
// equivalent to "x86" on the host side, i.e. x86_64, no AVX
contents = new CodeGen_GPU_Host(X86_64Bit | X86_SSE41 | GPU_PTX);
} else if (arch == "ptx-debug") {
contents = new CodeGen_GPU_Host(X86_64Bit | X86_SSE41 | GPU_PTX | GPU_debug);
} else if (arch == "opencl") {
// equivalent to "x86" on the host side, i.e. x86_64, no AVX
contents = new CodeGen_GPU_Host(X86_64Bit | X86_SSE41 | GPU_OpenCL);
}
#endif // _WIN32
else {
std::cerr << "Unknown target \"" << arch << "\"\n"
<< "Known targets are: "
<< "x86-32 x86-32-sse41 "
<< "x86-64 x86-64-sse41 x86-64-avx "
<< "x86-32-nacl x86-32-sse41-nacl "
<< "x86-64-nacl x86-64-sse41-nacl x86-64-avx-nacl "
<< "arm arm-android arm-ios arm-nacl "
<< "ptx ptx-debug opencl "
<< "native"
<< "\n"
<< "On this machine, native means " << native << "\n";
assert(false);
}
}
void StmtCompiler::compile(Stmt stmt, string name, const vector<Argument> &args) {
contents.ptr->compile(stmt, name, args);
}
void StmtCompiler::compile_to_bitcode(const string &filename) {
contents.ptr->compile_to_bitcode(filename);
}
void StmtCompiler::compile_to_native(const string &filename, bool assembly) {
contents.ptr->compile_to_native(filename, assembly);
}
JITCompiledModule StmtCompiler::compile_to_function_pointers() {
return contents.ptr->compile_to_function_pointers();
}
}
}
<|endoftext|> |
<commit_before>
// Copyright 2014 Toggl Desktop developers.
#include "./ui.h"
#include <cstdlib>
#include <sstream>
namespace kopsik {
void UI::DisplayLogin(const _Bool open, const uint64_t user_id) {
logger().debug("DisplayLogin");
on_display_login_(open, user_id);
}
_Bool UI::DisplayError(const error err) {
if (noError == err) {
return true;
}
if (isNetworkingError(err)) {
DisplayOnlineState(false);
return false;
}
logger().debug("DisplayError");
if (err.find("Request to server failed with status code: 403")
!= std::string::npos) {
on_display_error_("Invalid e-mail or password!", true);
return false;
}
on_display_error_(err.c_str(), isUserError(err));
return false;
}
error UI::VerifyCallbacks() {
logger().debug("VerifyCallbacks");
error err = findMissingCallbacks();
if (err != noError) {
logger().error(err);
}
std::stringstream ss;
ss << "sizeof(int64_t)=" << sizeof(int64_t)
<< ", sizeof(uint64_t)=" << sizeof(uint64_t)
<< ", sizeof(_Bool)=" << sizeof(_Bool)
<< ", sizeof(void *)=" << sizeof(void *) // NOLINT
<< ", sizeof(KopsikTimeEntryViewItem)=" <<
sizeof(KopsikTimeEntryViewItem)
<< ", sizeof(KopsikAutocompleteItem)=" << sizeof(KopsikAutocompleteItem)
<< ", sizeof(KopsikViewItem)=" << sizeof(KopsikViewItem)
<< ", sizeof(KopsikSettingsViewItem)=" << sizeof(KopsikSettingsViewItem)
<< std::endl;
logger().debug(ss.str());
return err;
}
error UI::findMissingCallbacks() {
if (!on_display_error_) {
return error("!on_display_error_");
}
if (!on_display_update_) {
return error("!on_display_update_");
}
if (!on_display_online_state_) {
return error("!on_display_online_state_");
}
if (!on_display_login_) {
return error("!on_display_login_");
}
if (!on_display_url_) {
return error("!on_display_url_");
}
if (!on_display_reminder_) {
return error("!on_display_reminder_");
}
if (!on_display_time_entry_list_) {
return error("!on_display_time_entry_list_");
}
if (!on_display_autocomplete_) {
return error("!on_display_autocomplete_");
}
if (!on_display_workspace_select_) {
return error("!on_display_workspace_select_");
}
if (!on_display_client_select_) {
return error("!on_display_client_select_");
}
if (!on_display_tags_) {
return error("!on_display_tags_");
}
if (!on_display_time_entry_editor_) {
return error("!on_display_time_entry_editor_");
}
if (!on_display_settings_) {
return error("!on_display_settings_");
}
if (!on_display_timer_state_) {
return error("!on_display_timer_state_");
}
return noError;
}
void UI::DisplayReminder() {
logger().debug("DisplayReminder");
on_display_reminder_("Reminder from Toggl Desktop",
"Don't forget to track your time!");
}
void UI::DisplayOnlineState(const _Bool is_online) {
logger().debug("DisplayOnlineState");
on_display_online_state_(is_online);
}
void UI::DisplayUpdate(const bool is_available,
const std::string url,
const std::string version) {
logger().debug("DisplayUpdate");
on_display_update_(is_available, url.c_str(), version.c_str());
}
void UI::DisplayAutocomplete(std::vector<kopsik::AutocompleteItem> *items) {
logger().debug("DisplayAutocomplete");
KopsikAutocompleteItem *first = 0;
for (std::vector<kopsik::AutocompleteItem>::const_iterator it =
items->begin(); it != items->end(); it++) {
KopsikAutocompleteItem *item = autocomplete_item_init(*it);
item->Next = first;
first = item;
}
on_display_autocomplete_(first);
autocomplete_item_clear(first);
}
void UI::DisplayTimeEntryList(const _Bool open,
KopsikTimeEntryViewItem* first) {
logger().debug("DisplayTimeEntryList");
on_display_time_entry_list_(open, first);
}
void UI::DisplayTags(std::vector<std::string> *tags) {
logger().debug("DisplayTags");
KopsikViewItem *first = 0;
for (std::vector<std::string>::const_iterator it = tags->begin();
it != tags->end(); it++) {
std::string name = *it;
KopsikViewItem *item = tag_to_view_item(name);
item->Next = first;
first = item;
}
on_display_tags_(first);
view_item_clear(first);
}
void UI::DisplayClientSelect(std::vector<kopsik::Client *> *clients) {
logger().debug("DisplayClientSelect");
KopsikViewItem *first = 0;
for (std::vector<kopsik::Client *>::const_iterator it = clients->begin();
it != clients->end(); it++) {
KopsikViewItem *item = client_to_view_item(*it);
item->Next = first;
first = item;
}
on_display_client_select_(first);
view_item_clear(first);
}
void UI::DisplayWorkspaceSelect(std::vector<kopsik::Workspace *> *list) {
logger().debug("DisplayWorkspaceSelect");
KopsikViewItem *first = 0;
for (std::vector<kopsik::Workspace *>::const_iterator it =
list->begin(); it != list->end(); it++) {
KopsikViewItem *item = workspace_to_view_item(*it);
item->Next = first;
first = item;
}
on_display_workspace_select_(first);
view_item_clear(first);
}
void UI::DisplayTimeEntryEditor(const _Bool open,
KopsikTimeEntryViewItem *te,
const std::string focused_field_name) {
logger().debug("DisplayTimeEntryEditor");
on_display_time_entry_editor_(open, te, focused_field_name.c_str());
}
void UI::DisplayURL(const std::string URL) {
logger().debug("DisplayURL");
on_display_url_(URL.c_str());
}
void UI::DisplaySettings(const _Bool open,
const _Bool record_timeline,
const Settings settings,
const _Bool use_proxy,
const Proxy proxy) {
logger().debug("DisplaySettings");
KopsikSettingsViewItem *view = settings_view_item_init(
record_timeline,
settings,
use_proxy,
proxy);
on_display_settings_(open, view);
settings_view_item_clear(view);
}
void UI::DisplayTimerState(KopsikTimeEntryViewItem *te) {
logger().debug("DisplayTimerState");
on_display_timer_state_(te);
}
_Bool UI::isNetworkingError(const error err) const {
std::string value(err);
if (value.find("Host not found") != std::string::npos) {
return true;
}
if (value.find("Cannot upgrade to WebSocket connection")
!= std::string::npos) { // NOLINT
return true;
}
if (value.find("No message received") != std::string::npos) {
return true;
}
if (value.find("Connection refused") != std::string::npos) {
return true;
}
if (value.find("Connection timed out") != std::string::npos) {
return true;
}
if (value.find("connect timed out") != std::string::npos) {
return true;
}
if (value.find("SSL connection unexpectedly closed") != std::string::npos) {
return true;
}
if (value.find("Network is down") != std::string::npos) {
return true;
}
if (value.find("Network is unreachable") != std::string::npos) {
return true;
}
if (value.find("Host is down") != std::string::npos) {
return true;
}
if (value.find("No route to host") != std::string::npos) {
return true;
}
if ((value.find("I/O error: 1") != std::string::npos)
&& (value.find(":443") != std::string::npos)) {
return true;
}
if (value.find("The request timed out") != std::string::npos) {
return true;
}
if (value.find("Could not connect to the server") != std::string::npos) {
return true;
}
if (value.find("Connection reset by peer") != std::string::npos) {
return true;
}
if (value.find("The Internet connection appears to be offline")
!= std::string::npos) {
return true;
}
return false;
}
_Bool UI::isUserError(const error err) const {
if (noError == err) {
return false;
}
std::string value(err);
if (value.find("is suspended") != std::string::npos) {
return true;
}
if (value.find("Request to server failed with status code: 403")
!= std::string::npos) {
return true;
}
return false;
}
} // namespace kopsik
<commit_msg>Dont send 'Stop time must be after start time' to bugsnag<commit_after>
// Copyright 2014 Toggl Desktop developers.
#include "./ui.h"
#include <cstdlib>
#include <sstream>
namespace kopsik {
void UI::DisplayLogin(const _Bool open, const uint64_t user_id) {
logger().debug("DisplayLogin");
on_display_login_(open, user_id);
}
_Bool UI::DisplayError(const error err) {
if (noError == err) {
return true;
}
if (isNetworkingError(err)) {
DisplayOnlineState(false);
return false;
}
logger().debug("DisplayError");
if (err.find("Request to server failed with status code: 403")
!= std::string::npos) {
on_display_error_("Invalid e-mail or password!", true);
return false;
}
on_display_error_(err.c_str(), isUserError(err));
return false;
}
error UI::VerifyCallbacks() {
logger().debug("VerifyCallbacks");
error err = findMissingCallbacks();
if (err != noError) {
logger().error(err);
}
std::stringstream ss;
ss << "sizeof(int64_t)=" << sizeof(int64_t)
<< ", sizeof(uint64_t)=" << sizeof(uint64_t)
<< ", sizeof(_Bool)=" << sizeof(_Bool)
<< ", sizeof(void *)=" << sizeof(void *) // NOLINT
<< ", sizeof(KopsikTimeEntryViewItem)=" <<
sizeof(KopsikTimeEntryViewItem)
<< ", sizeof(KopsikAutocompleteItem)=" << sizeof(KopsikAutocompleteItem)
<< ", sizeof(KopsikViewItem)=" << sizeof(KopsikViewItem)
<< ", sizeof(KopsikSettingsViewItem)=" << sizeof(KopsikSettingsViewItem)
<< std::endl;
logger().debug(ss.str());
return err;
}
error UI::findMissingCallbacks() {
if (!on_display_error_) {
return error("!on_display_error_");
}
if (!on_display_update_) {
return error("!on_display_update_");
}
if (!on_display_online_state_) {
return error("!on_display_online_state_");
}
if (!on_display_login_) {
return error("!on_display_login_");
}
if (!on_display_url_) {
return error("!on_display_url_");
}
if (!on_display_reminder_) {
return error("!on_display_reminder_");
}
if (!on_display_time_entry_list_) {
return error("!on_display_time_entry_list_");
}
if (!on_display_autocomplete_) {
return error("!on_display_autocomplete_");
}
if (!on_display_workspace_select_) {
return error("!on_display_workspace_select_");
}
if (!on_display_client_select_) {
return error("!on_display_client_select_");
}
if (!on_display_tags_) {
return error("!on_display_tags_");
}
if (!on_display_time_entry_editor_) {
return error("!on_display_time_entry_editor_");
}
if (!on_display_settings_) {
return error("!on_display_settings_");
}
if (!on_display_timer_state_) {
return error("!on_display_timer_state_");
}
return noError;
}
void UI::DisplayReminder() {
logger().debug("DisplayReminder");
on_display_reminder_("Reminder from Toggl Desktop",
"Don't forget to track your time!");
}
void UI::DisplayOnlineState(const _Bool is_online) {
logger().debug("DisplayOnlineState");
on_display_online_state_(is_online);
}
void UI::DisplayUpdate(const bool is_available,
const std::string url,
const std::string version) {
logger().debug("DisplayUpdate");
on_display_update_(is_available, url.c_str(), version.c_str());
}
void UI::DisplayAutocomplete(std::vector<kopsik::AutocompleteItem> *items) {
logger().debug("DisplayAutocomplete");
KopsikAutocompleteItem *first = 0;
for (std::vector<kopsik::AutocompleteItem>::const_iterator it =
items->begin(); it != items->end(); it++) {
KopsikAutocompleteItem *item = autocomplete_item_init(*it);
item->Next = first;
first = item;
}
on_display_autocomplete_(first);
autocomplete_item_clear(first);
}
void UI::DisplayTimeEntryList(const _Bool open,
KopsikTimeEntryViewItem* first) {
logger().debug("DisplayTimeEntryList");
on_display_time_entry_list_(open, first);
}
void UI::DisplayTags(std::vector<std::string> *tags) {
logger().debug("DisplayTags");
KopsikViewItem *first = 0;
for (std::vector<std::string>::const_iterator it = tags->begin();
it != tags->end(); it++) {
std::string name = *it;
KopsikViewItem *item = tag_to_view_item(name);
item->Next = first;
first = item;
}
on_display_tags_(first);
view_item_clear(first);
}
void UI::DisplayClientSelect(std::vector<kopsik::Client *> *clients) {
logger().debug("DisplayClientSelect");
KopsikViewItem *first = 0;
for (std::vector<kopsik::Client *>::const_iterator it = clients->begin();
it != clients->end(); it++) {
KopsikViewItem *item = client_to_view_item(*it);
item->Next = first;
first = item;
}
on_display_client_select_(first);
view_item_clear(first);
}
void UI::DisplayWorkspaceSelect(std::vector<kopsik::Workspace *> *list) {
logger().debug("DisplayWorkspaceSelect");
KopsikViewItem *first = 0;
for (std::vector<kopsik::Workspace *>::const_iterator it =
list->begin(); it != list->end(); it++) {
KopsikViewItem *item = workspace_to_view_item(*it);
item->Next = first;
first = item;
}
on_display_workspace_select_(first);
view_item_clear(first);
}
void UI::DisplayTimeEntryEditor(const _Bool open,
KopsikTimeEntryViewItem *te,
const std::string focused_field_name) {
logger().debug("DisplayTimeEntryEditor");
on_display_time_entry_editor_(open, te, focused_field_name.c_str());
}
void UI::DisplayURL(const std::string URL) {
logger().debug("DisplayURL");
on_display_url_(URL.c_str());
}
void UI::DisplaySettings(const _Bool open,
const _Bool record_timeline,
const Settings settings,
const _Bool use_proxy,
const Proxy proxy) {
logger().debug("DisplaySettings");
KopsikSettingsViewItem *view = settings_view_item_init(
record_timeline,
settings,
use_proxy,
proxy);
on_display_settings_(open, view);
settings_view_item_clear(view);
}
void UI::DisplayTimerState(KopsikTimeEntryViewItem *te) {
logger().debug("DisplayTimerState");
on_display_timer_state_(te);
}
_Bool UI::isNetworkingError(const error err) const {
std::string value(err);
if (value.find("Host not found") != std::string::npos) {
return true;
}
if (value.find("Cannot upgrade to WebSocket connection")
!= std::string::npos) { // NOLINT
return true;
}
if (value.find("No message received") != std::string::npos) {
return true;
}
if (value.find("Connection refused") != std::string::npos) {
return true;
}
if (value.find("Connection timed out") != std::string::npos) {
return true;
}
if (value.find("connect timed out") != std::string::npos) {
return true;
}
if (value.find("SSL connection unexpectedly closed") != std::string::npos) {
return true;
}
if (value.find("Network is down") != std::string::npos) {
return true;
}
if (value.find("Network is unreachable") != std::string::npos) {
return true;
}
if (value.find("Host is down") != std::string::npos) {
return true;
}
if (value.find("No route to host") != std::string::npos) {
return true;
}
if ((value.find("I/O error: 1") != std::string::npos)
&& (value.find(":443") != std::string::npos)) {
return true;
}
if (value.find("The request timed out") != std::string::npos) {
return true;
}
if (value.find("Could not connect to the server") != std::string::npos) {
return true;
}
if (value.find("Connection reset by peer") != std::string::npos) {
return true;
}
if (value.find("The Internet connection appears to be offline")
!= std::string::npos) {
return true;
}
return false;
}
_Bool UI::isUserError(const error err) const {
if (noError == err) {
return false;
}
std::string value(err);
if (value.find("is suspended") != std::string::npos) {
return true;
}
if (value.find("Request to server failed with status code: 403")
!= std::string::npos) {
return true;
}
if (value.find("Stop time must be after start time")
!= std::string::npos) {
return true;
}
return false;
}
} // namespace kopsik
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <memory>
#include <mutex>
#include <set>
#include <tuple>
#include "balancer.hpp"
#include "connection.hpp"
#include "log.hpp"
#include "pool.hpp"
#include "resolver.hpp"
#include "result.hpp"
#include "request/info.hpp"
#include "settings.hpp"
namespace elasticsearch {
void nullcb() {}
template<class Action> struct error_handler_t;
template<class Action> struct request_watcher_t;
const std::string INET_ADDR_PREFIX = "inet[";
const std::string INET_ADDR_SUFFIX = "]";
class http_transport_t {
public:
typedef blackhole::synchronized<blackhole::logger_base_t> logger_type;
typedef boost::asio::io_service loop_type;
typedef http_connection_t connection_type;
typedef pool_t<connection_type> pool_type;
typedef pool_type::endpoint_type endpoint_type;
template<class Action> friend struct error_handler_t;
template<class Action> friend struct request_watcher_t;
private:
settings_t settings;
loop_type& loop;
logger_type& log;
pool_type pool;
std::unique_ptr<balancing::strategy<pool_type>> balancer;
urlfetcher_t urlfetcher;
public:
http_transport_t(settings_t settings, loop_type& loop, logger_type& log) :
settings(settings),
loop(loop),
log(log),
balancer(new balancing::round_robin<pool_type>()),
urlfetcher(loop)
{}
void add_nodes(const std::vector<endpoint_type>& endpoints) {
for (auto it = endpoints.begin(); it != endpoints.end(); ++it) {
add_node(*it);
}
}
void add_node(const endpoint_type& endpoint) {
boost::system::error_code ec;
auto address = endpoint.address().to_string(ec);
if (ec) {
LOG(log, "can't add node endpoint '%s': %s", endpoint, ec.message());
return;
}
LOG(log, "adding '%s:%d' to the pool ...", address, endpoint.port());
bool inserted;
std::tie(std::ignore, inserted) = pool.insert(
endpoint,
std::make_shared<connection_type>(
endpoint,
settings.connections,
urlfetcher,
log
)
);
if (!inserted) {
LOG(log, "adding endpoint to the pool is rejected - already exists");
return;
}
}
void remove_node(const endpoint_type& endpoint) {
LOG(log, "removing '%s' from the pool ...", endpoint);
pool.remove(endpoint);
}
void sniff() {
sniff(&nullcb);
}
void sniff(std::function<void()>&& then) {
LOG(log, "sniffing nodes info ...");
auto callback = std::bind(
&http_transport_t::on_sniff, this, std::placeholders::_1, then
);
perform(actions::nodes_info_t(), callback);
}
template<class Action>
void perform(Action&& action,
typename callback<Action>::type callback,
int attempt = 1) {
typedef typename Action::result_type result_type;
BOOST_ASSERT(balancer);
LOG(log, "performing '%s' request [attempt %d from %d] ...",
action.name(), attempt, settings.retries);
if (attempt > settings.retries) {
LOG(log, "failed: too many attempts done");
loop.post(
std::bind(
callback,
result_type(error_t(generic_error_t("too many attempts")))
)
);
return;
}
auto connection = balancer->next(pool);
if (!connection) {
if (attempt == 1) {
add_nodes(settings.endpoints);
//!@todo: Ideally it must be handled via loop.post.
perform(std::move(action), callback, ++attempt);
} else {
LOG(log, "failed: no connections left");
loop.post(
std::bind(
callback,
result_type(error_t(generic_error_t("no connections left")))
)
);
}
return;
}
LOG(log, "balancing at %s", connection->endpoint());
request_watcher_t<Action> watcher {
*this, action, callback, ++attempt
};
connection->perform(std::move(action), watcher);
}
private:
void on_sniff(result_t<response::nodes_info_t>::type&& result,
std::function<void()> next) {
if (auto* info = boost::get<response::nodes_info_t>(&result)) {
LOG(log, "successfully sniffed %d node%s",
info->nodes.size(),
info->nodes.size() > 1 ? "s" : ""
);
std::set<std::string> addresses;
const auto& nodes = info->nodes;
for (auto it = nodes.begin(); it != nodes.end(); ++it) {
const response::node_t& node = it->second;
extract_addresses(addresses, node.addresses);
}
typedef boost::asio::ip::tcp protocol_type;
std::vector<endpoint_type> endpoints;
for (auto it = addresses.begin(); it != addresses.end(); ++it) {
try {
endpoints.push_back(
resolver<protocol_type>::resolve(*it, loop)
);
} catch (const std::exception& err) {
LOG(log, "failed to resolve %s address: %s", *it, err.what());
}
}
add_nodes(endpoints);
}
next();
}
void extract_addresses(std::set<std::string>& result,
const response::node_t::addresses_type& addresses) const {
auto it = addresses.find("http");
if (it == addresses.end()) {
return;
}
const std::string& address = it->second;
if (boost::algorithm::starts_with(address, INET_ADDR_PREFIX)) {
const std::string& parsed = address.substr(
INET_ADDR_PREFIX.size(),
address.size() -
INET_ADDR_PREFIX.size() -
INET_ADDR_SUFFIX.size()
);
result.insert(parsed);
} else {
LOG(log, "unknown address type: %s", address);
}
}
};
template<class Watcher>
struct error_handler_t : public boost::static_visitor<> {
typedef Watcher watcher_type;
const watcher_type& watcher;
error_handler_t(const watcher_type& watcher) :
watcher(watcher)
{}
void operator()(const connection_error_t& err) {
http_transport_t& transport = watcher.transport;
LOG(transport.log, "request failed with error: %s", err.reason);
transport.remove_node(err.endpoint);
if (transport.settings.sniffer.when.error) {
LOG(transport.log,
"sniff.on.error is true - preparing to update nodes list");
transport.sniff(watcher);
return;
}
}
void operator()(const generic_error_t& err) {
LOG(watcher.transport.log, "request failed with error: %s", err.reason);
}
};
template<class Action>
struct request_watcher_t {
typedef Action action_type;
typedef request_watcher_t<action_type> this_type;
typedef typename action_type::result_type result_type;
typedef typename callback<action_type>::type callback_type;
friend struct error_handler_t<request_watcher_t>;
http_transport_t& transport;
const action_type action;
const callback_type callback;
const int attempt;
template<class Result = result_type>
typename std::enable_if<
!std::is_same<Result, result_t<response::nodes_info_t>::type>::value
>::type
operator()(result_type&& result) const {
if (error_t* error = boost::get<error_t>(&result)) {
auto visitor = error_handler_t<this_type>(*this);
boost::apply_visitor(visitor, *error);
}
callback(std::move(result));
}
template<class Result = result_type>
typename std::enable_if<
std::is_same<Result, result_t<response::nodes_info_t>::type>::value
>::type
operator()(result_t<response::nodes_info_t>::type&& result) const {
callback(std::move(result));
}
void operator()() {
transport.perform(std::move(action), callback, attempt);
}
};
} // namespace elasticsearch
<commit_msg>[Elasticsearch] Wording.<commit_after>#pragma once
#include <string>
#include <memory>
#include <mutex>
#include <set>
#include <tuple>
#include "balancer.hpp"
#include "connection.hpp"
#include "log.hpp"
#include "pool.hpp"
#include "resolver.hpp"
#include "result.hpp"
#include "request/info.hpp"
#include "settings.hpp"
namespace elasticsearch {
void nullcb() {}
template<class Action> struct error_handler_t;
template<class Action> struct request_watcher_t;
const std::string INET_ADDR_PREFIX = "inet[";
const std::string INET_ADDR_SUFFIX = "]";
class http_transport_t {
public:
typedef blackhole::synchronized<blackhole::logger_base_t> logger_type;
typedef boost::asio::io_service loop_type;
typedef http_connection_t connection_type;
typedef pool_t<connection_type> pool_type;
typedef pool_type::endpoint_type endpoint_type;
template<class Action> friend struct error_handler_t;
template<class Action> friend struct request_watcher_t;
private:
settings_t settings;
loop_type& loop;
logger_type& log;
pool_type pool;
std::unique_ptr<balancing::strategy<pool_type>> balancer;
urlfetcher_t urlfetcher;
public:
http_transport_t(settings_t settings, loop_type& loop, logger_type& log) :
settings(settings),
loop(loop),
log(log),
balancer(new balancing::round_robin<pool_type>()),
urlfetcher(loop)
{}
void add_nodes(const std::vector<endpoint_type>& endpoints) {
for (auto it = endpoints.begin(); it != endpoints.end(); ++it) {
add_node(*it);
}
}
void add_node(const endpoint_type& endpoint) {
boost::system::error_code ec;
auto address = endpoint.address().to_string(ec);
if (ec) {
LOG(log, "can't add node endpoint '%s': %s", endpoint, ec.message());
return;
}
LOG(log, "adding '%s:%d' to the pool ...", address, endpoint.port());
bool inserted;
std::tie(std::ignore, inserted) = pool.insert(
endpoint,
std::make_shared<connection_type>(
endpoint,
settings.connections,
urlfetcher,
log
)
);
if (!inserted) {
LOG(log, "adding endpoint to the pool is rejected - already exists");
return;
}
}
void remove_node(const endpoint_type& endpoint) {
LOG(log, "removing '%s' from the pool ...", endpoint);
pool.remove(endpoint);
}
void sniff() {
sniff(&nullcb);
}
void sniff(std::function<void()>&& then) {
LOG(log, "sniffing nodes info ...");
auto callback = std::bind(
&http_transport_t::on_sniff, this, std::placeholders::_1, then
);
perform(actions::nodes_info_t(), callback);
}
template<class Action>
void perform(Action&& action,
typename callback<Action>::type callback,
int attempt = 1) {
typedef typename Action::result_type result_type;
BOOST_ASSERT(balancer);
LOG(log, "performing '%s' request [attempt %d/%d] ...",
action.name(), attempt, settings.retries);
if (attempt > settings.retries) {
LOG(log, "failed: too many attempts done");
loop.post(
std::bind(
callback,
result_type(error_t(generic_error_t("too many attempts")))
)
);
return;
}
auto connection = balancer->next(pool);
if (!connection) {
if (attempt == 1) {
add_nodes(settings.endpoints);
//!@todo: Ideally it must be handled via loop.post.
perform(std::move(action), callback, ++attempt);
} else {
LOG(log, "failed: no connections left");
loop.post(
std::bind(
callback,
result_type(error_t(generic_error_t("no connections left")))
)
);
}
return;
}
LOG(log, "balancing at %s", connection->endpoint());
request_watcher_t<Action> watcher {
*this, action, callback, ++attempt
};
connection->perform(std::move(action), watcher);
}
private:
void on_sniff(result_t<response::nodes_info_t>::type&& result,
std::function<void()> next) {
if (auto* info = boost::get<response::nodes_info_t>(&result)) {
LOG(log, "successfully sniffed %d node%s",
info->nodes.size(),
info->nodes.size() > 1 ? "s" : ""
);
std::set<std::string> addresses;
const auto& nodes = info->nodes;
for (auto it = nodes.begin(); it != nodes.end(); ++it) {
const response::node_t& node = it->second;
extract_addresses(addresses, node.addresses);
}
typedef boost::asio::ip::tcp protocol_type;
std::vector<endpoint_type> endpoints;
for (auto it = addresses.begin(); it != addresses.end(); ++it) {
try {
endpoints.push_back(
resolver<protocol_type>::resolve(*it, loop)
);
} catch (const std::exception& err) {
LOG(log, "failed to resolve %s address: %s", *it, err.what());
}
}
add_nodes(endpoints);
}
next();
}
void extract_addresses(std::set<std::string>& result,
const response::node_t::addresses_type& addresses) const {
auto it = addresses.find("http");
if (it == addresses.end()) {
return;
}
const std::string& address = it->second;
if (boost::algorithm::starts_with(address, INET_ADDR_PREFIX)) {
const std::string& parsed = address.substr(
INET_ADDR_PREFIX.size(),
address.size() -
INET_ADDR_PREFIX.size() -
INET_ADDR_SUFFIX.size()
);
result.insert(parsed);
} else {
LOG(log, "unknown address type: %s", address);
}
}
};
template<class Watcher>
struct error_handler_t : public boost::static_visitor<> {
typedef Watcher watcher_type;
const watcher_type& watcher;
error_handler_t(const watcher_type& watcher) :
watcher(watcher)
{}
void operator()(const connection_error_t& err) {
http_transport_t& transport = watcher.transport;
LOG(transport.log, "request failed with error: %s", err.reason);
transport.remove_node(err.endpoint);
if (transport.settings.sniffer.when.error) {
LOG(transport.log,
"sniff.on.error is true - preparing to update nodes list");
transport.sniff(watcher);
return;
}
}
void operator()(const generic_error_t& err) {
LOG(watcher.transport.log, "request failed with error: %s", err.reason);
}
};
template<class Action>
struct request_watcher_t {
typedef Action action_type;
typedef request_watcher_t<action_type> this_type;
typedef typename action_type::result_type result_type;
typedef typename callback<action_type>::type callback_type;
friend struct error_handler_t<request_watcher_t>;
http_transport_t& transport;
const action_type action;
const callback_type callback;
const int attempt;
template<class Result = result_type>
typename std::enable_if<
!std::is_same<Result, result_t<response::nodes_info_t>::type>::value
>::type
operator()(result_type&& result) const {
if (error_t* error = boost::get<error_t>(&result)) {
auto visitor = error_handler_t<this_type>(*this);
boost::apply_visitor(visitor, *error);
}
callback(std::move(result));
}
template<class Result = result_type>
typename std::enable_if<
std::is_same<Result, result_t<response::nodes_info_t>::type>::value
>::type
operator()(result_t<response::nodes_info_t>::type&& result) const {
callback(std::move(result));
}
void operator()() {
transport.perform(std::move(action), callback, attempt);
}
};
} // namespace elasticsearch
<|endoftext|> |
<commit_before>/***************************************************************************
copyright : (C) 2010 by Alex Novichkov
email : novichko@atnet.ru
copyright : (C) 2006 by Lukáš Lalinský
email : lalinsky@gmail.com
(original WavPack implementation)
copyright : (C) 2004 by Allan Sandfeld Jensen
email : kde@carewolf.org
(original MPC implementation)
***************************************************************************/
/***************************************************************************
* 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., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tbytevector.h>
#include <tstring.h>
#include <tdebug.h>
#include <tagunion.h>
#include <id3v1tag.h>
#include <tpropertymap.h>
#include "apefile.h"
#include "apetag.h"
#include "apefooter.h"
using namespace TagLib;
namespace
{
enum { APEIndex, ID3v1Index };
}
class APE::File::FilePrivate
{
public:
FilePrivate() :
APELocation(-1),
APESize(0),
ID3v1Location(-1),
properties(0),
hasAPE(false),
hasID3v1(false) {}
~FilePrivate()
{
delete properties;
}
long APELocation;
uint APESize;
long ID3v1Location;
TagUnion tag;
Properties *properties;
// These indicate whether the file *on disk* has these tags, not if
// this data structure does. This is used in computing offsets.
bool hasAPE;
bool hasID3v1;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
APE::File::File(FileName file, bool readProperties,
Properties::ReadStyle propertiesStyle) : TagLib::File(file)
{
d = new FilePrivate;
read(readProperties, propertiesStyle);
}
APE::File::File(IOStream *stream, bool readProperties,
Properties::ReadStyle propertiesStyle) : TagLib::File(stream)
{
d = new FilePrivate;
read(readProperties, propertiesStyle);
}
APE::File::~File()
{
delete d;
}
TagLib::Tag *APE::File::tag() const
{
return &d->tag;
}
PropertyMap APE::File::properties() const
{
if(d->hasAPE)
return d->tag.access<APE::Tag>(APEIndex, false)->properties();
if(d->hasID3v1)
return d->tag.access<ID3v1::Tag>(ID3v1Index, false)->properties();
return PropertyMap();
}
void APE::File::removeUnsupportedProperties(const StringList &properties)
{
if(d->hasAPE)
d->tag.access<APE::Tag>(APEIndex, false)->removeUnsupportedProperties(properties);
if(d->hasID3v1)
d->tag.access<ID3v1::Tag>(ID3v1Index, false)->removeUnsupportedProperties(properties);
}
PropertyMap APE::File::setProperties(const PropertyMap &properties)
{
if(d->hasAPE)
return d->tag.access<APE::Tag>(APEIndex, false)->setProperties(properties);
else if(d->hasID3v1)
return d->tag.access<ID3v1::Tag>(ID3v1Index, false)->setProperties(properties);
else
return d->tag.access<APE::Tag>(APEIndex, true)->setProperties(properties);
}
APE::Properties *APE::File::audioProperties() const
{
return d->properties;
}
bool APE::File::save()
{
if(readOnly()) {
debug("APE::File::save() -- File is read only.");
return false;
}
// Update ID3v1 tag
if(ID3v1Tag()) {
if(d->hasID3v1) {
seek(d->ID3v1Location);
writeBlock(ID3v1Tag()->render());
}
else {
seek(0, End);
d->ID3v1Location = tell();
writeBlock(ID3v1Tag()->render());
d->hasID3v1 = true;
}
}
else {
if(d->hasID3v1) {
removeBlock(d->ID3v1Location, 128);
d->hasID3v1 = false;
if(d->hasAPE) {
if(d->APELocation > d->ID3v1Location)
d->APELocation -= 128;
}
}
}
// Update APE tag
if(APETag()) {
if(d->hasAPE)
insert(APETag()->render(), d->APELocation, d->APESize);
else {
if(d->hasID3v1) {
insert(APETag()->render(), d->ID3v1Location, 0);
d->APESize = APETag()->footer()->completeTagSize();
d->hasAPE = true;
d->APELocation = d->ID3v1Location;
d->ID3v1Location += d->APESize;
}
else {
seek(0, End);
d->APELocation = tell();
writeBlock(APETag()->render());
d->APESize = APETag()->footer()->completeTagSize();
d->hasAPE = true;
}
}
}
else {
if(d->hasAPE) {
removeBlock(d->APELocation, d->APESize);
d->hasAPE = false;
if(d->hasID3v1) {
if(d->ID3v1Location > d->APELocation) {
d->ID3v1Location -= d->APESize;
}
}
}
}
return true;
}
ID3v1::Tag *APE::File::ID3v1Tag(bool create)
{
return d->tag.access<ID3v1::Tag>(ID3v1Index, create);
}
APE::Tag *APE::File::APETag(bool create)
{
return d->tag.access<APE::Tag>(APEIndex, create);
}
void APE::File::strip(int tags)
{
if(tags & ID3v1) {
d->tag.set(ID3v1Index, 0);
APETag(true);
}
if(tags & APE) {
d->tag.set(APEIndex, 0);
if(!ID3v1Tag())
APETag(true);
}
}
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////
void APE::File::read(bool readProperties, Properties::ReadStyle /* propertiesStyle */)
{
// Look for an ID3v1 tag
d->ID3v1Location = findID3v1();
if(d->ID3v1Location >= 0) {
d->tag.set(ID3v1Index, new ID3v1::Tag(this, d->ID3v1Location));
d->hasID3v1 = true;
}
// Look for an APE tag
d->APELocation = findAPE();
if(d->APELocation >= 0) {
d->tag.set(APEIndex, new APE::Tag(this, d->APELocation));
d->APESize = APETag()->footer()->completeTagSize();
d->APELocation = d->APELocation + APETag()->footer()->size() - d->APESize;
d->hasAPE = true;
}
if(!d->hasID3v1)
APETag(true);
// Look for APE audio properties
if(readProperties) {
d->properties = new Properties(this);
}
}
long APE::File::findAPE()
{
if(!isValid())
return -1;
if(d->hasID3v1)
seek(-160, End);
else
seek(-32, End);
long p = tell();
if(readBlock(8) == APE::Tag::fileIdentifier())
return p;
return -1;
}
long APE::File::findID3v1()
{
if(!isValid())
return -1;
seek(-128, End);
long p = tell();
if(readBlock(3) == ID3v1::Tag::fileIdentifier())
return p;
return -1;
}
<commit_msg>Rename anonymous enumeration symbols to be unique in apefile.cpp<commit_after>/***************************************************************************
copyright : (C) 2010 by Alex Novichkov
email : novichko@atnet.ru
copyright : (C) 2006 by Lukáš Lalinský
email : lalinsky@gmail.com
(original WavPack implementation)
copyright : (C) 2004 by Allan Sandfeld Jensen
email : kde@carewolf.org
(original MPC implementation)
***************************************************************************/
/***************************************************************************
* 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., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tbytevector.h>
#include <tstring.h>
#include <tdebug.h>
#include <tagunion.h>
#include <id3v1tag.h>
#include <tpropertymap.h>
#include "apefile.h"
#include "apetag.h"
#include "apefooter.h"
using namespace TagLib;
namespace
{
enum { ApeAPEIndex, ApeID3v1Index };
}
class APE::File::FilePrivate
{
public:
FilePrivate() :
APELocation(-1),
APESize(0),
ID3v1Location(-1),
properties(0),
hasAPE(false),
hasID3v1(false) {}
~FilePrivate()
{
delete properties;
}
long APELocation;
uint APESize;
long ID3v1Location;
TagUnion tag;
Properties *properties;
// These indicate whether the file *on disk* has these tags, not if
// this data structure does. This is used in computing offsets.
bool hasAPE;
bool hasID3v1;
};
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
APE::File::File(FileName file, bool readProperties,
Properties::ReadStyle propertiesStyle) : TagLib::File(file)
{
d = new FilePrivate;
read(readProperties, propertiesStyle);
}
APE::File::File(IOStream *stream, bool readProperties,
Properties::ReadStyle propertiesStyle) : TagLib::File(stream)
{
d = new FilePrivate;
read(readProperties, propertiesStyle);
}
APE::File::~File()
{
delete d;
}
TagLib::Tag *APE::File::tag() const
{
return &d->tag;
}
PropertyMap APE::File::properties() const
{
if(d->hasAPE)
return d->tag.access<APE::Tag>(ApeAPEIndex, false)->properties();
if(d->hasID3v1)
return d->tag.access<ID3v1::Tag>(ApeID3v1Index, false)->properties();
return PropertyMap();
}
void APE::File::removeUnsupportedProperties(const StringList &properties)
{
if(d->hasAPE)
d->tag.access<APE::Tag>(ApeAPEIndex, false)->removeUnsupportedProperties(properties);
if(d->hasID3v1)
d->tag.access<ID3v1::Tag>(ApeID3v1Index, false)->removeUnsupportedProperties(properties);
}
PropertyMap APE::File::setProperties(const PropertyMap &properties)
{
if(d->hasAPE)
return d->tag.access<APE::Tag>(ApeAPEIndex, false)->setProperties(properties);
else if(d->hasID3v1)
return d->tag.access<ID3v1::Tag>(ApeID3v1Index, false)->setProperties(properties);
else
return d->tag.access<APE::Tag>(ApeAPEIndex, true)->setProperties(properties);
}
APE::Properties *APE::File::audioProperties() const
{
return d->properties;
}
bool APE::File::save()
{
if(readOnly()) {
debug("APE::File::save() -- File is read only.");
return false;
}
// Update ID3v1 tag
if(ID3v1Tag()) {
if(d->hasID3v1) {
seek(d->ID3v1Location);
writeBlock(ID3v1Tag()->render());
}
else {
seek(0, End);
d->ID3v1Location = tell();
writeBlock(ID3v1Tag()->render());
d->hasID3v1 = true;
}
}
else {
if(d->hasID3v1) {
removeBlock(d->ID3v1Location, 128);
d->hasID3v1 = false;
if(d->hasAPE) {
if(d->APELocation > d->ID3v1Location)
d->APELocation -= 128;
}
}
}
// Update APE tag
if(APETag()) {
if(d->hasAPE)
insert(APETag()->render(), d->APELocation, d->APESize);
else {
if(d->hasID3v1) {
insert(APETag()->render(), d->ID3v1Location, 0);
d->APESize = APETag()->footer()->completeTagSize();
d->hasAPE = true;
d->APELocation = d->ID3v1Location;
d->ID3v1Location += d->APESize;
}
else {
seek(0, End);
d->APELocation = tell();
writeBlock(APETag()->render());
d->APESize = APETag()->footer()->completeTagSize();
d->hasAPE = true;
}
}
}
else {
if(d->hasAPE) {
removeBlock(d->APELocation, d->APESize);
d->hasAPE = false;
if(d->hasID3v1) {
if(d->ID3v1Location > d->APELocation) {
d->ID3v1Location -= d->APESize;
}
}
}
}
return true;
}
ID3v1::Tag *APE::File::ID3v1Tag(bool create)
{
return d->tag.access<ID3v1::Tag>(ApeID3v1Index, create);
}
APE::Tag *APE::File::APETag(bool create)
{
return d->tag.access<APE::Tag>(ApeAPEIndex, create);
}
void APE::File::strip(int tags)
{
if(tags & ID3v1) {
d->tag.set(ApeID3v1Index, 0);
APETag(true);
}
if(tags & APE) {
d->tag.set(ApeAPEIndex, 0);
if(!ID3v1Tag())
APETag(true);
}
}
////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////
void APE::File::read(bool readProperties, Properties::ReadStyle /* propertiesStyle */)
{
// Look for an ID3v1 tag
d->ID3v1Location = findID3v1();
if(d->ID3v1Location >= 0) {
d->tag.set(ApeID3v1Index, new ID3v1::Tag(this, d->ID3v1Location));
d->hasID3v1 = true;
}
// Look for an APE tag
d->APELocation = findAPE();
if(d->APELocation >= 0) {
d->tag.set(ApeAPEIndex, new APE::Tag(this, d->APELocation));
d->APESize = APETag()->footer()->completeTagSize();
d->APELocation = d->APELocation + APETag()->footer()->size() - d->APESize;
d->hasAPE = true;
}
if(!d->hasID3v1)
APETag(true);
// Look for APE audio properties
if(readProperties) {
d->properties = new Properties(this);
}
}
long APE::File::findAPE()
{
if(!isValid())
return -1;
if(d->hasID3v1)
seek(-160, End);
else
seek(-32, End);
long p = tell();
if(readBlock(8) == APE::Tag::fileIdentifier())
return p;
return -1;
}
long APE::File::findID3v1()
{
if(!isValid())
return -1;
seek(-128, End);
long p = tell();
if(readBlock(3) == ID3v1::Tag::fileIdentifier())
return p;
return -1;
}
<|endoftext|> |
<commit_before>// sensorFile.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iomanip>
#include "keyPoint.h"
#include "imageHelper.h"
class KeyPointMatch {
public:
KeyPoint m_kp0;
KeyPoint m_kp1;
vec2f m_offset; //re-projection offset when m_kp0 is projected into m_kp1;
//std::vector<KeyPoint> m_keyPoints;
};
inline float gaussR(float sigma, float dist)
{
return exp(-(dist*dist) / (2.0f*sigma*sigma));
}
inline float gaussR(float sigma, const vec3f& d)
{
float dist = d.length();
return exp(-(dist*dist) / (2.0f*sigma*sigma));
}
inline float gaussR(float sigma, const vec3uc& d)
{
vec3f _d(d); //_d /= 255.0f;
float dist = _d.length();
return exp(-(dist*dist) / (2.0f*sigma*sigma));
}
inline float linearR(float sigma, float dist)
{
return std::max(1.0f, std::min(0.0f, 1.0f - (dist*dist) / (2.0f*sigma*sigma)));
}
inline float gaussD(float sigma, int x, int y)
{
return exp(-((x*x + y*y) / (2.0f*sigma*sigma)));
}
inline float gaussD(float sigma, int x)
{
return exp(-((x*x) / (2.0f*sigma*sigma)));
}
void bilateralFilter(BaseImage<vec3uc>& img, float sigmaD, float sigmaR) {
BaseImage<vec3uc> res(img.getDimensions());
res.setInvalidValue(img.getInvalidValue());
const int kernelRadius = (int)ceil(2.0*sigmaD);
for (unsigned int y = 0; y < img.getHeight(); y++) {
for (unsigned int x = 0; x < img.getWidth(); x++) {
res.setInvalid(x, y);
vec3f sum = vec3f(0.0f);
float sumWeight = 0.0f;
if (img.isValid(x, y)) {
const vec3uc& center = img(x, y);
for (int m = x - kernelRadius; m <= (int)x + kernelRadius; m++) {
for (int n = y - kernelRadius; n <= (int)y + kernelRadius; n++) {
if (m >= 0 && n >= 0 && m < (int)img.getWidth() && n < (int)img.getHeight()) {
if (img.isValid(m, n)) {
const vec3uc& current = img(m, n);
const float weight = gaussD(sigmaD, m - x, n - y)*gaussR(sigmaR, current - center);
sumWeight += weight;
sum += weight*vec3f(current);
}
}
}
}
if (sumWeight > 0.0f) res(x, y) = math::round(sum / sumWeight);
}
}
}
img = res;
}
class ScannedScene {
public:
ScannedScene(const std::string& path, const std::string& name) {
load(path, name);
}
~ScannedScene() {
for (auto* sd : m_sds) {
SAFE_DELETE(sd);
}
}
void load(const std::string& path, const std::string& name) {
m_name = name;
Directory dir(path);
auto& files = dir.getFilesWithSuffix(".sens");
std::sort(files.begin(), files.end());
for (auto& f : files) {
m_sds.push_back(new SensorData);
SensorData* sd = m_sds.back();
sd->loadFromFile(path + "/" + f);
std::cout << *sd << std::endl;
break;
}
}
void findKeyPoints() {
for (size_t sensorIdx = 0; sensorIdx < m_sds.size(); sensorIdx++) {
SensorData* sd = m_sds[sensorIdx];
const mat4f intrinsicInv = sd->m_calibrationDepth.m_intrinsic.getInverse();
for (size_t imageIdx = 0; imageIdx < sd->m_frames.size(); imageIdx++) {
ColorImageR8G8B8 c = sd->computeColorImage(imageIdx);
DepthImage16 d = sd->computeDepthImage(imageIdx);
//float sigmaD = 2.0f;
//float sigmaR = 0.1f;
//sigmaD = 10.0f;
//sigmaR = 10.0f;
//FreeImageWrapper::saveImage("_before.png", c);
//bilateralFilter(c, sigmaD, sigmaR);
//FreeImageWrapper::saveImage("_after.png", c);
//std::cout << "here" << std::endl;
//getchar();
const mat4f& camToWorld = sd->m_frames[imageIdx].getCameraToWorld();
const unsigned int maxNumKeyPoints = 512;
std::vector<vec3f> rawKeyPoints = KeyPointFinder::findKeyPoints(c, maxNumKeyPoints);
size_t validKeyPoints = 0;
for (vec3f& rawkp : rawKeyPoints) {
vec2ui loc = math::round(vec2f(rawkp.x, rawkp.y));
if (d.isValid(loc)) {
KeyPoint kp;
kp.m_depth = d(loc) / sd->m_depthShift;
kp.m_frameIdx = (unsigned int)imageIdx;
kp.m_sensorIdx = (unsigned int)sensorIdx;
//kp.m_pixelPos = vec2f(rawkp.x, rawkp.y);
kp.m_pixelPos = vec2f(loc);
vec3f cameraPos = (intrinsicInv*vec4f(kp.m_pixelPos.x*kp.m_depth, kp.m_pixelPos.y*kp.m_depth, kp.m_depth, 0.0f)).getVec3();
kp.m_worldPos = camToWorld * cameraPos;
validKeyPoints++;
m_keyPoints.push_back(kp);
}
}
std::cout << "\tfound " << validKeyPoints << " keypoints for image " << sensorIdx << "|" << imageIdx << std::endl;
if (imageIdx == 5) break;
}
}
}
void matchKeyPoints() {
const float radius = 0.1f; //10 cm
const unsigned int maxK = 10;
NearestNeighborSearchFLANNf nn(4*maxK, 1);
std::vector<float> points(3 * m_keyPoints.size());
for (size_t i = 0; i < m_keyPoints.size(); i++) {
points[3 * i + 0] = m_keyPoints[i].m_worldPos.x;
points[3 * i + 1] = m_keyPoints[i].m_worldPos.y;
points[3 * i + 2] = m_keyPoints[i].m_worldPos.z;
}
nn.init(points.data(), m_keyPoints.size(), 3, maxK);
size_t numMatches = 0;
for (size_t i = 0; i < m_keyPoints.size(); i++) {
const float* query = &points[3*i];
std::vector<unsigned int> res = nn.fixedRadius(query, maxK, radius);
auto resPair = nn.fixedRadiusDist(query, maxK, radius);
if (res.size() == 0 || res[0] != i) throw MLIB_EXCEPTION("should find itself...");
for (size_t j = 1; j < res.size(); j++) {
KeyPointMatch m;
m.m_kp0 = m_keyPoints[i];
m.m_kp1 = m_keyPoints[res[j]];
mat4f worldToCam_kp1 = m_sds[m.m_kp1.m_sensorIdx]->m_frames[m.m_kp1.m_frameIdx].getCameraToWorld().getInverse();
vec3f p = worldToCam_kp1 * m.m_kp0.m_worldPos;
p = m_sds[m.m_kp1.m_sensorIdx]->m_calibrationDepth.cameraToProj(p);
m.m_offset = m.m_kp1.m_pixelPos - vec2f(p.x, p.y);
m_keyPointMatches.push_back(m);
numMatches++;
}
std::cout << "numMatches: " << numMatches << std::endl;
}
}
private:
std::vector<SensorData*> m_sds;
std::string m_name;
std::vector<KeyPoint> m_keyPoints;
std::vector<KeyPointMatch> m_keyPointMatches;
};
int main(int argc, char* argv[])
{
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
//_CrtSetBreakAlloc(1489);
try {
const std::string srcPath = "W:/data/matterport/v1_converted";
Directory rootDir(srcPath);
for (const std::string& s : rootDir.getDirectories()) {
if (s == "archive") continue;
std::cout << s << std::endl;
const std::string path = srcPath + "/" + s;
ScannedScene ss(path, s);
ss.findKeyPoints();
ss.matchKeyPoints();
break;
}
}
catch (const std::exception& e)
{
MessageBoxA(NULL, e.what(), "Exception caught", MB_ICONERROR);
exit(EXIT_FAILURE);
}
catch (...)
{
MessageBoxA(NULL, "UNKNOWN EXCEPTION", "Exception caught", MB_ICONERROR);
exit(EXIT_FAILURE);
}
std::cout << "<press key to continue>" << std::endl;
getchar();
return 0;
}
<commit_msg>basic version working; although re-projection error is still pretty high.. intrinsics wrong?<commit_after>// sensorFile.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iomanip>
#include "keyPoint.h"
#include "imageHelper.h"
class KeyPointMatch {
public:
KeyPoint m_kp0;
KeyPoint m_kp1;
vec2f m_offset; //re-projection offset when m_kp0 is projected into m_kp1;
//std::vector<KeyPoint> m_keyPoints;
};
inline float gaussR(float sigma, float dist)
{
return exp(-(dist*dist) / (2.0f*sigma*sigma));
}
inline float gaussR(float sigma, const vec3f& d)
{
float dist = d.length();
return exp(-(dist*dist) / (2.0f*sigma*sigma));
}
inline float gaussR(float sigma, const vec3uc& d)
{
vec3f _d(d); //_d /= 255.0f;
float dist = _d.length();
return exp(-(dist*dist) / (2.0f*sigma*sigma));
}
inline float linearR(float sigma, float dist)
{
return std::max(1.0f, std::min(0.0f, 1.0f - (dist*dist) / (2.0f*sigma*sigma)));
}
inline float gaussD(float sigma, int x, int y)
{
return exp(-((x*x + y*y) / (2.0f*sigma*sigma)));
}
inline float gaussD(float sigma, int x)
{
return exp(-((x*x) / (2.0f*sigma*sigma)));
}
void bilateralFilter(BaseImage<vec3uc>& img, float sigmaD, float sigmaR) {
BaseImage<vec3uc> res(img.getDimensions());
res.setInvalidValue(img.getInvalidValue());
const int kernelRadius = (int)ceil(2.0*sigmaD);
for (unsigned int y = 0; y < img.getHeight(); y++) {
for (unsigned int x = 0; x < img.getWidth(); x++) {
res.setInvalid(x, y);
vec3f sum = vec3f(0.0f);
float sumWeight = 0.0f;
if (img.isValid(x, y)) {
const vec3uc& center = img(x, y);
for (int m = x - kernelRadius; m <= (int)x + kernelRadius; m++) {
for (int n = y - kernelRadius; n <= (int)y + kernelRadius; n++) {
if (m >= 0 && n >= 0 && m < (int)img.getWidth() && n < (int)img.getHeight()) {
if (img.isValid(m, n)) {
const vec3uc& current = img(m, n);
const float weight = gaussD(sigmaD, m - x, n - y)*gaussR(sigmaR, current - center);
sumWeight += weight;
sum += weight*vec3f(current);
}
}
}
}
if (sumWeight > 0.0f) res(x, y) = math::round(sum / sumWeight);
}
}
}
img = res;
}
class ScannedScene {
public:
ScannedScene(const std::string& path, const std::string& name) {
load(path, name);
}
~ScannedScene() {
for (auto* sd : m_sds) {
SAFE_DELETE(sd);
}
}
void load(const std::string& path, const std::string& name) {
m_name = name;
Directory dir(path);
auto& files = dir.getFilesWithSuffix(".sens");
std::sort(files.begin(), files.end());
for (auto& f : files) {
m_sds.push_back(new SensorData);
SensorData* sd = m_sds.back();
sd->loadFromFile(path + "/" + f);
std::cout << *sd << std::endl;
break;
}
}
void findKeyPoints() {
for (size_t sensorIdx = 0; sensorIdx < m_sds.size(); sensorIdx++) {
SensorData* sd = m_sds[sensorIdx];
const mat4f intrinsicInv = sd->m_calibrationDepth.m_intrinsic.getInverse();
for (size_t imageIdx = 0; imageIdx < sd->m_frames.size(); imageIdx++) {
ColorImageR8G8B8 c = sd->computeColorImage(imageIdx);
DepthImage32 d = sd->computeDepthImage(imageIdx);
//float sigmaD = 2.0f;
//float sigmaR = 0.1f;
//sigmaD = 10.0f;
//sigmaR = 10.0f;
//FreeImageWrapper::saveImage("_before.png", c);
//bilateralFilter(c, sigmaD, sigmaR);
//FreeImageWrapper::saveImage("_after.png", c);
//std::cout << "here" << std::endl;
//getchar();
const mat4f& camToWorld = sd->m_frames[imageIdx].getCameraToWorld();
const unsigned int maxNumKeyPoints = 512;
const float minResponse = 0.03f;
std::vector<vec4f> rawKeyPoints = KeyPointFinder::findKeyPoints(c, maxNumKeyPoints, minResponse);
MeshDataf md;
size_t validKeyPoints = 0;
for (vec4f& rawkp : rawKeyPoints) {
const unsigned int padding = 50; //don't take keypoints in the padding region of the image
vec2ui loc = math::round(vec2f(rawkp.x, rawkp.y));
if (d.isValid(loc) && d.isValidCoordinate(loc + padding) && d.isValidCoordinate(loc - padding)) {
KeyPoint kp;
kp.m_depth = d(loc);
kp.m_frameIdx = (unsigned int)imageIdx;
kp.m_sensorIdx = (unsigned int)sensorIdx;
//kp.m_pixelPos = vec2f(rawkp.x, rawkp.y);
kp.m_pixelPos = vec2f(loc);
kp.m_size = rawkp.z;
kp.m_response = rawkp.w;
vec3f cameraPos = (intrinsicInv*vec4f(kp.m_pixelPos.x*kp.m_depth, kp.m_pixelPos.y*kp.m_depth, kp.m_depth, 0.0f)).getVec3();
kp.m_worldPos = camToWorld * cameraPos;
validKeyPoints++;
m_keyPoints.push_back(kp);
if (imageIdx == 0) md.merge(Shapesf::sphere(0.01f, vec3f(kp.m_worldPos), 10, 10, vec4f(1.0f, 0.0f, 0.0f, 1.0f)).computeMeshData());
}
}
std::cout << "\tfound " << validKeyPoints << " keypoints for image " << sensorIdx << "|" << imageIdx << std::endl;
if (imageIdx == 0) MeshIOf::saveToFile("test.ply", md);
if (imageIdx == 50) break;
}
}
}
void matchKeyPoints() {
const float radius = 0.05f; //10 cm
const unsigned int maxK = 5;
unsigned int currKeyPoint = 0;
std::vector<std::vector<NearestNeighborSearchFLANNf*>> nns(m_sds.size());
std::vector<std::vector<unsigned int>> nn_offsets(m_sds.size());
for (size_t sensorIdx = 0; sensorIdx < nns.size(); sensorIdx++) {
nns[sensorIdx].resize(m_sds[sensorIdx]->m_frames.size(), nullptr);
nn_offsets[sensorIdx].resize(m_sds[sensorIdx]->m_frames.size(), 0);
for (size_t frameIdx = 0; frameIdx < m_sds[sensorIdx]->m_frames.size(); frameIdx++) {
nn_offsets[sensorIdx][frameIdx] = currKeyPoint;
std::vector<float> points;
for (; currKeyPoint < (UINT)m_keyPoints.size() &&
m_keyPoints[currKeyPoint].m_sensorIdx == sensorIdx &&
m_keyPoints[currKeyPoint].m_frameIdx == frameIdx; currKeyPoint++) {
points.push_back(m_keyPoints[currKeyPoint].m_worldPos.x);
points.push_back(m_keyPoints[currKeyPoint].m_worldPos.y);
points.push_back(m_keyPoints[currKeyPoint].m_worldPos.z);
}
if (points.size()) {
nns[sensorIdx][frameIdx] = new NearestNeighborSearchFLANNf(4 * maxK, 1);
nns[sensorIdx][frameIdx]->init(points.data(), (unsigned int)points.size() / 3, 3, maxK);
}
}
}
for (size_t keyPointIdx = 0; keyPointIdx < m_keyPoints.size(); keyPointIdx++) {
KeyPoint& kp = m_keyPoints[keyPointIdx];
const float* query = (const float*)&kp.m_worldPos;
const size_t sensorIdx = kp.m_sensorIdx;
const size_t frameIdx = kp.m_frameIdx;
for (size_t sensorIdx_dst = sensorIdx; sensorIdx_dst < nns.size(); sensorIdx_dst++) {
size_t frameIdx_dst = 0;
if (sensorIdx_dst == sensorIdx) frameIdx_dst = frameIdx + 1;
for (; frameIdx_dst < nns[sensorIdx].size(); frameIdx_dst++) {
auto* nn = nns[sensorIdx_dst][frameIdx_dst];
if (nn == nullptr) continue;
size_t numMatches = 0;
std::vector<unsigned int> res = nn->fixedRadius(query, maxK, radius);
auto resPair = nn->fixedRadiusDist(query, maxK, radius);
auto resDist = nn->getDistances((UINT)res.size());
for (size_t j = 0; j < res.size(); j++) {
KeyPointMatch m;
m.m_kp0 = m_keyPoints[keyPointIdx];
m.m_kp1 = m_keyPoints[res[j] + nn_offsets[sensorIdx_dst][frameIdx_dst]];
mat4f worldToCam_kp1 = m_sds[m.m_kp1.m_sensorIdx]->m_frames[m.m_kp1.m_frameIdx].getCameraToWorld().getInverse();
vec3f p = worldToCam_kp1 * m.m_kp0.m_worldPos;
p = m_sds[m.m_kp1.m_sensorIdx]->m_calibrationDepth.cameraToProj(p);
m.m_offset = m.m_kp1.m_pixelPos - vec2f(p.x, p.y);
m_keyPointMatches.push_back(m);
numMatches++;
std::cout << m.m_offset << std::endl;
//std::cout << "match between: " << std::endl;
//std::cout << m.m_kp0;
//std::cout << m.m_kp1;
std::cout << "dist " << sensorIdx << ":\t" << (m.m_kp0.m_worldPos - m.m_kp1.m_worldPos).length() << std::endl;
int a = 5;
}
}
}
}
//clean up our mess...
for (size_t sensorIdx = 0; sensorIdx < nns.size(); sensorIdx++) {
for (size_t frameIdx = 0; frameIdx < nns[sensorIdx].size(); frameIdx++) {
SAFE_DELETE(nns[sensorIdx][frameIdx]);
}
}
}
private:
std::vector<SensorData*> m_sds;
std::string m_name;
std::vector<KeyPoint> m_keyPoints;
std::vector<KeyPointMatch> m_keyPointMatches;
};
int main(int argc, char* argv[])
{
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
//_CrtSetBreakAlloc(1042);
try {
const std::string srcPath = "W:/data/matterport/v1_converted";
Directory rootDir(srcPath);
for (const std::string& s : rootDir.getDirectories()) {
if (s == "archive") continue;
std::cout << s << std::endl;
const std::string path = srcPath + "/" + s;
ScannedScene ss(path, s);
ss.findKeyPoints();
ss.matchKeyPoints();
break;
}
}
catch (const std::exception& e)
{
MessageBoxA(NULL, e.what(), "Exception caught", MB_ICONERROR);
exit(EXIT_FAILURE);
}
catch (...)
{
MessageBoxA(NULL, "UNKNOWN EXCEPTION", "Exception caught", MB_ICONERROR);
exit(EXIT_FAILURE);
}
std::cout << "<press key to continue>" << std::endl;
getchar();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef K3_RUNTIME_MESSAGEPROC_H
#define K3_RUNTIME_MESSAGEPROC_H
#include <Dispatch.hpp>
namespace K3
{
//-------------------
// Message processor
enum class LoopStatus { Continue, Error, Done };
// template <typename Error, typename Result>
// class MPStatus {
// public:
// LoopStatus tag;
// Error error;
// Result result;
// };
class MessageProcessor {
public:
MessageProcessor(): _status(LoopStatus::Continue) {}
virtual void initialize() {}
virtual void finalize() {}
virtual LoopStatus process(Message msg) = 0;
LoopStatus status() { return _status; };
private:
LoopStatus _status;
};
using NativeMessageProcessor = MessageProcessor;
template <class E>
class VirtualizedMessageProcessor: public MessageProcessor {
public:
VirtualizedMessageProcessor(E e): MessageProcessor(), env(e) {}
private:
E env;
};
// Message Processor used by generated code. Processing is done by dispatch messages using a
// generated table of triggers. The trigger wrapper functions perform the deserialization of the
// message payload themeselves.
class DispatchMessageProcessor : public NativeMessageProcessor {
public:
DispatchMessageProcessor(TriggerDispatch td): table(td) {}
LoopStatus process(Message msg)
{
TriggerWrapper tw;
// Look the trigger up in the dispatch table, error out if not present.
try {
tw = table.at(msg.id());
} catch (std::out_of_range e) {
return LoopStatus::Error;
}
// Call the trigger.
tw(msg.contents());
// Message was processed, signal the engine to continue.
// TODO: Propagate trigger errors to engine, K3 error semantics?
return LoopStatus::Continue;
}
private:
TriggerDispatch table;
};
}
#endif
<commit_msg>Add MPStatus type alias, for later.<commit_after>#ifndef K3_RUNTIME_MESSAGEPROC_H
#define K3_RUNTIME_MESSAGEPROC_H
#include <Dispatch.hpp>
namespace K3
{
//-------------------
// Message processor
enum class LoopStatus { Continue, Error, Done };
// template <typename Error, typename Result>
// class MPStatus {
// public:
// LoopStatus tag;
// Error error;
// Result result;
// };
class MessageProcessor {
public:
MessageProcessor(): _status(LoopStatus::Continue) {}
virtual void initialize() {}
virtual void finalize() {}
virtual LoopStatus process(Message msg) = 0;
LoopStatus status() { return _status; };
private:
LoopStatus _status;
};
using MPStatus = LoopStatus;
using NativeMessageProcessor = MessageProcessor;
template <class E>
class VirtualizedMessageProcessor: public MessageProcessor {
public:
VirtualizedMessageProcessor(E e): MessageProcessor(), env(e) {}
private:
E env;
};
// Message Processor used by generated code. Processing is done by dispatch messages using a
// generated table of triggers. The trigger wrapper functions perform the deserialization of the
// message payload themeselves.
class DispatchMessageProcessor : public NativeMessageProcessor {
public:
DispatchMessageProcessor(TriggerDispatch td): table(td) {}
LoopStatus process(Message msg)
{
TriggerWrapper tw;
// Look the trigger up in the dispatch table, error out if not present.
try {
tw = table.at(msg.id());
} catch (std::out_of_range e) {
return LoopStatus::Error;
}
// Call the trigger.
tw(msg.contents());
// Message was processed, signal the engine to continue.
// TODO: Propagate trigger errors to engine, K3 error semantics?
return LoopStatus::Continue;
}
private:
TriggerDispatch table;
};
}
#endif
<|endoftext|> |
<commit_before>// tests expectation maximization of periodic gaussians for correctness
#include <math.h>
#include <vector>
#include <iostream>
#include <EMPeriodicGaussian.h>
#include <MathFunctions.h>
#include "util.h"
using namespace std;
using namespace Terran;
void testUnimodalPeriodicGaussian() {
vector<double> data;
vector<Param> initParams(1);
double period = 2*PI;
initParams[0].p = 1;
initParams[0].u = 1.2345;
initParams[0].s = 1.1;
for(int i=0; i < 5000; i++) {
data.push_back(periodicGaussianSample(initParams[0].u,initParams[0].s,period));
}
Param p;
p.p = 1;
p.u = 1.7;
p.s = 2.1;
vector<Param> params;
params.push_back(p);
EMPeriodicGaussian em(data, params, period);
em.run(100, 0.1);
vector<Param> optimizedParams = em.getParams();
Util::matchParameters(initParams, optimizedParams, 0.05);
}
void testBimodalPeriodicGaussian() {
vector<double> data;
double period = 2*PI;
vector<Param> initParams(2);
initParams[0].p = 0.65;
initParams[0].u = -0.3;
initParams[0].s = 0.5;
for(int i=0; i<10000*initParams[0].p; i++) {
data.push_back(periodicGaussianSample(initParams[0].u,initParams[0].s,period));
}
initParams[1].p = 0.35;
initParams[1].u = 1.9;
initParams[1].s = 0.5;
for(int i=0; i<10000*initParams[1].p; i++) {
data.push_back(periodicGaussianSample(initParams[1].u,initParams[1].s,period));
}
vector<Param> params;
{
Param p;
p.p = 0.5;
p.u = -1.0;
p.s = 0.5;
params.push_back(p);
}
{
Param p;
p.p = 0.5;
p.u = 2.1;
p.s = 1.4;
params.push_back(p);
}
EMPeriodicGaussian em(data, params, period);
em.run(100, 0.1);
vector<Param> optimizedParams = em.getParams();
Util::plotPeriodicGaussian(initParams, period, "bimodal");
Util::matchParameters(initParams, optimizedParams, 0.05);
}
#include <fstream>
#include <MethodsPeriodicGaussian.h>
using namespace std;
void testOverfitPeriodicGaussian() {
vector<double> data;
double period = 2*PI;
vector<Param> initParams(2);
initParams[0].p = 0.65;
initParams[0].u = -0.3;
initParams[0].s = 0.5;
for(int i=0; i<5000*initParams[0].p; i++) {
data.push_back(periodicGaussianSample(initParams[0].u,initParams[0].s,period));
}
initParams[1].p = 0.35;
initParams[1].u = 1.9;
initParams[1].s = 0.5;
for(int i=0; i<5000*initParams[1].p; i++) {
data.push_back(periodicGaussianSample(initParams[1].u,initParams[1].s,period));
}
/*
ofstream d("data.txt");
for(int i=0; i<data.size(); i++) {
d << data[i] << endl;
}
*/
vector<Param> params;
const int numSamples = 8;
for(int i=0; i < numSamples; i++) {
Param p;
p.p = 1/(float)numSamples;
p.u = -PI + ((float)i/numSamples)*(period);
p.s = 0.3;
params.push_back(p);
}
EMPeriodicGaussian em(data, params, period);
em.run(1000,0.001);
vector<Param> optimizedParams = em.getParams();
MethodsPeriodicGaussian mpg(optimizedParams, period);
vector<double> maxima = mpg.findMaxima();
vector<double> minima = mpg.findMinima();
vector<double> truthMaxima;
truthMaxima.push_back( 1.898);
truthMaxima.push_back(-0.301);
vector<double> truthMinima;
truthMinima.push_back( 0.888);
truthMinima.push_back(-2.382);
double tol = period/100.0;
Util::matchPoints(truthMaxima, maxima, tol);
Util::matchPoints(truthMinima, minima, tol);
}
void testAdaptiveRun() {
vector<double> data;
double period = 2*PI;
vector<Param> initParams(2);
initParams[0].p = 0.65;
initParams[0].u = -0.3;
initParams[0].s = 0.5;
for(int i=0; i<5000*initParams[0].p; i++) {
data.push_back(periodicGaussianSample(initParams[0].u,initParams[0].s,period));
}
initParams[1].p = 0.35;
initParams[1].u = 1.9;
initParams[1].s = 0.5;
for(int i=0; i<5000*initParams[1].p; i++) {
data.push_back(periodicGaussianSample(initParams[1].u,initParams[1].s,period));
}
ofstream d("data.txt");
for(int i=0; i<data.size(); i++) {
d << data[i] << endl;
}
vector<Param> params;
const int numSamples = 8;
for(int i=0; i < numSamples; i++) {
Param p;
p.p = 1/(float)numSamples;
p.u = -PI + ((float)i/numSamples)*(period);
p.s = 0.3;
params.push_back(p);
}
EMPeriodicGaussian em(data, params, period);
em.adaptiveRun(1000,0.01, 0.08);
vector<Param> optimizedParams = em.getParams();
MethodsPeriodicGaussian mpg(optimizedParams, period);
vector<double> maxima = mpg.findMaxima();
vector<double> minima = mpg.findMinima();
Util::plotPeriodicGaussian(optimizedParams, period, "adaptive");
vector<double> truthMaxima;
truthMaxima.push_back( 1.898);
truthMaxima.push_back(-0.301);
vector<double> truthMinima;
truthMinima.push_back( 0.888);
truthMinima.push_back(-2.382);
/*
cout << "maxima" << endl;
for(int i=0; i < maxima.size(); i++) {
cout << maxima[i] << endl;
}
cout << "minima" << endl;
for(int i=0; i < minima.size(); i++) {
cout << minima[i] << endl;
}
*/
double tol1 = period/100.0f;
double tol2 = period/50.0f;
Util::matchPoints(truthMaxima, maxima, tol1);
Util::matchPoints(truthMinima, minima, tol2);
}
int main() {
try {
testUnimodalPeriodicGaussian();
srand(1);
testBimodalPeriodicGaussian();
srand(1);
//testOverfitPeriodicGaussian();
srand(1);
testAdaptiveRun();
} catch( const std::exception &e ) {
cout << e.what() << endl;
}
cout << "done" << endl;
}
<commit_msg>minor cleanup<commit_after>// tests expectation maximization of periodic gaussians for correctness
#include <math.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <MethodsPeriodicGaussian.h>
#include <EMPeriodicGaussian.h>
#include <MathFunctions.h>
#include "util.h"
using namespace std;
using namespace Terran;
void testUnimodalPeriodicGaussian() {
vector<double> data;
vector<Param> initParams(1);
double period = 2*PI;
initParams[0].p = 1;
initParams[0].u = 1.2345;
initParams[0].s = 1.1;
for(int i=0; i < 5000; i++) {
data.push_back(periodicGaussianSample(initParams[0].u,initParams[0].s,period));
}
Param p;
p.p = 1;
p.u = 1.7;
p.s = 2.1;
vector<Param> params;
params.push_back(p);
EMPeriodicGaussian em(data, params, period);
em.run(100, 0.1);
vector<Param> optimizedParams = em.getParams();
Util::matchParameters(initParams, optimizedParams, 0.05);
}
void testBimodalPeriodicGaussian() {
vector<double> data;
double period = 2*PI;
vector<Param> initParams(2);
initParams[0].p = 0.65;
initParams[0].u = -0.3;
initParams[0].s = 0.5;
for(int i=0; i<10000*initParams[0].p; i++) {
data.push_back(periodicGaussianSample(initParams[0].u,initParams[0].s,period));
}
initParams[1].p = 0.35;
initParams[1].u = 1.9;
initParams[1].s = 0.5;
for(int i=0; i<10000*initParams[1].p; i++) {
data.push_back(periodicGaussianSample(initParams[1].u,initParams[1].s,period));
}
vector<Param> params;
{
Param p;
p.p = 0.5;
p.u = -1.0;
p.s = 0.5;
params.push_back(p);
}
{
Param p;
p.p = 0.5;
p.u = 2.1;
p.s = 1.4;
params.push_back(p);
}
EMPeriodicGaussian em(data, params, period);
em.run(100, 0.1);
vector<Param> optimizedParams = em.getParams();
Util::plotPeriodicGaussian(initParams, period, "bimodal");
Util::matchParameters(initParams, optimizedParams, 0.05);
}
void testOverfitPeriodicGaussian() {
vector<double> data;
double period = 2*PI;
vector<Param> initParams(2);
initParams[0].p = 0.65;
initParams[0].u = -0.3;
initParams[0].s = 0.5;
for(int i=0; i<5000*initParams[0].p; i++) {
data.push_back(periodicGaussianSample(initParams[0].u,initParams[0].s,period));
}
initParams[1].p = 0.35;
initParams[1].u = 1.9;
initParams[1].s = 0.5;
for(int i=0; i<5000*initParams[1].p; i++) {
data.push_back(periodicGaussianSample(initParams[1].u,initParams[1].s,period));
}
/*
ofstream d("data.txt");
for(int i=0; i<data.size(); i++) {
d << data[i] << endl;
}
*/
vector<Param> params;
const int numSamples = 8;
for(int i=0; i < numSamples; i++) {
Param p;
p.p = 1/(float)numSamples;
p.u = -PI + ((float)i/numSamples)*(period);
p.s = 0.3;
params.push_back(p);
}
EMPeriodicGaussian em(data, params, period);
em.run(1000,0.001);
vector<Param> optimizedParams = em.getParams();
MethodsPeriodicGaussian mpg(optimizedParams, period);
vector<double> maxima = mpg.findMaxima();
vector<double> minima = mpg.findMinima();
vector<double> truthMaxima;
truthMaxima.push_back( 1.898);
truthMaxima.push_back(-0.301);
vector<double> truthMinima;
truthMinima.push_back( 0.888);
truthMinima.push_back(-2.382);
double tol = period/100.0;
Util::matchPoints(truthMaxima, maxima, tol);
Util::matchPoints(truthMinima, minima, tol);
}
void testAdaptiveRun() {
vector<double> data;
double period = 2*PI;
vector<Param> initParams(2);
initParams[0].p = 0.65;
initParams[0].u = -0.3;
initParams[0].s = 0.5;
for(int i=0; i<5000*initParams[0].p; i++) {
data.push_back(periodicGaussianSample(initParams[0].u,initParams[0].s,period));
}
initParams[1].p = 0.35;
initParams[1].u = 1.9;
initParams[1].s = 0.5;
for(int i=0; i<5000*initParams[1].p; i++) {
data.push_back(periodicGaussianSample(initParams[1].u,initParams[1].s,period));
}
ofstream d("data.txt");
for(int i=0; i<data.size(); i++) {
d << data[i] << endl;
}
vector<Param> params;
const int numSamples = 8;
for(int i=0; i < numSamples; i++) {
Param p;
p.p = 1/(float)numSamples;
p.u = -PI + ((float)i/numSamples)*(period);
p.s = 0.3;
params.push_back(p);
}
EMPeriodicGaussian em(data, params, period);
em.adaptiveRun(1000,0.01, 0.08);
vector<Param> optimizedParams = em.getParams();
MethodsPeriodicGaussian mpg(optimizedParams, period);
vector<double> maxima = mpg.findMaxima();
vector<double> minima = mpg.findMinima();
Util::plotPeriodicGaussian(optimizedParams, period, "adaptive");
vector<double> truthMaxima;
truthMaxima.push_back( 1.898);
truthMaxima.push_back(-0.301);
vector<double> truthMinima;
truthMinima.push_back( 0.888);
truthMinima.push_back(-2.382);
/*
cout << "maxima" << endl;
for(int i=0; i < maxima.size(); i++) {
cout << maxima[i] << endl;
}
cout << "minima" << endl;
for(int i=0; i < minima.size(); i++) {
cout << minima[i] << endl;
}
*/
double tol1 = period/100.0f;
double tol2 = period/50.0f;
Util::matchPoints(truthMaxima, maxima, tol1);
Util::matchPoints(truthMinima, minima, tol2);
}
int main() {
try {
testUnimodalPeriodicGaussian();
srand(1);
testBimodalPeriodicGaussian();
srand(1);
//testOverfitPeriodicGaussian();
srand(1);
testAdaptiveRun();
} catch( const std::exception &e ) {
cout << e.what() << endl;
}
cout << "done" << endl;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.