text stringlengths 54 60.6k |
|---|
<commit_before>#include <pangolin/pangolin.h>
#include <pangolin/video/video_record_repeat.h>
#include <pangolin/gl/gltexturecache.h>
struct GlFormat
{
GlFormat() {}
GlFormat(const pangolin::VideoPixelFormat& fmt)
{
switch( fmt.channels) {
case 1: glformat = GL_LUMINANCE; break;
case 3: glformat = (fmt.format == "BGR24") ? GL_BGR : GL_RGB; break;
case 4: glformat = (fmt.format == "BGRA24") ? GL_BGRA : GL_RGBA; break;
default: throw std::runtime_error("Unable to display video format");
}
switch (fmt.channel_bits[0]) {
case 8: gltype = GL_UNSIGNED_BYTE; break;
case 16: gltype = GL_UNSIGNED_SHORT; break;
case 32: gltype = GL_FLOAT; break;
default: throw std::runtime_error("Unknown channel format");
}
}
GLint glformat;
GLenum gltype;
};
void RenderToViewport(
pangolin::Image<unsigned char>& image,
const GlFormat& fmt, bool flipx=false, bool flipy=false, bool linear_sampling = true
) {
pangolin::GlTexture& tex = pangolin::TextureCache::I().GlTex(image.w, image.h, GL_RGBA, GL_RGBA, fmt.gltype);
tex.Bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, linear_sampling ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, linear_sampling ? GL_LINEAR : GL_NEAREST);
tex.Upload(image.ptr,0,0, image.w, image.h, fmt.glformat, fmt.gltype);
tex.RenderToViewport(pangolin::Viewport(0,0,image.w, image.h), flipx, flipy);
}
void VideoViewer(const std::string& input_uri, const std::string& output_uri)
{
// Open Video by URI
pangolin::VideoRecordRepeat video(input_uri, output_uri);
int total_frames = std::numeric_limits<int>::max();
if(video.Streams().size() == 0) {
pango_print_error("No video streams from device.\n");
return;
}
// Check if video supports VideoPlaybackInterface
pangolin::VideoPlaybackInterface* video_playback = video.Cast<pangolin::VideoPlaybackInterface>();
if( video_playback ) {
total_frames = video_playback->GetTotalFrames();
std::cout << "Video length: " << total_frames << " frames" << std::endl;
}
std::vector<unsigned char> buffer;
buffer.resize(video.SizeBytes()+1);
// Create OpenGL window - guess sensible dimensions
pangolin::CreateWindowAndBind( "VideoViewer",
video.Width() * video.Streams().size(), video.Height()
);
// Setup resizable views for video streams
std::vector<GlFormat> glfmt;
pangolin::DisplayBase().SetLayout(pangolin::LayoutEqual);
for(unsigned int d=0; d < video.Streams().size(); ++d) {
pangolin::View& view = pangolin::CreateDisplay().SetAspect(video.Streams()[d].Aspect());
pangolin::DisplayBase().AddDisplay(view);
glfmt.push_back(GlFormat(video.Streams()[d].PixFormat()));
}
const int FRAME_SKIP = 30;
int frame = 0;
pangolin::Var<int> max_frame("max_frame", total_frames );
pangolin::Var<bool> linear_sampling("linear_sampling", true );
pangolin::Var<float> int16_scale("int16.scale", 20.0 );
pangolin::Var<float> int16_bias("int16.bias", 0.0 );
#ifdef CALLEE_HAS_CPP11
// Show/hide streams
for(size_t v=0; v < pangolin::DisplayBase().NumChildren() && v < 9; v++) {
pangolin::RegisterKeyPressCallback('1'+v, [v](){
pangolin::DisplayBase()[v].ToggleShow();
} );
}
pangolin::RegisterKeyPressCallback('r', [&](){
if(!video.IsRecording()) {
video.Record();
pango_print_info("Started Recording.\n");
}else{
video.Stop();
pango_print_info("Finished recording.\n");
}
fflush(stdout);
});
pangolin::RegisterKeyPressCallback('p', [&](){
video.Play();
max_frame = std::numeric_limits<int>::max();
pango_print_info("Playing from file log.\n");
fflush(stdout);
});
pangolin::RegisterKeyPressCallback('s', [&](){
video.Source();
max_frame = std::numeric_limits<int>::max();
pango_print_info("Playing from source input.\n");
fflush(stdout);
});
pangolin::RegisterKeyPressCallback(' ', [&](){
max_frame = (frame < max_frame) ? frame : std::numeric_limits<int>::max();
});
pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_LEFT, [&](){
if(video_playback) {
const int frame = std::min(video_playback->GetCurrentFrameId()-FRAME_SKIP, video_playback->GetTotalFrames()-1);
video_playback->Seek(frame);
}else{
// We can't go backwards
}
});
pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_RIGHT, [&](){
if(video_playback) {
const int frame = std::max(video_playback->GetCurrentFrameId()+FRAME_SKIP, 0);
video_playback->Seek(frame);
}else{
// Pause at this frame
max_frame = frame+1;
}
});
pangolin::RegisterKeyPressCallback('l', [&](){ linear_sampling = true; });
pangolin::RegisterKeyPressCallback('n', [&](){ linear_sampling = false; });
#endif
std::vector<pangolin::Image<unsigned char> > images;
// Stream and display video
while(!pangolin::ShouldQuit())
{
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
if (frame == 0 || frame < max_frame) {
images.clear();
if (video.Grab(&buffer[0], images) ){
++frame;
}
}
for(unsigned int i=0; i<images.size(); ++i)
{
if(pangolin::DisplayBase()[i].IsShown()) {
pangolin::DisplayBase()[i].Activate();
if(glfmt[i].gltype == GL_UNSIGNED_SHORT) {
pangolin::GlSlUtilities::Scale(int16_scale, int16_bias);
RenderToViewport(images[i], glfmt[i], false, true, linear_sampling);
pangolin::GlSlUtilities::UseNone();
}else{
RenderToViewport(images[i], glfmt[i], false, true, linear_sampling);
}
}
}
pangolin::FinishFrame();
}
}
int main( int argc, char* argv[] )
{
const std::string dflt_output_uri = "pango://video.pango";
if( argc > 1 ) {
const std::string input_uri = std::string(argv[1]);
const std::string output_uri = (argc > 2) ? std::string(argv[2]) : dflt_output_uri;
try{
VideoViewer(input_uri, output_uri);
} catch (pangolin::VideoException e) {
std::cout << e.what() << std::endl;
}
}else{
const std::string input_uris[] = {
"dc1394:[fps=30,dma=10,size=640x480,iso=400]//0",
"convert:[fmt=RGB24]//v4l:///dev/video0",
"convert:[fmt=RGB24]//v4l:///dev/video1",
"openni:[img1=rgb]//",
"test:[size=160x120,n=1,fmt=RGB24]//"
""
};
std::cout << "Usage : VideoViewer [video-uri]" << std::endl << std::endl;
std::cout << "Where video-uri describes a stream or file resource, e.g." << std::endl;
std::cout << "\tfile:[realtime=1]///home/user/video/movie.pvn" << std::endl;
std::cout << "\tfile:///home/user/video/movie.avi" << std::endl;
std::cout << "\tfiles:///home/user/seqiemce/foo%03d.jpeg" << std::endl;
std::cout << "\tdc1394:[fmt=RGB24,size=640x480,fps=30,iso=400,dma=10]//0" << std::endl;
std::cout << "\tdc1394:[fmt=FORMAT7_1,size=640x480,pos=2+2,iso=400,dma=10]//0" << std::endl;
std::cout << "\tv4l:///dev/video0" << std::endl;
std::cout << "\tconvert:[fmt=RGB24]//v4l:///dev/video0" << std::endl;
std::cout << "\tmjpeg://http://127.0.0.1/?action=stream" << std::endl;
std::cout << "\topenni:[img1=rgb]//" << std::endl;
std::cout << std::endl;
// Try to open some video device
for(int i=0; !input_uris[i].empty(); ++i )
{
try{
pango_print_info("Trying: %s\n", input_uris[i].c_str());
VideoViewer(input_uris[i], dflt_output_uri);
return 0;
}catch(pangolin::VideoException) { }
}
}
return 0;
}
<commit_msg>Fix trivial warning.<commit_after>#include <pangolin/pangolin.h>
#include <pangolin/video/video_record_repeat.h>
#include <pangolin/gl/gltexturecache.h>
struct GlFormat
{
GlFormat() {}
GlFormat(const pangolin::VideoPixelFormat& fmt)
{
switch( fmt.channels) {
case 1: glformat = GL_LUMINANCE; break;
case 3: glformat = (fmt.format == "BGR24") ? GL_BGR : GL_RGB; break;
case 4: glformat = (fmt.format == "BGRA24") ? GL_BGRA : GL_RGBA; break;
default: throw std::runtime_error("Unable to display video format");
}
switch (fmt.channel_bits[0]) {
case 8: gltype = GL_UNSIGNED_BYTE; break;
case 16: gltype = GL_UNSIGNED_SHORT; break;
case 32: gltype = GL_FLOAT; break;
default: throw std::runtime_error("Unknown channel format");
}
}
GLint glformat;
GLenum gltype;
};
void RenderToViewport(
pangolin::Image<unsigned char>& image,
const GlFormat& fmt, bool flipx=false, bool flipy=false, bool linear_sampling = true
) {
pangolin::GlTexture& tex = pangolin::TextureCache::I().GlTex(image.w, image.h, GL_RGBA, GL_RGBA, fmt.gltype);
tex.Bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, linear_sampling ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, linear_sampling ? GL_LINEAR : GL_NEAREST);
tex.Upload(image.ptr,0,0, image.w, image.h, fmt.glformat, fmt.gltype);
tex.RenderToViewport(pangolin::Viewport(0,0,image.w, image.h), flipx, flipy);
}
void VideoViewer(const std::string& input_uri, const std::string& output_uri)
{
// Open Video by URI
pangolin::VideoRecordRepeat video(input_uri, output_uri);
int total_frames = std::numeric_limits<int>::max();
if(video.Streams().size() == 0) {
pango_print_error("No video streams from device.\n");
return;
}
// Check if video supports VideoPlaybackInterface
pangolin::VideoPlaybackInterface* video_playback = video.Cast<pangolin::VideoPlaybackInterface>();
if( video_playback ) {
total_frames = video_playback->GetTotalFrames();
std::cout << "Video length: " << total_frames << " frames" << std::endl;
}
std::vector<unsigned char> buffer;
buffer.resize(video.SizeBytes()+1);
// Create OpenGL window - guess sensible dimensions
pangolin::CreateWindowAndBind( "VideoViewer",
video.Width() * video.Streams().size(), video.Height()
);
// Setup resizable views for video streams
std::vector<GlFormat> glfmt;
pangolin::DisplayBase().SetLayout(pangolin::LayoutEqual);
for(unsigned int d=0; d < video.Streams().size(); ++d) {
pangolin::View& view = pangolin::CreateDisplay().SetAspect(video.Streams()[d].Aspect());
pangolin::DisplayBase().AddDisplay(view);
glfmt.push_back(GlFormat(video.Streams()[d].PixFormat()));
}
int frame = 0;
pangolin::Var<int> max_frame("max_frame", total_frames );
pangolin::Var<bool> linear_sampling("linear_sampling", true );
pangolin::Var<float> int16_scale("int16.scale", 20.0 );
pangolin::Var<float> int16_bias("int16.bias", 0.0 );
#ifdef CALLEE_HAS_CPP11
const int FRAME_SKIP = 30;
// Show/hide streams
for(size_t v=0; v < pangolin::DisplayBase().NumChildren() && v < 9; v++) {
pangolin::RegisterKeyPressCallback('1'+v, [v](){
pangolin::DisplayBase()[v].ToggleShow();
} );
}
pangolin::RegisterKeyPressCallback('r', [&](){
if(!video.IsRecording()) {
video.Record();
pango_print_info("Started Recording.\n");
}else{
video.Stop();
pango_print_info("Finished recording.\n");
}
fflush(stdout);
});
pangolin::RegisterKeyPressCallback('p', [&](){
video.Play();
max_frame = std::numeric_limits<int>::max();
pango_print_info("Playing from file log.\n");
fflush(stdout);
});
pangolin::RegisterKeyPressCallback('s', [&](){
video.Source();
max_frame = std::numeric_limits<int>::max();
pango_print_info("Playing from source input.\n");
fflush(stdout);
});
pangolin::RegisterKeyPressCallback(' ', [&](){
max_frame = (frame < max_frame) ? frame : std::numeric_limits<int>::max();
});
pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_LEFT, [&](){
if(video_playback) {
const int frame = std::min(video_playback->GetCurrentFrameId()-FRAME_SKIP, video_playback->GetTotalFrames()-1);
video_playback->Seek(frame);
}else{
// We can't go backwards
}
});
pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + pangolin::PANGO_KEY_RIGHT, [&](){
if(video_playback) {
const int frame = std::max(video_playback->GetCurrentFrameId()+FRAME_SKIP, 0);
video_playback->Seek(frame);
}else{
// Pause at this frame
max_frame = frame+1;
}
});
pangolin::RegisterKeyPressCallback('l', [&](){ linear_sampling = true; });
pangolin::RegisterKeyPressCallback('n', [&](){ linear_sampling = false; });
#endif
std::vector<pangolin::Image<unsigned char> > images;
// Stream and display video
while(!pangolin::ShouldQuit())
{
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
if (frame == 0 || frame < max_frame) {
images.clear();
if (video.Grab(&buffer[0], images) ){
++frame;
}
}
for(unsigned int i=0; i<images.size(); ++i)
{
if(pangolin::DisplayBase()[i].IsShown()) {
pangolin::DisplayBase()[i].Activate();
if(glfmt[i].gltype == GL_UNSIGNED_SHORT) {
pangolin::GlSlUtilities::Scale(int16_scale, int16_bias);
RenderToViewport(images[i], glfmt[i], false, true, linear_sampling);
pangolin::GlSlUtilities::UseNone();
}else{
RenderToViewport(images[i], glfmt[i], false, true, linear_sampling);
}
}
}
pangolin::FinishFrame();
}
}
int main( int argc, char* argv[] )
{
const std::string dflt_output_uri = "pango://video.pango";
if( argc > 1 ) {
const std::string input_uri = std::string(argv[1]);
const std::string output_uri = (argc > 2) ? std::string(argv[2]) : dflt_output_uri;
try{
VideoViewer(input_uri, output_uri);
} catch (pangolin::VideoException e) {
std::cout << e.what() << std::endl;
}
}else{
const std::string input_uris[] = {
"dc1394:[fps=30,dma=10,size=640x480,iso=400]//0",
"convert:[fmt=RGB24]//v4l:///dev/video0",
"convert:[fmt=RGB24]//v4l:///dev/video1",
"openni:[img1=rgb]//",
"test:[size=160x120,n=1,fmt=RGB24]//"
""
};
std::cout << "Usage : VideoViewer [video-uri]" << std::endl << std::endl;
std::cout << "Where video-uri describes a stream or file resource, e.g." << std::endl;
std::cout << "\tfile:[realtime=1]///home/user/video/movie.pvn" << std::endl;
std::cout << "\tfile:///home/user/video/movie.avi" << std::endl;
std::cout << "\tfiles:///home/user/seqiemce/foo%03d.jpeg" << std::endl;
std::cout << "\tdc1394:[fmt=RGB24,size=640x480,fps=30,iso=400,dma=10]//0" << std::endl;
std::cout << "\tdc1394:[fmt=FORMAT7_1,size=640x480,pos=2+2,iso=400,dma=10]//0" << std::endl;
std::cout << "\tv4l:///dev/video0" << std::endl;
std::cout << "\tconvert:[fmt=RGB24]//v4l:///dev/video0" << std::endl;
std::cout << "\tmjpeg://http://127.0.0.1/?action=stream" << std::endl;
std::cout << "\topenni:[img1=rgb]//" << std::endl;
std::cout << std::endl;
// Try to open some video device
for(int i=0; !input_uris[i].empty(); ++i )
{
try{
pango_print_info("Trying: %s\n", input_uris[i].c_str());
VideoViewer(input_uris[i], dflt_output_uri);
return 0;
}catch(pangolin::VideoException) { }
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2014 BVLC and contributors.
// This program converts a set of images to a leveldb by storing them as Datum
// proto buffers.
// Usage:
// convert_imageset [-g] ROOTFOLDER/ LISTFILE DB_NAME RANDOM_SHUFFLE[0 or 1]
// [resize_height] [resize_width]
// where ROOTFOLDER is the root folder that holds all the images, and LISTFILE
// should be a list of files as well as their labels, in the format as
// subfolder1/file1.JPEG 7
// ....
// if RANDOM_SHUFFLE is 1, a random shuffle will be carried out before we
// process the file lines.
// Optional flag -g indicates the images should be read as
// single-channel grayscale. If omitted, grayscale images will be
// converted to color.
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <lmdb.h>
#include <sys/stat.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <utility>
#include <vector>
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
#include "caffe/util/rng.hpp"
using namespace caffe; // NOLINT(build/namespaces)
using std::pair;
using std::string;
DEFINE_bool(gray, false,
"When this option is on, treat images as grayscale ones");
DEFINE_bool(shuffle, false,
"Randomly shuffle the order of images and their labels");
DEFINE_string(backend, "leveldb", "The backend for storing the result");
DEFINE_int32(resize_width, 0, "Width images are resized to");
DEFINE_int32(resize_height, 0, "Height images are resized to");
int main(int argc, char** argv) {
::google::InitGoogleLogging(argv[0]);
#ifndef GFLAGS_GFLAGS_H_
namespace gflags = google;
#endif
gflags::SetUsageMessage("Convert a set of images to the leveldb/lmdb\n"
"format used as input for Caffe.\n"
"Usage:\n"
" convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n"
"The ImageNet dataset for the training demo is at\n"
" http://www.image-net.org/download-images\n");
gflags::ParseCommandLineFlags(&argc, &argv, true);
if (argc != 4) {
fputs("Use --help to see detailed description of usage\n", stdout);
return 1;
}
bool is_color = !FLAGS_gray;
std::ifstream infile(argv[2]);
std::vector<std::pair<string, int> > lines;
string filename;
int label;
while (infile >> filename >> label) {
lines.push_back(std::make_pair(filename, label));
}
if (FLAGS_shuffle) {
// randomly shuffle data
LOG(INFO) << "Shuffling data";
shuffle(lines.begin(), lines.end());
}
LOG(INFO) << "A total of " << lines.size() << " images.";
const string& db_backend = FLAGS_backend;
const char* db_path = argv[3];
int resize_height = std::max<int>(0, FLAGS_resize_height);
int resize_width = std::max<int>(0, FLAGS_resize_width);
// Open new db
// lmdb
MDB_env *mdb_env;
MDB_dbi mdb_dbi;
MDB_val mdb_key, mdb_data;
MDB_txn *mdb_txn;
// leveldb
leveldb::DB* db;
leveldb::Options options;
options.error_if_exists = true;
options.create_if_missing = true;
options.write_buffer_size = 268435456;
leveldb::WriteBatch* batch = NULL;
// Open db
if (db_backend == "leveldb") { // leveldb
LOG(INFO) << "Opening leveldb " << db_path;
leveldb::Status status = leveldb::DB::Open(
options, db_path, &db);
CHECK(status.ok()) << "Failed to open leveldb " << db_path;
batch = new leveldb::WriteBatch();
} else if (db_backend == "lmdb") { // lmdb
LOG(INFO) << "Opening lmdb " << db_path;
CHECK_EQ(mkdir(db_path, 0744), 0)
<< "mkdir " << db_path << "failed";
CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << "mdb_env_create failed";
CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS) // 1TB
<< "mdb_env_set_mapsize failed";
CHECK_EQ(mdb_env_open(mdb_env, db_path, 0, 0664), MDB_SUCCESS)
<< "mdb_env_open failed";
CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)
<< "mdb_txn_begin failed";
CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)
<< "mdb_open failed";
} else {
LOG(FATAL) << "Unknown db backend " << db_backend;
}
// Storing to db
string root_folder(argv[1]);
Datum datum;
int count = 0;
const int kMaxKeyLength = 256;
char key_cstr[kMaxKeyLength];
int data_size;
bool data_size_initialized = false;
for (int line_id = 0; line_id < lines.size(); ++line_id) {
if (!ReadImageToDatum(root_folder + lines[line_id].first,
lines[line_id].second, resize_height, resize_width, is_color, &datum)) {
continue;
}
if (!data_size_initialized) {
data_size = datum.channels() * datum.height() * datum.width();
data_size_initialized = true;
} else {
const string& data = datum.data();
CHECK_EQ(data.size(), data_size) << "Incorrect data field size "
<< data.size();
}
// sequential
snprintf(key_cstr, kMaxKeyLength, "%08d_%s", line_id,
lines[line_id].first.c_str());
string value;
datum.SerializeToString(&value);
string keystr(key_cstr);
// Put in db
if (db_backend == "leveldb") { // leveldb
batch->Put(keystr, value);
} else if (db_backend == "lmdb") { // lmdb
mdb_data.mv_size = value.size();
mdb_data.mv_data = reinterpret_cast<void*>(&value[0]);
mdb_key.mv_size = keystr.size();
mdb_key.mv_data = reinterpret_cast<void*>(&keystr[0]);
CHECK_EQ(mdb_put(mdb_txn, mdb_dbi, &mdb_key, &mdb_data, 0), MDB_SUCCESS)
<< "mdb_put failed";
} else {
LOG(FATAL) << "Unknown db backend " << db_backend;
}
if (++count % 1000 == 0) {
// Commit txn
if (db_backend == "leveldb") { // leveldb
db->Write(leveldb::WriteOptions(), batch);
delete batch;
batch = new leveldb::WriteBatch();
} else if (db_backend == "lmdb") { // lmdb
CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS)
<< "mdb_txn_commit failed";
CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)
<< "mdb_txn_begin failed";
} else {
LOG(FATAL) << "Unknown db backend " << db_backend;
}
LOG(ERROR) << "Processed " << count << " files.";
}
}
// write the last batch
if (count % 1000 != 0) {
if (db_backend == "leveldb") { // leveldb
db->Write(leveldb::WriteOptions(), batch);
delete batch;
delete db;
} else if (db_backend == "lmdb") { // lmdb
CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS) << "mdb_txn_commit failed";
mdb_close(mdb_env, mdb_dbi);
mdb_env_close(mdb_env);
} else {
LOG(FATAL) << "Unknown db backend " << db_backend;
}
LOG(ERROR) << "Processed " << count << " files.";
}
return 0;
}
<commit_msg>Use gflags to show help when the arguments not correct<commit_after>// Copyright 2014 BVLC and contributors.
// This program converts a set of images to a leveldb by storing them as Datum
// proto buffers.
// Usage:
// convert_imageset [-g] ROOTFOLDER/ LISTFILE DB_NAME RANDOM_SHUFFLE[0 or 1]
// [resize_height] [resize_width]
// where ROOTFOLDER is the root folder that holds all the images, and LISTFILE
// should be a list of files as well as their labels, in the format as
// subfolder1/file1.JPEG 7
// ....
// if RANDOM_SHUFFLE is 1, a random shuffle will be carried out before we
// process the file lines.
// Optional flag -g indicates the images should be read as
// single-channel grayscale. If omitted, grayscale images will be
// converted to color.
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
#include <lmdb.h>
#include <sys/stat.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <utility>
#include <vector>
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
#include "caffe/util/rng.hpp"
using namespace caffe; // NOLINT(build/namespaces)
using std::pair;
using std::string;
DEFINE_bool(gray, false,
"When this option is on, treat images as grayscale ones");
DEFINE_bool(shuffle, false,
"Randomly shuffle the order of images and their labels");
DEFINE_string(backend, "leveldb", "The backend for storing the result");
DEFINE_int32(resize_width, 0, "Width images are resized to");
DEFINE_int32(resize_height, 0, "Height images are resized to");
int main(int argc, char** argv) {
::google::InitGoogleLogging(argv[0]);
#ifndef GFLAGS_GFLAGS_H_
namespace gflags = google;
#endif
gflags::SetUsageMessage("Convert a set of images to the leveldb/lmdb\n"
"format used as input for Caffe.\n"
"Usage:\n"
" convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n"
"The ImageNet dataset for the training demo is at\n"
" http://www.image-net.org/download-images\n");
gflags::ParseCommandLineFlags(&argc, &argv, true);
if (argc != 4) {
gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset");
return 1;
}
bool is_color = !FLAGS_gray;
std::ifstream infile(argv[2]);
std::vector<std::pair<string, int> > lines;
string filename;
int label;
while (infile >> filename >> label) {
lines.push_back(std::make_pair(filename, label));
}
if (FLAGS_shuffle) {
// randomly shuffle data
LOG(INFO) << "Shuffling data";
shuffle(lines.begin(), lines.end());
}
LOG(INFO) << "A total of " << lines.size() << " images.";
const string& db_backend = FLAGS_backend;
const char* db_path = argv[3];
int resize_height = std::max<int>(0, FLAGS_resize_height);
int resize_width = std::max<int>(0, FLAGS_resize_width);
// Open new db
// lmdb
MDB_env *mdb_env;
MDB_dbi mdb_dbi;
MDB_val mdb_key, mdb_data;
MDB_txn *mdb_txn;
// leveldb
leveldb::DB* db;
leveldb::Options options;
options.error_if_exists = true;
options.create_if_missing = true;
options.write_buffer_size = 268435456;
leveldb::WriteBatch* batch = NULL;
// Open db
if (db_backend == "leveldb") { // leveldb
LOG(INFO) << "Opening leveldb " << db_path;
leveldb::Status status = leveldb::DB::Open(
options, db_path, &db);
CHECK(status.ok()) << "Failed to open leveldb " << db_path;
batch = new leveldb::WriteBatch();
} else if (db_backend == "lmdb") { // lmdb
LOG(INFO) << "Opening lmdb " << db_path;
CHECK_EQ(mkdir(db_path, 0744), 0)
<< "mkdir " << db_path << "failed";
CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << "mdb_env_create failed";
CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS) // 1TB
<< "mdb_env_set_mapsize failed";
CHECK_EQ(mdb_env_open(mdb_env, db_path, 0, 0664), MDB_SUCCESS)
<< "mdb_env_open failed";
CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)
<< "mdb_txn_begin failed";
CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS)
<< "mdb_open failed";
} else {
LOG(FATAL) << "Unknown db backend " << db_backend;
}
// Storing to db
string root_folder(argv[1]);
Datum datum;
int count = 0;
const int kMaxKeyLength = 256;
char key_cstr[kMaxKeyLength];
int data_size;
bool data_size_initialized = false;
for (int line_id = 0; line_id < lines.size(); ++line_id) {
if (!ReadImageToDatum(root_folder + lines[line_id].first,
lines[line_id].second, resize_height, resize_width, is_color, &datum)) {
continue;
}
if (!data_size_initialized) {
data_size = datum.channels() * datum.height() * datum.width();
data_size_initialized = true;
} else {
const string& data = datum.data();
CHECK_EQ(data.size(), data_size) << "Incorrect data field size "
<< data.size();
}
// sequential
snprintf(key_cstr, kMaxKeyLength, "%08d_%s", line_id,
lines[line_id].first.c_str());
string value;
datum.SerializeToString(&value);
string keystr(key_cstr);
// Put in db
if (db_backend == "leveldb") { // leveldb
batch->Put(keystr, value);
} else if (db_backend == "lmdb") { // lmdb
mdb_data.mv_size = value.size();
mdb_data.mv_data = reinterpret_cast<void*>(&value[0]);
mdb_key.mv_size = keystr.size();
mdb_key.mv_data = reinterpret_cast<void*>(&keystr[0]);
CHECK_EQ(mdb_put(mdb_txn, mdb_dbi, &mdb_key, &mdb_data, 0), MDB_SUCCESS)
<< "mdb_put failed";
} else {
LOG(FATAL) << "Unknown db backend " << db_backend;
}
if (++count % 1000 == 0) {
// Commit txn
if (db_backend == "leveldb") { // leveldb
db->Write(leveldb::WriteOptions(), batch);
delete batch;
batch = new leveldb::WriteBatch();
} else if (db_backend == "lmdb") { // lmdb
CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS)
<< "mdb_txn_commit failed";
CHECK_EQ(mdb_txn_begin(mdb_env, NULL, 0, &mdb_txn), MDB_SUCCESS)
<< "mdb_txn_begin failed";
} else {
LOG(FATAL) << "Unknown db backend " << db_backend;
}
LOG(ERROR) << "Processed " << count << " files.";
}
}
// write the last batch
if (count % 1000 != 0) {
if (db_backend == "leveldb") { // leveldb
db->Write(leveldb::WriteOptions(), batch);
delete batch;
delete db;
} else if (db_backend == "lmdb") { // lmdb
CHECK_EQ(mdb_txn_commit(mdb_txn), MDB_SUCCESS) << "mdb_txn_commit failed";
mdb_close(mdb_env, mdb_dbi);
mdb_env_close(mdb_env);
} else {
LOG(FATAL) << "Unknown db backend " << db_backend;
}
LOG(ERROR) << "Processed " << count << " files.";
}
return 0;
}
<|endoftext|> |
<commit_before>// -*- c++ -*-
/*!
* This file is part of CameraPlus.
*
* Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>
*
* 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 <QCoreApplication>
#include <qtcamera.h>
#include <qtcamdevice.h>
#include <qtcamconfig.h>
#include <qtcamnullviewfinder.h>
#include <QDebug>
void dump(const QList<QSize>& res, const char *name) {
qDebug() << name << "resolutions";
foreach (const QSize& r, res) {
qDebug() << r.width() << "x"<< r.height();
}
}
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QtCamera c;
for (int x = 0; x < 2; x++) {
QtCamDevice *dev = c.device(x, &c);
dev->setViewfinder(new QtCamNullViewfinder(dev));
if (!dev->start()) {
qFatal("Failed to start camera");
}
dump(dev->queryImageResolutions(), "image");
dump(dev->queryVideoResolutions(), "video");
dump(dev->queryViewfinderResolutions(), "viewfinder");
dev->stop(false);
delete dev;
}
}
<commit_msg>dump:resolutions: print common names and aspect ratios too<commit_after>// -*- c++ -*-
/*!
* This file is part of CameraPlus.
*
* Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>
*
* 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 <QCoreApplication>
#include <qtcamera.h>
#include <qtcamdevice.h>
#include <qtcamconfig.h>
#include <qtcamnullviewfinder.h>
#include <qtcamutils.h>
#include <QDebug>
void dump(const QList<QSize>& res, const char *name) {
qDebug() << name << "resolutions";
foreach (const QSize& r, res) {
qDebug() << r.width() << "x"<< r.height() <<
QtCamUtils::aspectRatioForResolution(r) <<
QtCamUtils::commonNameForResolution(r);
}
}
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QtCamera c;
for (int x = 0; x < 2; x++) {
QtCamDevice *dev = c.device(x, &c);
dev->setViewfinder(new QtCamNullViewfinder(dev));
if (!dev->start()) {
qFatal("Failed to start camera");
}
dump(dev->queryImageResolutions(), "image");
dump(dev->queryVideoResolutions(), "video");
dump(dev->queryViewfinderResolutions(), "viewfinder");
dev->stop(false);
delete dev;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <cmath>
#include <iostream>
#include "core/constants.hpp"
#include "core/fp_utils.hpp"
#include "core/global_config.hpp"
namespace mocc {
inline real_t RadToDeg( real_t rad ) {
return 180*(rad*RPI);
}
struct Angle {
/// x-component of the angle
real_t ox;
/// y-component of the angle
real_t oy;
/// z-component of the angle
real_t oz;
/// azimuthal angle
real_t alpha;
/// polar cosine
real_t theta;
/// quadrature weight
real_t weight;
/// Reciprocal of the sine of the polar angle. This is useful for
/// computing true ray segment length from 2D projected length.
real_t rsintheta;
/**
* Default constructor makes a nonsense angle. Watch out.
*/
Angle() {}
/**
* Construct using alpha/theta
*/
Angle( real_t alpha, real_t theta, real_t weight ):
alpha(alpha),
theta(theta),
weight(weight)
{
ox = sin(theta)*cos(alpha);
oy = sin(theta)*sin(alpha);
oz = cos(theta);
}
/**
* Construct using direction cosines
*/
Angle( real_t ox, real_t oy, real_t oz, real_t weight):
ox(ox), oy(oy), oz(oz), weight(weight)
{
theta = acos(oz);
alpha = acos(ox/sin(theta));
rsintheta = 1.0/sin(theta);
}
// Provide stream insertion support
friend std::ostream& operator<<(std::ostream& os, const Angle &ang );
/**
* \brief Return the upwind surface of the angle, given a \ref Normal
* direction.
*/
Surface upwind_surface( Normal norm ) const {
switch( norm ) {
case Normal::X_NORM:
return (ox > 0.0) ? Surface::WEST : Surface::EAST;
case Normal::Y_NORM:
return (oy > 0.0) ? Surface::SOUTH : Surface::NORTH;
case Normal::Z_NORM:
return (oz > 0.0) ? Surface::BOTTOM : Surface::TOP;
default:
return Surface::INVALID;
}
return Surface::INVALID;
}
/**
* \brief Provide operator==
*
* Equivalence between two \ref Angle objects means that all angle
* components and weight are very close, within FP tolerance
*/
bool operator==( const Angle &other ) const {
return !(*this != other);
}
/**
* \brief Provide operator!=
*
* \copydetails operator!=
*
* We only fully implement \c operator!=, since a bunch of OR'd
* not-equivalent conditions can short-circuit, wheras a bunch of AND'd
* equivalent conditions must all be evaluated.
*/
bool operator!=( const Angle &other ) const {
return
(
!fp_equiv_ulp( ox, other.ox ) ||
!fp_equiv_ulp( oy, other.oy ) ||
!fp_equiv_ulp( oz, other.oz ) ||
!fp_equiv_ulp( alpha, other.alpha ) ||
!fp_equiv_ulp( theta, other.theta ) ||
!fp_equiv_ulp( weight, other.weight ) ||
!fp_equiv_ulp( rsintheta, other.rsintheta )
);
}
};
Angle ToOctant( Angle in, int octant );
Angle ModifyAlpha ( Angle in, real_t new_alpha );
}
<commit_msg>Fix docs<commit_after>#pragma once
#include <cmath>
#include <iostream>
#include "core/constants.hpp"
#include "core/fp_utils.hpp"
#include "core/global_config.hpp"
namespace mocc {
inline real_t RadToDeg( real_t rad ) {
return 180*(rad*RPI);
}
struct Angle {
/// x-component of the angle
real_t ox;
/// y-component of the angle
real_t oy;
/// z-component of the angle
real_t oz;
/// azimuthal angle
real_t alpha;
/// polar cosine
real_t theta;
/// quadrature weight
real_t weight;
/// Reciprocal of the sine of the polar angle. This is useful for
/// computing true ray segment length from 2D projected length.
real_t rsintheta;
/**
* Default constructor makes a nonsense angle. Watch out.
*/
Angle() {}
/**
* Construct using alpha/theta
*/
Angle( real_t alpha, real_t theta, real_t weight ):
alpha(alpha),
theta(theta),
weight(weight)
{
ox = sin(theta)*cos(alpha);
oy = sin(theta)*sin(alpha);
oz = cos(theta);
}
/**
* Construct using direction cosines
*/
Angle( real_t ox, real_t oy, real_t oz, real_t weight):
ox(ox), oy(oy), oz(oz), weight(weight)
{
theta = acos(oz);
alpha = acos(ox/sin(theta));
rsintheta = 1.0/sin(theta);
}
// Provide stream insertion support
friend std::ostream& operator<<(std::ostream& os, const Angle &ang );
/**
* \brief Return the upwind surface of the angle, given a \ref Normal
* direction.
*/
Surface upwind_surface( Normal norm ) const {
switch( norm ) {
case Normal::X_NORM:
return (ox > 0.0) ? Surface::WEST : Surface::EAST;
case Normal::Y_NORM:
return (oy > 0.0) ? Surface::SOUTH : Surface::NORTH;
case Normal::Z_NORM:
return (oz > 0.0) ? Surface::BOTTOM : Surface::TOP;
default:
return Surface::INVALID;
}
return Surface::INVALID;
}
/**
* \brief Provide operator==
*
* Equivalence between two \ref Angle objects means that all angle
* components and weight are very close, within FP tolerance
*/
bool operator==( const Angle &other ) const {
return !(*this != other);
}
/**
* \brief Provide operator!=
*
* \copydetails operator==
*
* We only fully implement \c operator!=, since a bunch of OR'd
* not-equivalent conditions can short-circuit, wheras a bunch of AND'd
* equivalent conditions must all be evaluated.
*/
bool operator!=( const Angle &other ) const {
return
(
!fp_equiv_ulp( ox, other.ox ) ||
!fp_equiv_ulp( oy, other.oy ) ||
!fp_equiv_ulp( oz, other.oz ) ||
!fp_equiv_ulp( alpha, other.alpha ) ||
!fp_equiv_ulp( theta, other.theta ) ||
!fp_equiv_ulp( weight, other.weight ) ||
!fp_equiv_ulp( rsintheta, other.rsintheta )
);
}
};
Angle ToOctant( Angle in, int octant );
Angle ModifyAlpha ( Angle in, real_t new_alpha );
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include "etl/print.hpp"
//#include "dll/conv_rbm.hpp"
//#include "dll/conv_layer.hpp"
#include "dll/conv_rbm_mp.hpp"
#include "dll/conv_mp_layer.hpp"
#include "dll/vector.hpp"
#include "dll/generic_trainer.hpp"
#include "mnist/mnist_reader.hpp"
#include "utils.hpp"
int main(int argc, char* argv[]){
auto reconstruction = false;
auto load = false;
auto train = true;
for(int i = 1; i < argc; ++i){
std::string command(argv[i]);
if(command == "sample"){
reconstruction = true;
}
if(command == "init"){
train = false;
}
if(command == "load"){
load = true;
train = false;
}
}
dll::conv_rbm_mp<dll::conv_mp_layer<
28, 12, 8, 2,
dll::batch_size<25>,
//dll::weight_decay<dll::decay_type::L1>,
dll::visible<dll::unit_type::BINARY>
>> rbm;
auto dataset = mnist::read_dataset<std::vector, vector, double>();
if(dataset.training_images.empty() || dataset.training_labels.empty()){
std::cout << "Impossible to read dataset" << std::endl;
return 1;
}
binarize_each(dataset.training_images);
binarize_each(dataset.test_images);
//normalize(dataset.training_images);
//normalize(dataset.test_images);
if(load){
std::ifstream is("crbm-1.dat", std::ofstream::binary);
rbm.load(is);
} else if(train) {
rbm.learning_rate = 0.1;
rbm.train(dataset.training_images, 10);
std::ofstream os("crbm-1.dat", std::ofstream::binary);
rbm.store(os);
}
if(reconstruction){
//std::cout << "W:" << sum(rbm.w) << std::endl;
std::cout << "b:" << rbm.b << std::endl;
std::cout << "c:" << rbm.c << std::endl;
std::cout << "Start reconstructions" << std::endl;
for(size_t t = 0; t < 10; ++t){
auto& image = dataset.training_images[666 + t];
//std::cout << "Source image" << std::endl;
//for(size_t i = 0; i < 28; ++i){
//for(size_t j = 0; j < 28; ++j){
//std::cout << static_cast<size_t>(image[i * 28 + j]) << " ";
//}
//std::cout << std::endl;
//}
//std::cout << "before:" << sum(rbm.v2_a) << std::endl;
//std::cout << "before:" << sum(sum(rbm.h2_a)) << std::endl;
rbm.reconstruct(image);
//std::cout << "after:" << sum(rbm.v2_a) << std::endl;
//std::cout << "after:" << sum(sum(rbm.h2_a)) << std::endl;
//std::cout << "h1_s after:" << sum(rbm.h1_s) << std::endl;
//std::cout << "h2_s after:" << sum(rbm.h2_s) << std::endl;
//std::cout << "Reconstructed image" << std::endl;
rbm.display_visible_unit_samples();
}
}
return 0;
}
<commit_msg>Goes back to crbm without pmp<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include "etl/print.hpp"
#include "dll/conv_rbm.hpp"
#include "dll/conv_layer.hpp"
//#include "dll/conv_rbm_mp.hpp"
//#include "dll/conv_mp_layer.hpp"
#include "dll/vector.hpp"
#include "dll/generic_trainer.hpp"
#include "mnist/mnist_reader.hpp"
#include "utils.hpp"
int main(int argc, char* argv[]){
auto reconstruction = false;
auto load = false;
auto train = true;
for(int i = 1; i < argc; ++i){
std::string command(argv[i]);
if(command == "sample"){
reconstruction = true;
}
if(command == "init"){
train = false;
}
if(command == "load"){
load = true;
train = false;
}
}
dll::conv_rbm<dll::conv_layer<
28, 12, 8,
dll::batch_size<25>,
//dll::weight_decay<dll::decay_type::L1>,
dll::visible<dll::unit_type::BINARY>
>> rbm;
auto dataset = mnist::read_dataset<std::vector, vector, double>();
if(dataset.training_images.empty() || dataset.training_labels.empty()){
std::cout << "Impossible to read dataset" << std::endl;
return 1;
}
binarize_each(dataset.training_images);
binarize_each(dataset.test_images);
//normalize(dataset.training_images);
//normalize(dataset.test_images);
if(load){
std::ifstream is("crbm-1.dat", std::ofstream::binary);
rbm.load(is);
} else if(train) {
rbm.learning_rate = 0.1;
rbm.train(dataset.training_images, 10);
std::ofstream os("crbm-1.dat", std::ofstream::binary);
rbm.store(os);
}
if(reconstruction){
//std::cout << "W:" << sum(rbm.w) << std::endl;
std::cout << "b:" << rbm.b << std::endl;
std::cout << "c:" << rbm.c << std::endl;
std::cout << "Start reconstructions" << std::endl;
for(size_t t = 0; t < 10; ++t){
auto& image = dataset.training_images[666 + t];
//std::cout << "Source image" << std::endl;
//for(size_t i = 0; i < 28; ++i){
//for(size_t j = 0; j < 28; ++j){
//std::cout << static_cast<size_t>(image[i * 28 + j]) << " ";
//}
//std::cout << std::endl;
//}
//std::cout << "before:" << sum(rbm.v2_a) << std::endl;
//std::cout << "before:" << sum(sum(rbm.h2_a)) << std::endl;
rbm.reconstruct(image);
//std::cout << "after:" << sum(rbm.v2_a) << std::endl;
//std::cout << "after:" << sum(sum(rbm.h2_a)) << std::endl;
//std::cout << "h1_s after:" << sum(rbm.h1_s) << std::endl;
//std::cout << "h2_s after:" << sum(rbm.h2_s) << std::endl;
//std::cout << "Reconstructed image" << std::endl;
rbm.display_visible_unit_samples();
}
}
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <fstream>
#include "filesystem.hpp"
namespace std
{
template<> struct hash<dafs::BlockFormat>
{
std::size_t operator()(dafs::BlockFormat const& s) const
{
std::size_t h = 0;
for (int i=0; i<dafs::BLOCK_SIZE_IN_BYTES; i++)
{
h ^= std::hash<char>{}(s.contents[i]);
}
return h;
}
};
template<> struct hash<dafs::BlockInfo>
{
std::size_t operator()(dafs::BlockInfo const& b) const
{
std::fstream f(b.path,
std::ios::out | std::ios::in | std::ios::binary);
dafs::BlockFormat rawblock;
f.read(rawblock.contents, dafs::BLOCK_SIZE_IN_BYTES);
return std::hash<dafs::BlockFormat>{}(rawblock);
}
};
}
<commit_msg>Fix block hash input<commit_after>#pragma once
#include <fstream>
#include <sys/stat.h>
#include "filesystem.hpp"
namespace std
{
template<> struct hash<dafs::BlockFormat>
{
std::size_t operator()(dafs::BlockFormat const& s, const int size=dafs::BLOCK_SIZE_IN_BYTES) const
{
std::size_t h = 0;
for (int i=0; i<size; i++)
{
h ^= std::hash<char>{}(s.contents[i]);
}
return h;
}
};
template<> struct hash<dafs::BlockInfo>
{
std::size_t operator()(dafs::BlockInfo const& b) const
{
std::fstream f(b.path,
std::ios::in | std::ios::binary);
dafs::BlockFormat rawblock;
size_t size = 0;
struct stat st;
if (stat(b.path.c_str(), &st) == 0)
{
size = st.st_size;
}
f.read(rawblock.contents, size);
return std::hash<dafs::BlockFormat>{}(rawblock, size);
}
};
}
<|endoftext|> |
<commit_before>
#include <sstream>
#include <algorithm>
#include "data/vocab.h"
#include "common/utils.h"
#include "common/file_stream.h"
#include "3rd_party/exception.h"
#include "3rd_party/yaml-cpp/yaml.h"
#include "common/logging.h"
Vocab::Vocab() {
}
size_t Vocab::operator[](const std::string& word) const {
auto it = str2id_.find(word);
if(it != str2id_.end())
return it->second;
else
return UNK_ID;
}
Words Vocab::operator()(const std::vector<std::string>& lineTokens, bool addEOS) const {
Words words(lineTokens.size());
std::transform(lineTokens.begin(), lineTokens.end(), words.begin(),
[&](const std::string& w) { return (*this)[w]; });
if(addEOS)
words.push_back(EOS_ID);
return words;
}
Words Vocab::operator()(const std::string& line, bool addEOS) const {
std::vector<std::string> lineTokens;
Split(line, lineTokens, " ");
return (*this)(lineTokens, addEOS);
}
std::vector<std::string> Vocab::operator()(const Words& sentence, bool ignoreEOS) const {
std::vector<std::string> decoded;
for(size_t i = 0; i < sentence.size(); ++i) {
if(sentence[i] != EOS_ID || !ignoreEOS) {
decoded.push_back((*this)[sentence[i]]);
}
}
return decoded;
}
const std::string& Vocab::operator[](size_t id) const {
UTIL_THROW_IF2(id >= id2str_.size(), "Unknown word id: " << id);
return id2str_[id];
}
size_t Vocab::size() const {
return id2str_.size();
}
void Vocab::loadOrCreate(const std::string& trainPath, int max)
{
if(boost::filesystem::exists(trainPath + ".json")) {
load(trainPath + ".json", max);
return;
}
if(boost::filesystem::exists(trainPath + ".yml")) {
load(trainPath + ".yml", max);
return;
}
create(trainPath + ".yml", max, trainPath);
load(trainPath + ".yml", max);
}
void Vocab::load(const std::string& vocabPath, int max)
{
LOG(data) << "Loading vocabulary from " << vocabPath << " (max: " << max << ")";
YAML::Node vocab = YAML::Load(InputFileStream(vocabPath));
for(auto&& pair : vocab) {
auto str = pair.first.as<std::string>();
auto id = pair.second.as<Word>();
if (id < (Word)max) {
str2id_[str] = id;
if(id >= id2str_.size())
id2str_.resize(id + 1);
id2str_[id] = str;
}
}
UTIL_THROW_IF2(id2str_.empty(), "Empty vocabulary " << vocabPath);
id2str_[EOS_ID] = EOS_STR;
id2str_[UNK_ID] = UNK_STR;
}
class Vocab::VocabFreqOrderer
{
public:
bool operator()(const Vocab::Str2Id::value_type* a, const Vocab::Str2Id::value_type* b) const {
return a->second < b->second;
}
};
void Vocab::create(const std::string& vocabPath, int max, const std::string& trainPath)
{
LOG(data) << "Creating vocabulary " << vocabPath
<< " from " << trainPath << " (max: " << max << ")";
UTIL_THROW_IF2(boost::filesystem::exists(vocabPath),
"Vocab file " << vocabPath << " exist. Not overwriting");
InputFileStream trainStrm(trainPath);
Str2Id vocab;
std::string line;
while (getline((std::istream&)trainStrm, line)) {
std::vector<std::string> toks;
Split(line, toks);
for (const std::string &tok: toks) {
Str2Id::iterator iter = vocab.find(tok);
if (iter == vocab.end())
vocab[tok] = 1;
else
iter->second++;
}
}
// put into vector & sort
std::vector<const Str2Id::value_type*> vocabVec;
vocabVec.reserve(max);
for (const Str2Id::value_type &p: vocab)
vocabVec.push_back(&p);
std::sort(vocabVec.rbegin(), vocabVec.rend(), VocabFreqOrderer());
YAML::Node vocabYaml;
vocabYaml[EOS_STR] = EOS_ID;
vocabYaml[UNK_STR] = UNK_ID;
for(size_t i = 2; i < vocabVec.size(); ++i) {
const Str2Id::value_type *p = vocabVec[i];
vocabYaml[p->first] = i;
}
OutputFileStream vocabStrm(vocabPath);
(std::ostream&)vocabStrm << vocabYaml;
}
<commit_msg>fixed bad indexing in created vocab<commit_after>
#include <sstream>
#include <algorithm>
#include "data/vocab.h"
#include "common/utils.h"
#include "common/file_stream.h"
#include "3rd_party/exception.h"
#include "3rd_party/yaml-cpp/yaml.h"
#include "common/logging.h"
Vocab::Vocab() {
}
size_t Vocab::operator[](const std::string& word) const {
auto it = str2id_.find(word);
if(it != str2id_.end())
return it->second;
else
return UNK_ID;
}
Words Vocab::operator()(const std::vector<std::string>& lineTokens, bool addEOS) const {
Words words(lineTokens.size());
std::transform(lineTokens.begin(), lineTokens.end(), words.begin(),
[&](const std::string& w) { return (*this)[w]; });
if(addEOS)
words.push_back(EOS_ID);
return words;
}
Words Vocab::operator()(const std::string& line, bool addEOS) const {
std::vector<std::string> lineTokens;
Split(line, lineTokens, " ");
return (*this)(lineTokens, addEOS);
}
std::vector<std::string> Vocab::operator()(const Words& sentence, bool ignoreEOS) const {
std::vector<std::string> decoded;
for(size_t i = 0; i < sentence.size(); ++i) {
if(sentence[i] != EOS_ID || !ignoreEOS) {
decoded.push_back((*this)[sentence[i]]);
}
}
return decoded;
}
const std::string& Vocab::operator[](size_t id) const {
UTIL_THROW_IF2(id >= id2str_.size(), "Unknown word id: " << id);
return id2str_[id];
}
size_t Vocab::size() const {
return id2str_.size();
}
void Vocab::loadOrCreate(const std::string& trainPath, int max)
{
if(boost::filesystem::exists(trainPath + ".json")) {
load(trainPath + ".json", max);
return;
}
if(boost::filesystem::exists(trainPath + ".yml")) {
load(trainPath + ".yml", max);
return;
}
create(trainPath + ".yml", max, trainPath);
load(trainPath + ".yml", max);
}
void Vocab::load(const std::string& vocabPath, int max)
{
LOG(data) << "Loading vocabulary from " << vocabPath << " (max: " << max << ")";
YAML::Node vocab = YAML::Load(InputFileStream(vocabPath));
for(auto&& pair : vocab) {
auto str = pair.first.as<std::string>();
auto id = pair.second.as<Word>();
if (id < (Word)max) {
str2id_[str] = id;
if(id >= id2str_.size())
id2str_.resize(id + 1);
id2str_[id] = str;
}
}
UTIL_THROW_IF2(id2str_.empty(), "Empty vocabulary " << vocabPath);
id2str_[EOS_ID] = EOS_STR;
id2str_[UNK_ID] = UNK_STR;
}
class Vocab::VocabFreqOrderer
{
public:
bool operator()(const Vocab::Str2Id::value_type* a, const Vocab::Str2Id::value_type* b) const {
return a->second < b->second;
}
};
void Vocab::create(const std::string& vocabPath, int max, const std::string& trainPath)
{
LOG(data) << "Creating vocabulary " << vocabPath
<< " from " << trainPath << " (max: " << max << ")";
UTIL_THROW_IF2(boost::filesystem::exists(vocabPath),
"Vocab file " << vocabPath << " exist. Not overwriting");
InputFileStream trainStrm(trainPath);
Str2Id vocab;
std::string line;
while (getline((std::istream&)trainStrm, line)) {
std::vector<std::string> toks;
Split(line, toks);
for (const std::string &tok: toks) {
Str2Id::iterator iter = vocab.find(tok);
if (iter == vocab.end())
vocab[tok] = 1;
else
iter->second++;
}
}
// put into vector & sort
std::vector<const Str2Id::value_type*> vocabVec;
vocabVec.reserve(max);
for (const Str2Id::value_type &p: vocab)
vocabVec.push_back(&p);
std::sort(vocabVec.rbegin(), vocabVec.rend(), VocabFreqOrderer());
YAML::Node vocabYaml;
vocabYaml[EOS_STR] = EOS_ID;
vocabYaml[UNK_STR] = UNK_ID;
for(size_t i = 0; i < vocabVec.size(); ++i) {
const Str2Id::value_type *p = vocabVec[i];
vocabYaml[p->first] = i + 2;
}
OutputFileStream vocabStrm(vocabPath);
(std::ostream&)vocabStrm << vocabYaml;
}
<|endoftext|> |
<commit_before>#include <csignal>
#include <cstdlib>
#include <string>
#include <vector>
#ifndef _WIN32
#include <cstring>
#include <execinfo.h>
#include <unistd.h>
#endif
#pragma warning(push, 0)
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/raw_ostream.h>
#pragma warning(pop)
#include "../driver/driver.h"
#include "../driver/repl.h"
#include "../support/utility.h"
using namespace delta;
static void printHelp() {
llvm::outs() << "OVERVIEW: Delta compiler\n"
"\n"
"USAGE: delta [options] <inputs>\n"
"\n"
"OPTIONS:\n"
" -c - Compile only, generating an .o file; don't link\n"
" -emit-assembly - Emit assembly code\n"
" -emit-llvm-bitcode - Emit LLVM bitcode\n"
" -F<directory> - Add a search path for C framework header import\n"
" -fPIC - Emit position-independent code\n"
" -help - Display this help\n"
" -I<directory> - Add a search path for module and C header import\n"
" -o<filename> - Use the given filename for the output executable\n"
" -parse - Perform parsing\n"
" -print-ast - Print the abstract syntax tree to stdout\n"
" -print-ir - Print the generated LLVM IR to stdout\n"
" -typecheck - Perform parsing and type checking\n"
" -Werror - Treat warnings as errors\n";
}
extern "C" void signalHandler(int signal) {
#ifndef _WIN32
void* stacktrace[128];
int size = backtrace(stacktrace, 128);
llvm::errs() << strsignal(signal) << '\n';
backtrace_symbols_fd(stacktrace, size, STDERR_FILENO);
#endif
std::exit(signal);
}
int main(int argc, const char** argv) {
std::signal(SIGINT, signalHandler);
std::signal(SIGILL, signalHandler);
std::signal(SIGABRT, signalHandler);
std::signal(SIGFPE, signalHandler);
std::signal(SIGSEGV, signalHandler);
std::signal(SIGTERM, signalHandler);
const char* argv0 = argv[0];
--argc;
++argv;
if (argc == 0) {
return replMain();
}
llvm::StringRef command = argv[0];
bool build = command == "build";
bool run = command == "run";
if (build || run) {
--argc;
++argv;
}
std::vector<std::string> inputs;
std::vector<llvm::StringRef> args;
for (int i = 0; i < argc; ++i) {
llvm::StringRef arg = argv[i];
if (arg == "help" || arg == "-help" || arg == "--help" || arg == "-h") {
printHelp();
return 0;
} else if (arg.startswith("-")) {
args.push_back(arg);
} else {
inputs.push_back(arg);
}
}
try {
if (inputs.empty()) {
llvm::SmallString<128> currentPath;
if (auto error = llvm::sys::fs::current_path(currentPath)) {
printErrorAndExit(error.message());
}
return buildPackage(currentPath, argv0, args, run);
} else {
return buildExecutable(inputs, nullptr, argv0, args, ".", "", run);
}
} catch (const CompileError& error) {
error.print();
return 1;
}
}
<commit_msg>Use InitLLVM for stack traces<commit_after>#include <string>
#include <vector>
#pragma warning(push, 0)
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/InitLLVM.h>
#include <llvm/Support/raw_ostream.h>
#pragma warning(pop)
#include "../driver/driver.h"
#include "../driver/repl.h"
#include "../support/utility.h"
using namespace delta;
static void printHelp() {
llvm::outs() << "OVERVIEW: Delta compiler\n"
"\n"
"USAGE: delta [options] <inputs>\n"
"\n"
"OPTIONS:\n"
" -c - Compile only, generating an .o file; don't link\n"
" -emit-assembly - Emit assembly code\n"
" -emit-llvm-bitcode - Emit LLVM bitcode\n"
" -F<directory> - Add a search path for C framework header import\n"
" -fPIC - Emit position-independent code\n"
" -help - Display this help\n"
" -I<directory> - Add a search path for module and C header import\n"
" -o<filename> - Use the given filename for the output executable\n"
" -parse - Perform parsing\n"
" -print-ast - Print the abstract syntax tree to stdout\n"
" -print-ir - Print the generated LLVM IR to stdout\n"
" -typecheck - Perform parsing and type checking\n"
" -Werror - Treat warnings as errors\n";
}
int main(int argc, const char** argv) {
llvm::InitLLVM x(argc, argv);
const char* argv0 = argv[0];
--argc;
++argv;
if (argc == 0) {
return replMain();
}
llvm::StringRef command = argv[0];
bool build = command == "build";
bool run = command == "run";
if (build || run) {
--argc;
++argv;
}
std::vector<std::string> inputs;
std::vector<llvm::StringRef> args;
for (int i = 0; i < argc; ++i) {
llvm::StringRef arg = argv[i];
if (arg == "help" || arg == "-help" || arg == "--help" || arg == "-h") {
printHelp();
return 0;
} else if (arg.startswith("-")) {
args.push_back(arg);
} else {
inputs.push_back(arg);
}
}
try {
if (inputs.empty()) {
llvm::SmallString<128> currentPath;
if (auto error = llvm::sys::fs::current_path(currentPath)) {
printErrorAndExit(error.message());
}
return buildPackage(currentPath, argv0, args, run);
} else {
return buildExecutable(inputs, nullptr, argv0, args, ".", "", run);
}
} catch (const CompileError& error) {
error.print();
return 1;
}
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <std_msgs/String.h>
#include <vector>
#include <fstream>
#include <string>
class WaypointsSaver{
public:
WaypointsSaver() :
filename_("waypoints.yaml")
{
waypoints_viz_sub_ = nh_.subscribe("waypoints_viz", 1, &WaypointsSaver::waypointsVizCallback, this);
waypoints_joy_sub_ = nh_.subscribe("waypoints_joy", 1, &WaypointsSaver::waypointsJoyCallback, this);
finish_pose_sub_ = nh_.subscribe("finish_pose", 1, &WaypointsSaver::finishPoseCallback, this);
ros::NodeHandle private_nh("~");
private_nh.param("filename", filename_, filename_);
private_nh.param("save_joy_button", save_joy_button_, 0);
private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
private_nh.param("world_frame", world_frame_, std::string("/map"));
}
void waypointsJoyCallback(const sensor_msgs::Joy &msg){
static ros::Time saved_time(0.0);
//ROS_INFO_STREAM("joy = " << msg);
if(msg.buttons[save_joy_button_] == 1 && (ros::Time::now() - saved_time).toSec() > 3.0){
tf::StampedTransform robot_gl;
try{
tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
geometry_msgs::PointStamped point;
point.point.x = robot_gl.getOrigin().x();
point.point.y = robot_gl.getOrigin().y();
point.point.z = robot_gl.getOrigin().z();
waypoints_.push_back(point);
saved_time = ros::Time::now();
}catch(tf::TransformException &e){
ROS_WARN_STREAM("tf::TransformException: " << e.what());
}
}
}
void waypointsVizCallback(const geometry_msgs::PointStamped &msg){
ROS_INFO_STREAM("point = " << msg);
waypoints_.push_back(msg);
}
void finishPoseCallback(const geometry_msgs::PoseStamped &msg){
finish_pose_ = msg;
save();
waypoints_.clear();
}
void save(){
std::ofstream ofs(filename_.c_str(), std::ios::out);
ofs << "waypoints:" << std::endl;
for(int i=0; i < waypoints_.size(); i++){
ofs << " " << "- point:" << std::endl;
ofs << " x: " << waypoints_[i].point.x << std::endl;
ofs << " y: " << waypoints_[i].point.y << std::endl;
ofs << " z: " << waypoints_[i].point.z << std::endl;
}
ofs << "finish_pose:" << std::endl;
ofs << " header:" << std::endl;
ofs << " seq: " << finish_pose_.header.seq << std::endl;
ofs << " stamp: " << finish_pose_.header.stamp << std::endl;
ofs << " frame_id: " << finish_pose_.header.frame_id << std::endl;;
ofs << " pose:" << std::endl;
ofs << " position:" << std::endl;
ofs << " x: " << finish_pose_.pose.position.x << std::endl;
ofs << " y: " << finish_pose_.pose.position.y << std::endl;
ofs << " z: " << finish_pose_.pose.position.z << std::endl;
ofs << " orientation:" << std::endl;
ofs << " x: " << finish_pose_.pose.orientation.x << std::endl;
ofs << " y: " << finish_pose_.pose.orientation.y << std::endl;
ofs << " z: " << finish_pose_.pose.orientation.z << std::endl;
ofs << " w: " << finish_pose_.pose.orientation.w << std::endl;
ofs.close();
ROS_INFO_STREAM("write success");
}
void run(){
ros::spin();
}
private:
ros::Subscriber waypoints_viz_sub_;
ros::Subscriber waypoints_joy_sub_;
ros::Subscriber finish_pose_sub_;
std::vector<geometry_msgs::PointStamped> waypoints_;
geometry_msgs::PoseStamped finish_pose_;
tf::TransformListener tf_listener_;
int save_joy_button_;
ros::NodeHandle nh_;
std::string filename_;
std::string world_frame_;
std::string robot_frame_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "waypoints_saver");
WaypointsSaver saver;
saver.run();
return 0;
}
<commit_msg>Add license<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Daiki Maekawa and Robot Design and Control Lab.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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 <ros/ros.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <std_msgs/String.h>
#include <vector>
#include <fstream>
#include <string>
class WaypointsSaver{
public:
WaypointsSaver() :
filename_("waypoints.yaml")
{
waypoints_viz_sub_ = nh_.subscribe("waypoints_viz", 1, &WaypointsSaver::waypointsVizCallback, this);
waypoints_joy_sub_ = nh_.subscribe("waypoints_joy", 1, &WaypointsSaver::waypointsJoyCallback, this);
finish_pose_sub_ = nh_.subscribe("finish_pose", 1, &WaypointsSaver::finishPoseCallback, this);
ros::NodeHandle private_nh("~");
private_nh.param("filename", filename_, filename_);
private_nh.param("save_joy_button", save_joy_button_, 0);
private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
private_nh.param("world_frame", world_frame_, std::string("/map"));
}
void waypointsJoyCallback(const sensor_msgs::Joy &msg){
static ros::Time saved_time(0.0);
//ROS_INFO_STREAM("joy = " << msg);
if(msg.buttons[save_joy_button_] == 1 && (ros::Time::now() - saved_time).toSec() > 3.0){
tf::StampedTransform robot_gl;
try{
tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
geometry_msgs::PointStamped point;
point.point.x = robot_gl.getOrigin().x();
point.point.y = robot_gl.getOrigin().y();
point.point.z = robot_gl.getOrigin().z();
waypoints_.push_back(point);
saved_time = ros::Time::now();
}catch(tf::TransformException &e){
ROS_WARN_STREAM("tf::TransformException: " << e.what());
}
}
}
void waypointsVizCallback(const geometry_msgs::PointStamped &msg){
ROS_INFO_STREAM("point = " << msg);
waypoints_.push_back(msg);
}
void finishPoseCallback(const geometry_msgs::PoseStamped &msg){
finish_pose_ = msg;
save();
waypoints_.clear();
}
void save(){
std::ofstream ofs(filename_.c_str(), std::ios::out);
ofs << "waypoints:" << std::endl;
for(int i=0; i < waypoints_.size(); i++){
ofs << " " << "- point:" << std::endl;
ofs << " x: " << waypoints_[i].point.x << std::endl;
ofs << " y: " << waypoints_[i].point.y << std::endl;
ofs << " z: " << waypoints_[i].point.z << std::endl;
}
ofs << "finish_pose:" << std::endl;
ofs << " header:" << std::endl;
ofs << " seq: " << finish_pose_.header.seq << std::endl;
ofs << " stamp: " << finish_pose_.header.stamp << std::endl;
ofs << " frame_id: " << finish_pose_.header.frame_id << std::endl;;
ofs << " pose:" << std::endl;
ofs << " position:" << std::endl;
ofs << " x: " << finish_pose_.pose.position.x << std::endl;
ofs << " y: " << finish_pose_.pose.position.y << std::endl;
ofs << " z: " << finish_pose_.pose.position.z << std::endl;
ofs << " orientation:" << std::endl;
ofs << " x: " << finish_pose_.pose.orientation.x << std::endl;
ofs << " y: " << finish_pose_.pose.orientation.y << std::endl;
ofs << " z: " << finish_pose_.pose.orientation.z << std::endl;
ofs << " w: " << finish_pose_.pose.orientation.w << std::endl;
ofs.close();
ROS_INFO_STREAM("write success");
}
void run(){
ros::spin();
}
private:
ros::Subscriber waypoints_viz_sub_;
ros::Subscriber waypoints_joy_sub_;
ros::Subscriber finish_pose_sub_;
std::vector<geometry_msgs::PointStamped> waypoints_;
geometry_msgs::PoseStamped finish_pose_;
tf::TransformListener tf_listener_;
int save_joy_button_;
ros::NodeHandle nh_;
std::string filename_;
std::string world_frame_;
std::string robot_frame_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "waypoints_saver");
WaypointsSaver saver;
saver.run();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/source/event_posix.h"
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
namespace webrtc {
const long int E6 = 1000000;
const long int E9 = 1000 * E6;
EventWrapper* EventPosix::Create() {
EventPosix* ptr = new EventPosix;
if (!ptr) {
return NULL;
}
const int error = ptr->Construct();
if (error) {
delete ptr;
return NULL;
}
return ptr;
}
EventPosix::EventPosix()
: timer_thread_(0),
timer_event_(0),
periodic_(false),
time_(0),
count_(0),
state_(kDown) {
}
int EventPosix::Construct() {
// Set start time to zero
memset(&created_at_, 0, sizeof(created_at_));
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
int result = pthread_mutex_init(&mutex_, &attr);
if (result != 0) {
return -1;
}
#ifdef WEBRTC_CLOCK_TYPE_REALTIME
result = pthread_cond_init(&cond_, 0);
if (result != 0) {
return -1;
}
#else
pthread_condattr_t cond_attr;
result = pthread_condattr_init(&cond_attr);
if (result != 0) {
return -1;
}
result = pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC);
if (result != 0) {
return -1;
}
result = pthread_cond_init(&cond_, &cond_attr);
if (result != 0) {
return -1;
}
result = pthread_condattr_destroy(&cond_attr);
if (result != 0) {
return -1;
}
#endif
return 0;
}
EventPosix::~EventPosix() {
StopTimer();
pthread_cond_destroy(&cond_);
pthread_mutex_destroy(&mutex_);
}
bool EventPosix::Reset() {
if (0 != pthread_mutex_lock(&mutex_)) {
return false;
}
state_ = kDown;
pthread_mutex_unlock(&mutex_);
return true;
}
bool EventPosix::Set() {
if (0 != pthread_mutex_lock(&mutex_)) {
return false;
}
state_ = kUp;
// Release all waiting threads
pthread_cond_broadcast(&cond_);
pthread_mutex_unlock(&mutex_);
return true;
}
EventTypeWrapper EventPosix::Wait(unsigned long timeout) {
int ret_val = 0;
if (0 != pthread_mutex_lock(&mutex_)) {
return kEventError;
}
if (kDown == state_) {
if (WEBRTC_EVENT_INFINITE != timeout) {
timespec end_at;
#ifndef WEBRTC_MAC
#ifdef WEBRTC_CLOCK_TYPE_REALTIME
clock_gettime(CLOCK_REALTIME, &end_at);
#else
clock_gettime(CLOCK_MONOTONIC, &end_at);
#endif
#else
timeval value;
struct timezone time_zone;
time_zone.tz_minuteswest = 0;
time_zone.tz_dsttime = 0;
gettimeofday(&value, &time_zone);
TIMEVAL_TO_TIMESPEC(&value, &end_at);
#endif
end_at.tv_sec += timeout / 1000;
end_at.tv_nsec += (timeout - (timeout / 1000) * 1000) * E6;
if (end_at.tv_nsec >= E9) {
end_at.tv_sec++;
end_at.tv_nsec -= E9;
}
ret_val = pthread_cond_timedwait(&cond_, &mutex_, &end_at);
} else {
ret_val = pthread_cond_wait(&cond_, &mutex_);
}
}
state_ = kDown;
pthread_mutex_unlock(&mutex_);
switch (ret_val) {
case 0:
return kEventSignaled;
case ETIMEDOUT:
return kEventTimeout;
default:
return kEventError;
}
}
EventTypeWrapper EventPosix::Wait(timespec& wake_at) {
int ret_val = 0;
if (0 != pthread_mutex_lock(&mutex_)) {
return kEventError;
}
if (kUp != state_) {
ret_val = pthread_cond_timedwait(&cond_, &mutex_, &wake_at);
}
state_ = kDown;
pthread_mutex_unlock(&mutex_);
switch (ret_val) {
case 0:
return kEventSignaled;
case ETIMEDOUT:
return kEventTimeout;
default:
return kEventError;
}
}
bool EventPosix::StartTimer(bool periodic, unsigned long time) {
pthread_mutex_lock(&mutex_);
if (timer_thread_) {
if (periodic_) {
// Timer already started.
pthread_mutex_unlock(&mutex_);
return false;
} else {
// New one shot timer
time_ = time;
created_at_.tv_sec = 0;
timer_event_->Set();
pthread_mutex_unlock(&mutex_);
return true;
}
}
// Start the timer thread
timer_event_ = static_cast<EventPosix*>(EventWrapper::Create());
const char* thread_name = "WebRtc_event_timer_thread";
timer_thread_ = ThreadWrapper::CreateThread(Run, this, kRealtimePriority,
thread_name);
periodic_ = periodic;
time_ = time;
unsigned int id = 0;
bool started = timer_thread_->Start(id);
pthread_mutex_unlock(&mutex_);
return started;
}
bool EventPosix::Run(ThreadObj obj) {
return static_cast<EventPosix*>(obj)->Process();
}
bool EventPosix::Process() {
pthread_mutex_lock(&mutex_);
if (created_at_.tv_sec == 0) {
#ifndef WEBRTC_MAC
#ifdef WEBRTC_CLOCK_TYPE_REALTIME
clock_gettime(CLOCK_REALTIME, &created_at_);
#else
clock_gettime(CLOCK_MONOTONIC, &created_at_);
#endif
#else
timeval value;
struct timezone time_zone;
time_zone.tz_minuteswest = 0;
time_zone.tz_dsttime = 0;
gettimeofday(&value, &time_zone);
TIMEVAL_TO_TIMESPEC(&value, &created_at_);
#endif
count_ = 0;
}
timespec end_at;
unsigned long long time = time_ * ++count_;
end_at.tv_sec = created_at_.tv_sec + time / 1000;
end_at.tv_nsec = created_at_.tv_nsec + (time - (time / 1000) * 1000) * E6;
if (end_at.tv_nsec >= E9) {
end_at.tv_sec++;
end_at.tv_nsec -= E9;
}
pthread_mutex_unlock(&mutex_);
switch (timer_event_->Wait(end_at)) {
case kEventSignaled:
return true;
case kEventError:
return false;
case kEventTimeout:
break;
}
pthread_mutex_lock(&mutex_);
if (periodic_ || count_ == 1)
Set();
pthread_mutex_unlock(&mutex_);
return true;
}
bool EventPosix::StopTimer() {
if (timer_event_) {
timer_event_->Set();
}
if (timer_thread_) {
if (!timer_thread_->Stop()) {
return false;
}
delete timer_thread_;
timer_thread_ = 0;
}
if (timer_event_) {
delete timer_event_;
timer_event_ = 0;
}
// Set time to zero to force new reference time for the timer.
memset(&created_at_, 0, sizeof(created_at_));
count_ = 0;
return true;
}
} // namespace webrtc
<commit_msg>Add CHECK to EventWrapper to see if there's a subtle bug there or not.<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/source/event_posix.h"
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include "webrtc/base/checks.h"
namespace webrtc {
const long int E6 = 1000000;
const long int E9 = 1000 * E6;
EventWrapper* EventPosix::Create() {
EventPosix* ptr = new EventPosix;
if (!ptr) {
return NULL;
}
const int error = ptr->Construct();
if (error) {
delete ptr;
return NULL;
}
return ptr;
}
EventPosix::EventPosix()
: timer_thread_(0),
timer_event_(0),
periodic_(false),
time_(0),
count_(0),
state_(kDown) {
}
int EventPosix::Construct() {
// Set start time to zero
memset(&created_at_, 0, sizeof(created_at_));
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
int result = pthread_mutex_init(&mutex_, &attr);
if (result != 0) {
return -1;
}
#ifdef WEBRTC_CLOCK_TYPE_REALTIME
result = pthread_cond_init(&cond_, 0);
if (result != 0) {
return -1;
}
#else
pthread_condattr_t cond_attr;
result = pthread_condattr_init(&cond_attr);
if (result != 0) {
return -1;
}
result = pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC);
if (result != 0) {
return -1;
}
result = pthread_cond_init(&cond_, &cond_attr);
if (result != 0) {
return -1;
}
result = pthread_condattr_destroy(&cond_attr);
if (result != 0) {
return -1;
}
#endif
return 0;
}
EventPosix::~EventPosix() {
StopTimer();
pthread_cond_destroy(&cond_);
pthread_mutex_destroy(&mutex_);
}
bool EventPosix::Reset() {
if (0 != pthread_mutex_lock(&mutex_)) {
return false;
}
state_ = kDown;
pthread_mutex_unlock(&mutex_);
return true;
}
bool EventPosix::Set() {
if (0 != pthread_mutex_lock(&mutex_)) {
return false;
}
state_ = kUp;
// Release all waiting threads
pthread_cond_broadcast(&cond_);
pthread_mutex_unlock(&mutex_);
return true;
}
EventTypeWrapper EventPosix::Wait(unsigned long timeout) {
int ret_val = 0;
if (0 != pthread_mutex_lock(&mutex_)) {
return kEventError;
}
if (kDown == state_) {
if (WEBRTC_EVENT_INFINITE != timeout) {
timespec end_at;
#ifndef WEBRTC_MAC
#ifdef WEBRTC_CLOCK_TYPE_REALTIME
clock_gettime(CLOCK_REALTIME, &end_at);
#else
clock_gettime(CLOCK_MONOTONIC, &end_at);
#endif
#else
timeval value;
struct timezone time_zone;
time_zone.tz_minuteswest = 0;
time_zone.tz_dsttime = 0;
gettimeofday(&value, &time_zone);
TIMEVAL_TO_TIMESPEC(&value, &end_at);
#endif
end_at.tv_sec += timeout / 1000;
end_at.tv_nsec += (timeout - (timeout / 1000) * 1000) * E6;
if (end_at.tv_nsec >= E9) {
end_at.tv_sec++;
end_at.tv_nsec -= E9;
}
ret_val = pthread_cond_timedwait(&cond_, &mutex_, &end_at);
} else {
ret_val = pthread_cond_wait(&cond_, &mutex_);
}
}
if (ret_val == 0)
CHECK(state_ == kUp);
state_ = kDown;
pthread_mutex_unlock(&mutex_);
switch (ret_val) {
case 0:
return kEventSignaled;
case ETIMEDOUT:
return kEventTimeout;
default:
return kEventError;
}
}
EventTypeWrapper EventPosix::Wait(timespec& wake_at) {
int ret_val = 0;
if (0 != pthread_mutex_lock(&mutex_)) {
return kEventError;
}
if (kUp != state_) {
ret_val = pthread_cond_timedwait(&cond_, &mutex_, &wake_at);
}
state_ = kDown;
pthread_mutex_unlock(&mutex_);
switch (ret_val) {
case 0:
return kEventSignaled;
case ETIMEDOUT:
return kEventTimeout;
default:
return kEventError;
}
}
bool EventPosix::StartTimer(bool periodic, unsigned long time) {
pthread_mutex_lock(&mutex_);
if (timer_thread_) {
if (periodic_) {
// Timer already started.
pthread_mutex_unlock(&mutex_);
return false;
} else {
// New one shot timer
time_ = time;
created_at_.tv_sec = 0;
timer_event_->Set();
pthread_mutex_unlock(&mutex_);
return true;
}
}
// Start the timer thread
timer_event_ = static_cast<EventPosix*>(EventWrapper::Create());
const char* thread_name = "WebRtc_event_timer_thread";
timer_thread_ = ThreadWrapper::CreateThread(Run, this, kRealtimePriority,
thread_name);
periodic_ = periodic;
time_ = time;
unsigned int id = 0;
bool started = timer_thread_->Start(id);
pthread_mutex_unlock(&mutex_);
return started;
}
bool EventPosix::Run(ThreadObj obj) {
return static_cast<EventPosix*>(obj)->Process();
}
bool EventPosix::Process() {
pthread_mutex_lock(&mutex_);
if (created_at_.tv_sec == 0) {
#ifndef WEBRTC_MAC
#ifdef WEBRTC_CLOCK_TYPE_REALTIME
clock_gettime(CLOCK_REALTIME, &created_at_);
#else
clock_gettime(CLOCK_MONOTONIC, &created_at_);
#endif
#else
timeval value;
struct timezone time_zone;
time_zone.tz_minuteswest = 0;
time_zone.tz_dsttime = 0;
gettimeofday(&value, &time_zone);
TIMEVAL_TO_TIMESPEC(&value, &created_at_);
#endif
count_ = 0;
}
timespec end_at;
unsigned long long time = time_ * ++count_;
end_at.tv_sec = created_at_.tv_sec + time / 1000;
end_at.tv_nsec = created_at_.tv_nsec + (time - (time / 1000) * 1000) * E6;
if (end_at.tv_nsec >= E9) {
end_at.tv_sec++;
end_at.tv_nsec -= E9;
}
pthread_mutex_unlock(&mutex_);
switch (timer_event_->Wait(end_at)) {
case kEventSignaled:
return true;
case kEventError:
return false;
case kEventTimeout:
break;
}
pthread_mutex_lock(&mutex_);
if (periodic_ || count_ == 1)
Set();
pthread_mutex_unlock(&mutex_);
return true;
}
bool EventPosix::StopTimer() {
if (timer_event_) {
timer_event_->Set();
}
if (timer_thread_) {
if (!timer_thread_->Stop()) {
return false;
}
delete timer_thread_;
timer_thread_ = 0;
}
if (timer_event_) {
delete timer_event_;
timer_event_ = 0;
}
// Set time to zero to force new reference time for the timer.
memset(&created_at_, 0, sizeof(created_at_));
count_ = 0;
return true;
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#ifndef _IZENELIB_AM_SUCCINCT_CONSTANTS_HPP
#define _IZENELIB_AM_SUCCINCT_CONSTANTS_HPP
#include <types.h>
NS_IZENELIB_AM_BEGIN
namespace succinct
{
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
/* Defined by BSIZE */
typedef uint64_t block_t;
/* Block size (64-bit environment) */
static const size_t BSIZE = 64;
static const size_t PRESUM_SZ = 128;
static const size_t CACHELINE_SZ = 256;
static const size_t LEVEL1_NUM = 256;
static const size_t LEVEL2_NUM = BSIZE;
static const size_t kLargeBlockSize = 1024;
static const size_t kHugeBlockSize = 32768;
static const size_t kSmallBlockSize = 64;
static const size_t kSelectBlockSize = 2048;
static const size_t kSmallBlockPerLargeBlock = kLargeBlockSize / kSmallBlockSize;
static const size_t kSmallBlockPerHugeBlock = kHugeBlockSize / kSmallBlockSize;
}
NS_IZENELIB_AM_END
#endif
<commit_msg>uint16_t is safe for at most 65536-64<commit_after>#ifndef _IZENELIB_AM_SUCCINCT_CONSTANTS_HPP
#define _IZENELIB_AM_SUCCINCT_CONSTANTS_HPP
#include <types.h>
NS_IZENELIB_AM_BEGIN
namespace succinct
{
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
/* Defined by BSIZE */
typedef uint64_t block_t;
/* Block size (64-bit environment) */
static const size_t BSIZE = 64;
static const size_t PRESUM_SZ = 128;
static const size_t CACHELINE_SZ = 256;
static const size_t LEVEL1_NUM = 256;
static const size_t LEVEL2_NUM = BSIZE;
static const size_t kLargeBlockSize = 1024;
static const size_t kHugeBlockSize = 65536;
static const size_t kSmallBlockSize = 64;
static const size_t kSelectBlockSize = 2048;
static const size_t kSmallBlockPerLargeBlock = kLargeBlockSize / kSmallBlockSize;
static const size_t kSmallBlockPerHugeBlock = kHugeBlockSize / kSmallBlockSize;
}
NS_IZENELIB_AM_END
#endif
<|endoftext|> |
<commit_before>#ifndef TIMING_HPP_
#define TIMING_HPP_
#include <boost/chrono/chrono.hpp>
#include <boost/chrono/chrono_io.hpp>
#include <boost/chrono/system_clocks.hpp>
typedef boost::chrono::high_resolution_clock clock_type;
typedef clock_type::time_point time_point_type;
typedef clock_type::duration duration_type;
/*! Basic timer class */
class timer {
public:
static constexpr double hertz = (double)clock_type::period::num/clock_type::period::den;
timer() : m_start( clock_type::now() ), m_end( time_point_type::max() ) {}
inline void start() {
m_end = time_point_type::max();
m_start = clock_type::now();
}
inline void stop() {
m_end = clock_type::now();
}
duration_type elapsed() const {
if( m_end == time_point_type::max() ) {
time_point_type t = clock_type::now();
return (t - m_start);
}
return (m_end - m_start);
}
virtual ~timer() {}
protected:
time_point_type m_start, m_end;
};
#endif // TIMING_HPP_
<commit_msg>Removed timing<commit_after><|endoftext|> |
<commit_before>#include "rltk.hpp"
#include <SFML/Graphics.hpp>
namespace rltk {
void run(std::function<void(double)> on_tick, const int window_width, const int window_height, const std::string window_title) {
sf::RenderWindow window(sf::VideoMode(window_width, window_height, sf::Style::Titlebar | sf::Style::Resize | sf::Style::Close), window_title);
double duration_ms = 0.0;
while (window.isOpen())
{
clock_t start_time = clock();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
on_tick(duration_ms);
window.display();
duration_ms = ((clock() - start_time) * 1000.0) / CLOCKS_PER_SEC;
}
}
}
<commit_msg>Window moved to a unique_ptr<commit_after>#include "rltk.hpp"
#include <SFML/Graphics.hpp>
#include <memory>
namespace rltk {
std::unique_ptr<sf::RenderWindow> main_window;
void run(std::function<void(double)> on_tick, const int window_width, const int window_height, const std::string window_title) {
std::make_unique<sf::RenderWindow>(sf::VideoMode(window_width, window_height, sf::Style::Titlebar | sf::Style::Resize | sf::Style::Close), window_title);
main_window->setVerticalSyncEnabled(true);
double duration_ms = 0.0;
while (main_window->isOpen())
{
clock_t start_time = clock();
sf::Event event;
while (main_window->pollEvent(event))
{
if (event.type == sf::Event::Closed) {
main_window->close();
}
}
main_window->clear();
sf::Vector2u size_pixels = main_window->getSize();
on_tick(duration_ms);
main_window->display();
duration_ms = ((clock() - start_time) * 1000.0) / CLOCKS_PER_SEC;
}
}
}
<|endoftext|> |
<commit_before>/*
* MoldUDP64 protocol support
*
* The implementation is based on the following specifications provided
* by NASDAQ:
*
* MoldUDP64 Protocol Specification
* V 1.00
* 07/07/2009
*/
#pragma once
#include "helix/nasdaq/moldudp64_messages.h"
#include "helix/compat/endian.h"
#include "helix/helix.hh"
#include "helix/net.hh"
#include <experimental/optional>
namespace helix {
namespace nasdaq {
enum moldudp64_state {
synchronized,
gap_fill,
};
template<typename Handler>
class moldudp64_session : public session {
Handler _handler;
send_callback _send_cb;
uint64_t _expected_seq_no = 1;
moldudp64_state _state = moldudp64_state::synchronized;
std::experimental::optional<uint64_t> _sync_to_seq_no;
public:
explicit moldudp64_session(void *data);
virtual bool is_rth_timestamp(uint64_t timestamp) override;
virtual void subscribe(const std::string& symbol, size_t max_orders) override;
virtual void register_callback(event_callback callback) override;
virtual void set_send_callback(send_callback callback) override;
virtual size_t process_packet(const net::packet_view& packet) override;
private:
void retransmit_request(uint64_t seq_no, uint64_t expected_seq_no);
};
template<typename Handler>
moldudp64_session<Handler>::moldudp64_session(void* data)
: session{data}
{
}
template<typename Handler>
bool moldudp64_session<Handler>::is_rth_timestamp(uint64_t timestamp)
{
return _handler.is_rth_timestamp(timestamp);
}
template<typename Handler>
void moldudp64_session<Handler>::subscribe(const std::string& symbol, size_t max_orders)
{
_handler.subscribe(symbol, max_orders);
}
template<typename Handler>
void moldudp64_session<Handler>::register_callback(event_callback callback)
{
_handler.register_callback(callback);
}
template<typename Handler>
void moldudp64_session<Handler>::set_send_callback(send_callback send_cb)
{
_send_cb = send_cb;
}
template<typename Handler>
size_t moldudp64_session<Handler>::process_packet(const net::packet_view& packet)
{
auto* p = packet.buf();
if (packet.len() < sizeof(moldudp64_header)) {
throw truncated_packet_error("MoldUDP64 header is truncated");
}
auto* header = packet.cast<moldudp64_header>();
auto recv_seq_no = be64toh(header->SequenceNumber);
if (recv_seq_no < _expected_seq_no) {
return packet.len();
}
if (_expected_seq_no < recv_seq_no) {
_sync_to_seq_no = recv_seq_no;
if (_state == moldudp64_state::synchronized) {
_state = moldudp64_state::gap_fill;
retransmit_request(recv_seq_no, _expected_seq_no);
}
return packet.len();
}
bool sync = _state == moldudp64_state::synchronized;
p += sizeof(moldudp64_header);
for (int i = 0; i < be16toh(header->MessageCount); i++) {
auto* msg_block = reinterpret_cast<const moldudp64_message_block*>(p);
p += sizeof(moldudp64_message_block);
auto message_length = be16toh(msg_block->MessageLength);
if (message_length) {
_handler.process_packet(net::packet_view{p, message_length}, sync);
}
p += message_length;
_expected_seq_no++;
}
if (_state == moldudp64_state::gap_fill) {
if (_expected_seq_no >= _sync_to_seq_no.value()) {
_state = moldudp64_state::synchronized;
_sync_to_seq_no = std::experimental::nullopt;
} else {
retransmit_request(recv_seq_no, _expected_seq_no);
}
}
return p - packet.buf();
}
template<typename Handler>
void moldudp64_session<Handler>::retransmit_request(uint64_t seq_no, uint64_t expected_seq_no)
{
if (!bool(_send_cb)) {
throw std::runtime_error(std::string("invalid sequence number: ") + std::to_string(seq_no) + ", expected: " + std::to_string(expected_seq_no));
}
uint64_t message_count = 0xfffe;
moldudp64_request_packet request_packet;
request_packet.SequenceNumber = htobe64(expected_seq_no);
request_packet.MessageCount = htobe16(message_count);
char *base = reinterpret_cast<char*>(&request_packet);
size_t len = sizeof(request_packet);
_send_cb(base, len);
}
}
}
<commit_msg>nasdaq/moldudp64: Use operator* for accessing optional value<commit_after>/*
* MoldUDP64 protocol support
*
* The implementation is based on the following specifications provided
* by NASDAQ:
*
* MoldUDP64 Protocol Specification
* V 1.00
* 07/07/2009
*/
#pragma once
#include "helix/nasdaq/moldudp64_messages.h"
#include "helix/compat/endian.h"
#include "helix/helix.hh"
#include "helix/net.hh"
#include <experimental/optional>
namespace helix {
namespace nasdaq {
enum moldudp64_state {
synchronized,
gap_fill,
};
template<typename Handler>
class moldudp64_session : public session {
Handler _handler;
send_callback _send_cb;
uint64_t _expected_seq_no = 1;
moldudp64_state _state = moldudp64_state::synchronized;
std::experimental::optional<uint64_t> _sync_to_seq_no;
public:
explicit moldudp64_session(void *data);
virtual bool is_rth_timestamp(uint64_t timestamp) override;
virtual void subscribe(const std::string& symbol, size_t max_orders) override;
virtual void register_callback(event_callback callback) override;
virtual void set_send_callback(send_callback callback) override;
virtual size_t process_packet(const net::packet_view& packet) override;
private:
void retransmit_request(uint64_t seq_no, uint64_t expected_seq_no);
};
template<typename Handler>
moldudp64_session<Handler>::moldudp64_session(void* data)
: session{data}
{
}
template<typename Handler>
bool moldudp64_session<Handler>::is_rth_timestamp(uint64_t timestamp)
{
return _handler.is_rth_timestamp(timestamp);
}
template<typename Handler>
void moldudp64_session<Handler>::subscribe(const std::string& symbol, size_t max_orders)
{
_handler.subscribe(symbol, max_orders);
}
template<typename Handler>
void moldudp64_session<Handler>::register_callback(event_callback callback)
{
_handler.register_callback(callback);
}
template<typename Handler>
void moldudp64_session<Handler>::set_send_callback(send_callback send_cb)
{
_send_cb = send_cb;
}
template<typename Handler>
size_t moldudp64_session<Handler>::process_packet(const net::packet_view& packet)
{
auto* p = packet.buf();
if (packet.len() < sizeof(moldudp64_header)) {
throw truncated_packet_error("MoldUDP64 header is truncated");
}
auto* header = packet.cast<moldudp64_header>();
auto recv_seq_no = be64toh(header->SequenceNumber);
if (recv_seq_no < _expected_seq_no) {
return packet.len();
}
if (_expected_seq_no < recv_seq_no) {
_sync_to_seq_no = recv_seq_no;
if (_state == moldudp64_state::synchronized) {
_state = moldudp64_state::gap_fill;
retransmit_request(recv_seq_no, _expected_seq_no);
}
return packet.len();
}
bool sync = _state == moldudp64_state::synchronized;
p += sizeof(moldudp64_header);
for (int i = 0; i < be16toh(header->MessageCount); i++) {
auto* msg_block = reinterpret_cast<const moldudp64_message_block*>(p);
p += sizeof(moldudp64_message_block);
auto message_length = be16toh(msg_block->MessageLength);
if (message_length) {
_handler.process_packet(net::packet_view{p, message_length}, sync);
}
p += message_length;
_expected_seq_no++;
}
if (_state == moldudp64_state::gap_fill) {
if (_expected_seq_no >= *_sync_to_seq_no) {
_state = moldudp64_state::synchronized;
_sync_to_seq_no = std::experimental::nullopt;
} else {
retransmit_request(recv_seq_no, _expected_seq_no);
}
}
return p - packet.buf();
}
template<typename Handler>
void moldudp64_session<Handler>::retransmit_request(uint64_t seq_no, uint64_t expected_seq_no)
{
if (!bool(_send_cb)) {
throw std::runtime_error(std::string("invalid sequence number: ") + std::to_string(seq_no) + ", expected: " + std::to_string(expected_seq_no));
}
uint64_t message_count = 0xfffe;
moldudp64_request_packet request_packet;
request_packet.SequenceNumber = htobe64(expected_seq_no);
request_packet.MessageCount = htobe16(message_count);
char *base = reinterpret_cast<char*>(&request_packet);
size_t len = sizeof(request_packet);
_send_cb(base, len);
}
}
}
<|endoftext|> |
<commit_before>#ifndef IMQUE_QUEUE_QUEUE_IMPL_HH
#define IMQUE_QUEUE_QUEUE_IMPL_HH
#include "../atomic/atomic.hh"
#include "../ipc/shared_memory.hh"
#include "../allocator/fixed_allocator.hh"
#include <inttypes.h>
#include <string.h>
#include <algorithm>
namespace imque {
namespace queue {
static const char MAGIC[] = "IMQUE-0.1.1";
// FIFOキュー
class QueueImpl {
struct Node {
uint32_t next;
uint32_t data_size;
char data[0];
static const uint32_t END = 0;
};
struct Header {
char magic[sizeof(MAGIC)];
uint32_t shm_size;
volatile uint32_t head; // NOTE: mdを保持。md自体がABA対策がなされているので、ここではそれ用のフィールドは不要。
volatile uint32_t tail;
uint32_t overflowed_count;
};
static const uint32_t HEADER_SIZE = sizeof(Header);
// 参照カウント周りの処理隠蔽用のクラス
class NodeRef {
public:
NodeRef(uint32_t md, allocator::FixedAllocator& alc)
: alc_(alc), md_(0) {
if(alc.dup(md)) { // 既に解放されている可能性もあるのでチェックする
md_ = md;
}
}
~NodeRef() {
if(md_) {
alc_.release(md_);
}
}
operator bool() const { return md_ != 0; }
Node node_copy() const { return atomic::fetch(alc_.ptr<Node>(md_)); }
uint32_t& node_next() { return alc_.ptr<Node>(md_)->next; }
uint32_t md() const { return md_; }
private:
allocator::FixedAllocator& alc_;
uint32_t md_;
};
public:
QueueImpl(ipc::SharedMemory& shm)
: shm_size_(shm.size()),
que_(shm.ptr<Header>()),
alc_(shm.ptr<void>(HEADER_SIZE), std::max(0, static_cast<int32_t>(shm.size() - HEADER_SIZE))) {
}
operator bool() const { return alc_ && que_; }
// 初期化メソッド。
// コンストラクタに渡した一つの shm につき、一回呼び出す必要がある。
void init() {
if(*this) {
alc_.init();
uint32_t sentinel = alc_.allocate(sizeof(Node));
if(sentinel == 0) {
que_ = NULL;
return;
}
memcpy(que_->magic, MAGIC, sizeof(MAGIC));
que_->shm_size = shm_size_;
alc_.ptr<Node>(sentinel)->next = Node::END;
que_->head = sentinel;
que_->tail = sentinel;
assert(alc_.dup(sentinel)); // head と tail の二箇所から参照されているので、参照カウントを一つ増やしておく
que_->overflowed_count = 0;
}
}
// 重複初期化チェック(簡易)付きの初期化メソッド。
// 共有メモリ用のファイルを使い回している場合は、二回目以降は明示的なinit()呼び出しを行った方が安全。
void init_once() {
if(*this && (memcmp(que_->magic, MAGIC, sizeof(MAGIC)) != 0 ||
shm_size_ != que_->shm_size)) {
init();
}
}
// キューに要素を追加する (キューに空きがない場合は false を返す)
bool enq(const void* data, size_t size) {
return enqv(&data, &size, 1);
}
// キューに要素を追加する (キューに空きがない場合は false を返す)
// datav および sizev は count 分のサイズを持ち、それらを全て結合したデータがキューには追加される
bool enqv(const void** datav, size_t* sizev, size_t count) {
size_t total_size = 0;
for(size_t i=0; i < count; i++) {
total_size += sizev[i];
}
uint32_t md = alc_.allocate(sizeof(Node) + total_size); // md = memory descriptor
if(md == 0) {
atomic::add(&que_->overflowed_count, 1);
return false;
}
Node* node = alc_.ptr<Node>(md);
node->next = Node::END;
node->data_size = total_size;
size_t offset = sizeof(Node);
for(size_t i=0; i < count; i++) {
memcpy(alc_.ptr<void>(md, offset), datav[i], sizev[i]);
offset += sizev[i];
}
enqImpl(md);
return true;
}
// キューから要素を取り出し buf に格納する (キューが空の場合は false を返す)
bool deq(std::string& buf) {
uint32_t md = deqImpl();
if(md == 0) {
return false;
}
Node* node = alc_.ptr<Node>(md);
buf.assign(node->data, node->data_size);
assert(alc_.release(md));
return true;
}
// キューが空かどうか
bool isEmpty() {
for(;;) {
NodeRef head_ref(que_->head, alc_);
if(! head_ref) {
continue;
}
return head_ref.node_copy().next == Node::END;
}
}
// キューへの要素追加に失敗した回数を返す
size_t overflowedCount() const { return que_->overflowed_count; }
size_t resetOverflowedCount() {
return atomic::fetch_and_clear(&que_->overflowed_count);
}
private:
void enqImpl(uint32_t new_tail) {
assert(alc_.dup(new_tail, 2)); // head と tail からの参照分を始めにカウントしておく
for(;;) {
NodeRef tail_ref(que_->tail, alc_);
if(! tail_ref) {
continue;
}
Node node = tail_ref.node_copy();
if(node.next != Node::END) {
// tail が末尾を指していないので、一つ前に進める
if(atomic::compare_and_swap(&que_->tail, tail_ref.md(), node.next)) {
alc_.release(tail_ref.md());
}
continue;
}
if(atomic::compare_and_swap(&tail_ref.node_next(), node.next, new_tail)) {
break;
}
}
}
uint32_t deqImpl() {
for(;;) {
NodeRef head_ref(que_->head, alc_);
if(! head_ref) {
continue;
}
Node node = head_ref.node_copy();
if(node.next == Node::END) {
return 0;
}
if(atomic::compare_and_swap(&que_->head, head_ref.md(), node.next)) {
alc_.release(head_ref.md());
return node.next;
}
}
}
private:
const uint32_t shm_size_;
Header* que_;
allocator::FixedAllocator alc_;
};
}
}
#endif
<commit_msg>enqueue直後にtailの更新を試みるコードを追加(若干冗長だが性能は良くなる)<commit_after>#ifndef IMQUE_QUEUE_QUEUE_IMPL_HH
#define IMQUE_QUEUE_QUEUE_IMPL_HH
#include "../atomic/atomic.hh"
#include "../ipc/shared_memory.hh"
#include "../allocator/fixed_allocator.hh"
#include <inttypes.h>
#include <string.h>
#include <algorithm>
namespace imque {
namespace queue {
static const char MAGIC[] = "IMQUE-0.1.1";
// FIFOキュー
class QueueImpl {
struct Node {
uint32_t next;
uint32_t data_size;
char data[0];
static const uint32_t END = 0;
};
struct Header {
char magic[sizeof(MAGIC)];
uint32_t shm_size;
volatile uint32_t head; // NOTE: mdを保持。md自体がABA対策がなされているので、ここではそれ用のフィールドは不要。
volatile uint32_t tail;
uint32_t overflowed_count;
};
static const uint32_t HEADER_SIZE = sizeof(Header);
// 参照カウント周りの処理隠蔽用のクラス
class NodeRef {
public:
NodeRef(uint32_t md, allocator::FixedAllocator& alc)
: alc_(alc), md_(0) {
if(alc.dup(md)) { // 既に解放されている可能性もあるのでチェックする
md_ = md;
}
}
~NodeRef() {
if(md_) {
alc_.release(md_);
}
}
operator bool() const { return md_ != 0; }
Node node_copy() const { return atomic::fetch(alc_.ptr<Node>(md_)); }
uint32_t& node_next() { return alc_.ptr<Node>(md_)->next; }
uint32_t md() const { return md_; }
private:
allocator::FixedAllocator& alc_;
uint32_t md_;
};
public:
QueueImpl(ipc::SharedMemory& shm)
: shm_size_(shm.size()),
que_(shm.ptr<Header>()),
alc_(shm.ptr<void>(HEADER_SIZE), std::max(0, static_cast<int32_t>(shm.size() - HEADER_SIZE))) {
}
operator bool() const { return alc_ && que_; }
// 初期化メソッド。
// コンストラクタに渡した一つの shm につき、一回呼び出す必要がある。
void init() {
if(*this) {
alc_.init();
uint32_t sentinel = alc_.allocate(sizeof(Node));
if(sentinel == 0) {
que_ = NULL;
return;
}
memcpy(que_->magic, MAGIC, sizeof(MAGIC));
que_->shm_size = shm_size_;
alc_.ptr<Node>(sentinel)->next = Node::END;
que_->head = sentinel;
que_->tail = sentinel;
assert(alc_.dup(sentinel)); // head と tail の二箇所から参照されているので、参照カウントを一つ増やしておく
que_->overflowed_count = 0;
}
}
// 重複初期化チェック(簡易)付きの初期化メソッド。
// 共有メモリ用のファイルを使い回している場合は、二回目以降は明示的なinit()呼び出しを行った方が安全。
void init_once() {
if(*this && (memcmp(que_->magic, MAGIC, sizeof(MAGIC)) != 0 ||
shm_size_ != que_->shm_size)) {
init();
}
}
// キューに要素を追加する (キューに空きがない場合は false を返す)
bool enq(const void* data, size_t size) {
return enqv(&data, &size, 1);
}
// キューに要素を追加する (キューに空きがない場合は false を返す)
// datav および sizev は count 分のサイズを持ち、それらを全て結合したデータがキューには追加される
bool enqv(const void** datav, size_t* sizev, size_t count) {
size_t total_size = 0;
for(size_t i=0; i < count; i++) {
total_size += sizev[i];
}
uint32_t md = alc_.allocate(sizeof(Node) + total_size); // md = memory descriptor
if(md == 0) {
atomic::add(&que_->overflowed_count, 1);
return false;
}
Node* node = alc_.ptr<Node>(md);
node->next = Node::END;
node->data_size = total_size;
size_t offset = sizeof(Node);
for(size_t i=0; i < count; i++) {
memcpy(alc_.ptr<void>(md, offset), datav[i], sizev[i]);
offset += sizev[i];
}
enqImpl(md);
return true;
}
// キューから要素を取り出し buf に格納する (キューが空の場合は false を返す)
bool deq(std::string& buf) {
uint32_t md = deqImpl();
if(md == 0) {
return false;
}
Node* node = alc_.ptr<Node>(md);
buf.assign(node->data, node->data_size);
assert(alc_.release(md));
return true;
}
// キューが空かどうか
bool isEmpty() {
for(;;) {
NodeRef head_ref(que_->head, alc_);
if(! head_ref) {
continue;
}
return head_ref.node_copy().next == Node::END;
}
}
// キューへの要素追加に失敗した回数を返す
size_t overflowedCount() const { return que_->overflowed_count; }
size_t resetOverflowedCount() {
return atomic::fetch_and_clear(&que_->overflowed_count);
}
private:
void enqImpl(uint32_t new_tail) {
assert(alc_.dup(new_tail, 2)); // head と tail からの参照分を始めにカウントしておく
for(;;) {
NodeRef tail_ref(que_->tail, alc_);
if(! tail_ref) {
continue;
}
Node node = tail_ref.node_copy();
if(node.next != Node::END) {
// tail が末尾を指していないので、一つ前に進める
if(atomic::compare_and_swap(&que_->tail, tail_ref.md(), node.next)) {
alc_.release(tail_ref.md());
}
continue;
}
if(atomic::compare_and_swap(&tail_ref.node_next(), node.next, new_tail)) {
if(atomic::compare_and_swap(&que_->tail, tail_ref.md(), new_tail)) {
alc_.release(tail_ref.md());
}
break;
}
}
}
uint32_t deqImpl() {
for(;;) {
NodeRef head_ref(que_->head, alc_);
if(! head_ref) {
continue;
}
Node node = head_ref.node_copy();
if(node.next == Node::END) {
return 0;
}
if(atomic::compare_and_swap(&que_->head, head_ref.md(), node.next)) {
alc_.release(head_ref.md());
return node.next;
}
}
}
private:
const uint32_t shm_size_;
Header* que_;
allocator::FixedAllocator alc_;
};
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
#include "traits.hpp"
#include "meta_list.hpp"
#include "detection.hpp"
namespace kgr {
struct single {
single() = default;
~single() = default;
single(const single&) = delete;
single& operator=(const single&) = delete;
single(single&&) = default;
single& operator=(single&&) = default;
};
struct polymorphic {};
struct final {};
struct supplied {};
struct abstract : polymorphic, single {};
template<typename T>
struct defaults_to {
using default_service = T;
};
template<typename... Types>
struct overrides {
using parent_types = detail::meta_list<Types...>;
};
namespace detail {
template<typename, typename = void>
struct parent_type_helper {
using parent_types = meta_list<>;
};
template<typename T>
struct parent_type_helper<T, void_t<typename T::parent_types>> {
using parent_types = typename T::parent_types;
};
template<typename T>
using parent_types = typename parent_type_helper<T>::parent_types;
template<typename, typename = void>
struct default_type_helper {
using has_default = std::false_type;
};
template<typename T>
struct default_type_helper<T, void_t<typename T::default_service>> {
using has_default = std::true_type;
using service = typename T::default_service;
};
template<typename T>
using default_type = typename default_type_helper<T>::service;
template<typename T>
using has_default = typename default_type_helper<T>::has_default;
template<typename T>
using is_abstract_service = std::is_base_of<abstract, T>;
template<typename T>
using is_single = std::is_base_of<single, T>;
template<typename T>
using is_supplied_service = std::is_base_of<supplied, T>;
template<typename T>
using is_final_service = std::is_base_of<final, T>;
template<typename T>
using is_not_final_service = negation<is_final_service<T>>;
template<typename T>
using is_polymorphic = std::integral_constant<bool, std::is_base_of<polymorphic, T>::value || !meta_list_empty<parent_types<T>>::value>;
template<typename Service, typename Overrider>
using is_overriden_by = meta_list_contains<Service, parent_types<Overrider>>;
} // namespace detail
} // namespace kgr
#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
<commit_msg>use bool_constant<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
#include "traits.hpp"
#include "meta_list.hpp"
#include "detection.hpp"
namespace kgr {
struct single {
single() = default;
~single() = default;
single(const single&) = delete;
single& operator=(const single&) = delete;
single(single&&) = default;
single& operator=(single&&) = default;
};
struct polymorphic {};
struct final {};
struct supplied {};
struct abstract : polymorphic, single {};
template<typename T>
struct defaults_to {
using default_service = T;
};
template<typename... Types>
struct overrides {
using parent_types = detail::meta_list<Types...>;
};
namespace detail {
template<typename, typename = void>
struct parent_type_helper {
using parent_types = meta_list<>;
};
template<typename T>
struct parent_type_helper<T, void_t<typename T::parent_types>> {
using parent_types = typename T::parent_types;
};
template<typename T>
using parent_types = typename parent_type_helper<T>::parent_types;
template<typename, typename = void>
struct default_type_helper {
using has_default = std::false_type;
};
template<typename T>
struct default_type_helper<T, void_t<typename T::default_service>> {
using has_default = std::true_type;
using service = typename T::default_service;
};
template<typename T>
using default_type = typename default_type_helper<T>::service;
template<typename T>
using has_default = typename default_type_helper<T>::has_default;
template<typename T>
using is_abstract_service = std::is_base_of<abstract, T>;
template<typename T>
using is_single = std::is_base_of<single, T>;
template<typename T>
using is_supplied_service = std::is_base_of<supplied, T>;
template<typename T>
using is_final_service = std::is_base_of<final, T>;
template<typename T>
using is_not_final_service = negation<is_final_service<T>>;
template<typename T>
using is_polymorphic = bool_constant<std::is_base_of<polymorphic, T>::value || !meta_list_empty<parent_types<T>>::value>;
template<typename Service, typename Overrider>
using is_overriden_by = meta_list_contains<Service, parent_types<Overrider>>;
} // namespace detail
} // namespace kgr
#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_SINGLE_HPP
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006-2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED
#define TORRENT_EXTENSIONS_HPP_INCLUDED
#ifndef TORRENT_DISABLE_EXTENSIONS
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/weak_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <vector>
#include "libtorrent/config.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/socket.hpp"
namespace libtorrent
{
namespace aux { struct session_impl; }
struct peer_plugin;
class bt_peer_connection;
struct peer_request;
class peer_connection;
class entry;
struct lazy_entry;
struct disk_buffer_holder;
struct bitfield;
class alert;
struct torrent_plugin;
class torrent;
struct TORRENT_EXPORT plugin
{
virtual ~plugin() {}
virtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)
{ return boost::shared_ptr<torrent_plugin>(); }
// called when plugin is added to a session
virtual void added(boost::weak_ptr<aux::session_impl> s) {}
// called when an alert is posted
// alerts that are filtered are not
// posted
virtual void on_alert(alert const* a) {}
// called once per second
virtual void on_tick() {}
// called when saving settings state
virtual void save_state(entry& ent) const {}
// called when loading settings state
virtual void load_state(lazy_entry const& ent) {}
};
struct TORRENT_EXPORT torrent_plugin
{
virtual ~torrent_plugin() {}
// throwing an exception closes the connection
// returning a 0 pointer is valid and will not add
// the peer_plugin to the peer_connection
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)
{ return boost::shared_ptr<peer_plugin>(); }
virtual void on_piece_pass(int index) {}
virtual void on_piece_failed(int index) {}
// called aproximately once every second
virtual void tick() {}
// if true is returned, it means the handler handled the event,
// and no other plugins will have their handlers called, and the
// default behavior will be skipped
virtual bool on_pause() { return false; }
virtual bool on_resume() { return false; }
// this is called when the initial checking of
// files is completed.
virtual void on_files_checked() {}
// called when the torrent changes state
// the state is one of torrent_status::state_t
// enum members
virtual void on_state(int s) {}
// called every time policy::add_peer is called
// src is a bitmask of which sources this peer
// has been seen from. flags is a bitmask of:
enum flags_t {
// this is the first time we see this peer
first_time = 1,
// this peer was not added because it was
// filtered by the IP filter
filtered = 2
};
virtual void on_add_peer(tcp::endpoint const& ip
, int src, int flags) {}
};
struct TORRENT_EXPORT peer_plugin
{
virtual ~peer_plugin() {}
virtual char const* type() const { return ""; }
// can add entries to the extension handshake
// this is not called for web seeds
virtual void add_handshake(entry&) {}
// throwing an exception from any of the handlers (except add_handshake)
// closes the connection
// this is called when the initial BT handshake is received. Returning false
// means that the other end doesn't support this extension and will remove
// it from the list of plugins.
// this is not called for web seeds
virtual bool on_handshake(char const* reserved_bits) { return true; }
// called when the extension handshake from the other end is received
// if this returns false, it means that this extension isn't
// supported by this peer. It will result in this peer_plugin
// being removed from the peer_connection and destructed.
// this is not called for web seeds
virtual bool on_extension_handshake(lazy_entry const& h) { return true; }
// returning true from any of the message handlers
// indicates that the plugin has handeled the message.
// it will break the plugin chain traversing and not let
// anyone else handle the message, including the default
// handler.
virtual bool on_choke()
{ return false; }
virtual bool on_unchoke()
{ return false; }
virtual bool on_interested()
{ return false; }
virtual bool on_not_interested()
{ return false; }
virtual bool on_have(int index)
{ return false; }
virtual bool on_dont_have(int index)
{ return false; }
virtual bool on_bitfield(bitfield const& bitfield)
{ return false; }
virtual bool on_have_all()
{ return false; }
virtual bool on_have_none()
{ return false; }
virtual bool on_allowed_fast(int index)
{ return false; }
virtual bool on_request(peer_request const& req)
{ return false; }
virtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)
{ return false; }
virtual bool on_cancel(peer_request const& req)
{ return false; }
virtual bool on_reject(peer_request const& req)
{ return false; }
virtual bool on_suggest(int index)
{ return false; }
// called when an extended message is received. If returning true,
// the message is not processed by any other plugin and if false
// is returned the next plugin in the chain will receive it to
// be able to handle it
// this is not called for web seeds
virtual bool on_extended(int length
, int msg, buffer::const_interval body)
{ return false; }
// this is not called for web seeds
virtual bool on_unknown_message(int length, int msg
, buffer::const_interval body)
{ return false; }
// called when a piece that this peer participated in either
// fails or passes the hash_check
virtual void on_piece_pass(int index) {}
virtual void on_piece_failed(int index) {}
// called aproximately once every second
virtual void tick() {}
// called each time a request message is to be sent. If true
// is returned, the original request message won't be sent and
// no other plugin will have this function called.
virtual bool write_request(peer_request const& r) { return false; }
};
}
#endif
#endif // TORRENT_EXTENSIONS_HPP_INCLUDED
<commit_msg>fix some unused variables warnings in extension.hpp<commit_after>/*
Copyright (c) 2006-2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED
#define TORRENT_EXTENSIONS_HPP_INCLUDED
#ifndef TORRENT_DISABLE_EXTENSIONS
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/weak_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <vector>
#include "libtorrent/config.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/socket.hpp"
namespace libtorrent
{
namespace aux { struct session_impl; }
struct peer_plugin;
class bt_peer_connection;
struct peer_request;
class peer_connection;
class entry;
struct lazy_entry;
struct disk_buffer_holder;
struct bitfield;
class alert;
struct torrent_plugin;
class torrent;
struct TORRENT_EXPORT plugin
{
virtual ~plugin() {}
virtual boost::shared_ptr<torrent_plugin> new_torrent(torrent*, void*)
{ return boost::shared_ptr<torrent_plugin>(); }
// called when plugin is added to a session
virtual void added(boost::weak_ptr<aux::session_impl>) {}
// called when an alert is posted
// alerts that are filtered are not
// posted
virtual void on_alert(alert const*) {}
// called once per second
virtual void on_tick() {}
// called when saving settings state
virtual void save_state(entry&) const {}
// called when loading settings state
virtual void load_state(lazy_entry const&) {}
};
struct TORRENT_EXPORT torrent_plugin
{
virtual ~torrent_plugin() {}
// throwing an exception closes the connection
// returning a 0 pointer is valid and will not add
// the peer_plugin to the peer_connection
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)
{ return boost::shared_ptr<peer_plugin>(); }
virtual void on_piece_pass(int /*index*/) {}
virtual void on_piece_failed(int /*index*/) {}
// called aproximately once every second
virtual void tick() {}
// if true is returned, it means the handler handled the event,
// and no other plugins will have their handlers called, and the
// default behavior will be skipped
virtual bool on_pause() { return false; }
virtual bool on_resume() { return false; }
// this is called when the initial checking of
// files is completed.
virtual void on_files_checked() {}
// called when the torrent changes state
// the state is one of torrent_status::state_t
// enum members
virtual void on_state(int /*s*/) {}
// called every time policy::add_peer is called
// src is a bitmask of which sources this peer
// has been seen from. flags is a bitmask of:
enum flags_t {
// this is the first time we see this peer
first_time = 1,
// this peer was not added because it was
// filtered by the IP filter
filtered = 2
};
virtual void on_add_peer(tcp::endpoint const&,
int /*src*/, int /*flags*/) {}
};
struct TORRENT_EXPORT peer_plugin
{
virtual ~peer_plugin() {}
virtual char const* type() const { return ""; }
// can add entries to the extension handshake
// this is not called for web seeds
virtual void add_handshake(entry&) {}
// throwing an exception from any of the handlers (except add_handshake)
// closes the connection
// this is called when the initial BT handshake is received. Returning false
// means that the other end doesn't support this extension and will remove
// it from the list of plugins.
// this is not called for web seeds
virtual bool on_handshake(char const* /*reserved_bits*/) { return true; }
// called when the extension handshake from the other end is received
// if this returns false, it means that this extension isn't
// supported by this peer. It will result in this peer_plugin
// being removed from the peer_connection and destructed.
// this is not called for web seeds
virtual bool on_extension_handshake(lazy_entry const&) { return true; }
// returning true from any of the message handlers
// indicates that the plugin has handeled the message.
// it will break the plugin chain traversing and not let
// anyone else handle the message, including the default
// handler.
virtual bool on_choke()
{ return false; }
virtual bool on_unchoke()
{ return false; }
virtual bool on_interested()
{ return false; }
virtual bool on_not_interested()
{ return false; }
virtual bool on_have(int /*index*/)
{ return false; }
virtual bool on_dont_have(int /*index*/)
{ return false; }
virtual bool on_bitfield(bitfield const& /*bitfield*/)
{ return false; }
virtual bool on_have_all()
{ return false; }
virtual bool on_have_none()
{ return false; }
virtual bool on_allowed_fast(int /*index*/)
{ return false; }
virtual bool on_request(peer_request const&)
{ return false; }
virtual bool on_piece(peer_request const& /*piece*/, disk_buffer_holder& /*data*/)
{ return false; }
virtual bool on_cancel(peer_request const&)
{ return false; }
virtual bool on_reject(peer_request const&)
{ return false; }
virtual bool on_suggest(int /*index*/)
{ return false; }
// called when an extended message is received. If returning true,
// the message is not processed by any other plugin and if false
// is returned the next plugin in the chain will receive it to
// be able to handle it
// this is not called for web seeds
virtual bool on_extended(int /*length*/, int /*msg*/,
buffer::const_interval /*body*/)
{ return false; }
// this is not called for web seeds
virtual bool on_unknown_message(int /*length*/, int /*msg*/,
buffer::const_interval /*body*/)
{ return false; }
// called when a piece that this peer participated in either
// fails or passes the hash_check
virtual void on_piece_pass(int /*index*/) {}
virtual void on_piece_failed(int /*index*/) {}
// called aproximately once every second
virtual void tick() {}
// called each time a request message is to be sent. If true
// is returned, the original request message won't be sent and
// no other plugin will have this function called.
virtual bool write_request(peer_request const&) { return false; }
};
}
#endif
#endif // TORRENT_EXTENSIONS_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED
#define TORRENT_UDP_SOCKET_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/deadline_timer.hpp"
#include <vector>
#include <boost/function/function4.hpp>
namespace libtorrent
{
class connection_queue;
class udp_socket
{
public:
typedef boost::function<void(error_code const& ec
, udp::endpoint const&, char const* buf, int size)> callback_t;
udp_socket(io_service& ios, callback_t const& c, connection_queue& cc);
~udp_socket();
bool is_open() const
{
return m_ipv4_sock.is_open()
#if TORRENT_USE_IPV6
|| m_ipv6_sock.is_open()
#endif
;
}
io_service& get_io_service() { return m_ipv4_sock.get_io_service(); }
void send(udp::endpoint const& ep, char const* p, int len, error_code& ec);
void bind(udp::endpoint const& ep, error_code& ec);
void bind(int port);
void close();
int local_port() const { return m_bind_port; }
void set_proxy_settings(proxy_settings const& ps);
proxy_settings const& get_proxy_settings() { return m_proxy_settings; }
bool is_closed() const { return m_abort; }
tcp::endpoint local_endpoint() const
{
udp::endpoint ep = m_ipv4_sock.local_endpoint();
return tcp::endpoint(ep.address(), ep.port());
}
protected:
struct queued_packet
{
udp::endpoint ep;
buffer buf;
};
private:
callback_t m_callback;
void on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred);
void on_name_lookup(error_code const& e, tcp::resolver::iterator i);
void on_timeout();
void on_connect(int ticket);
void on_connected(error_code const& ec);
void handshake1(error_code const& e);
void handshake2(error_code const& e);
void handshake3(error_code const& e);
void handshake4(error_code const& e);
void socks_forward_udp(mutex::scoped_lock& l);
void connect1(error_code const& e);
void connect2(error_code const& e);
void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);
void unwrap(error_code const& e, char const* buf, int size);
mutable mutex m_mutex;
udp::socket m_ipv4_sock;
udp::endpoint m_v4_ep;
char m_v4_buf[1600];
#if TORRENT_USE_IPV6
udp::socket m_ipv6_sock;
udp::endpoint m_v6_ep;
char m_v6_buf[1600];
#endif
int m_bind_port;
char m_outstanding;
tcp::socket m_socks5_sock;
int m_connection_ticket;
proxy_settings m_proxy_settings;
connection_queue& m_cc;
tcp::resolver m_resolver;
char m_tmp_buf[100];
bool m_queue_packets;
bool m_tunnel_packets;
bool m_abort;
udp::endpoint m_proxy_addr;
// while we're connecting to the proxy
// we have to queue the packets, we'll flush
// them once we're connected
std::list<queued_packet> m_queue;
#ifdef TORRENT_DEBUG
bool m_started;
int m_magic;
int m_outstanding_when_aborted;
#endif
};
struct rate_limited_udp_socket : public udp_socket
{
rate_limited_udp_socket(io_service& ios, callback_t const& c, connection_queue& cc);
void set_rate_limit(int limit) { m_rate_limit = limit; }
bool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; }
bool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);
void close();
private:
void on_tick(error_code const& e);
deadline_timer m_timer;
int m_queue_size_limit;
int m_rate_limit;
int m_quota;
ptime m_last_tick;
std::list<queued_packet> m_queue;
};
}
#endif
<commit_msg>ignore failures in when asking for local_endpoint<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED
#define TORRENT_UDP_SOCKET_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/deadline_timer.hpp"
#include <vector>
#include <boost/function/function4.hpp>
namespace libtorrent
{
class connection_queue;
class udp_socket
{
public:
typedef boost::function<void(error_code const& ec
, udp::endpoint const&, char const* buf, int size)> callback_t;
udp_socket(io_service& ios, callback_t const& c, connection_queue& cc);
~udp_socket();
bool is_open() const
{
return m_ipv4_sock.is_open()
#if TORRENT_USE_IPV6
|| m_ipv6_sock.is_open()
#endif
;
}
io_service& get_io_service() { return m_ipv4_sock.get_io_service(); }
void send(udp::endpoint const& ep, char const* p, int len, error_code& ec);
void bind(udp::endpoint const& ep, error_code& ec);
void bind(int port);
void close();
int local_port() const { return m_bind_port; }
void set_proxy_settings(proxy_settings const& ps);
proxy_settings const& get_proxy_settings() { return m_proxy_settings; }
bool is_closed() const { return m_abort; }
tcp::endpoint local_endpoint() const
{
error_code ec;
udp::endpoint ep = m_ipv4_sock.local_endpoint(ec);
return tcp::endpoint(ep.address(), ep.port());
}
protected:
struct queued_packet
{
udp::endpoint ep;
buffer buf;
};
private:
callback_t m_callback;
void on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred);
void on_name_lookup(error_code const& e, tcp::resolver::iterator i);
void on_timeout();
void on_connect(int ticket);
void on_connected(error_code const& ec);
void handshake1(error_code const& e);
void handshake2(error_code const& e);
void handshake3(error_code const& e);
void handshake4(error_code const& e);
void socks_forward_udp(mutex::scoped_lock& l);
void connect1(error_code const& e);
void connect2(error_code const& e);
void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);
void unwrap(error_code const& e, char const* buf, int size);
mutable mutex m_mutex;
udp::socket m_ipv4_sock;
udp::endpoint m_v4_ep;
char m_v4_buf[1600];
#if TORRENT_USE_IPV6
udp::socket m_ipv6_sock;
udp::endpoint m_v6_ep;
char m_v6_buf[1600];
#endif
int m_bind_port;
char m_outstanding;
tcp::socket m_socks5_sock;
int m_connection_ticket;
proxy_settings m_proxy_settings;
connection_queue& m_cc;
tcp::resolver m_resolver;
char m_tmp_buf[100];
bool m_queue_packets;
bool m_tunnel_packets;
bool m_abort;
udp::endpoint m_proxy_addr;
// while we're connecting to the proxy
// we have to queue the packets, we'll flush
// them once we're connected
std::list<queued_packet> m_queue;
#ifdef TORRENT_DEBUG
bool m_started;
int m_magic;
int m_outstanding_when_aborted;
#endif
};
struct rate_limited_udp_socket : public udp_socket
{
rate_limited_udp_socket(io_service& ios, callback_t const& c, connection_queue& cc);
void set_rate_limit(int limit) { m_rate_limit = limit; }
bool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; }
bool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);
void close();
private:
void on_tick(error_code const& e);
deadline_timer m_timer;
int m_queue_size_limit;
int m_rate_limit;
int m_quota;
ptime m_last_tick;
std::list<queued_packet> m_queue;
};
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED
#define TORRENT_UDP_SOCKET_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include "libtorrent/session_settings.hpp"
#include <vector>
#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
namespace libtorrent
{
class connection_queue;
class udp_socket
{
public:
typedef boost::function<void(error_code const& ec
, udp::endpoint const&, char const* buf, int size)> callback_t;
udp_socket(io_service& ios, callback_t const& c, connection_queue& cc);
bool is_open() const { return m_ipv4_sock.is_open() || m_ipv6_sock.is_open(); }
io_service& get_io_service() { return m_ipv4_sock.get_io_service(); }
void send(udp::endpoint const& ep, char const* p, int len, error_code& ec);
void bind(udp::endpoint const& ep, error_code& ec);
void bind(int port);
void close();
int local_port() const { return m_bind_port; }
void set_proxy_settings(proxy_settings const& ps);
proxy_settings const& get_proxy_settings() { return m_proxy_settings; }
#ifndef NDEBUG
~udp_socket() { m_magic = 0; }
#endif
private:
callback_t m_callback;
void on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred);
void on_name_lookup(error_code const& e, tcp::resolver::iterator i);
void on_timeout();
void on_connect(int ticket);
void on_connected(error_code const& ec);
void handshake1(error_code const& e);
void handshake2(error_code const& e);
void handshake3(error_code const& e);
void handshake4(error_code const& e);
void socks_forward_udp();
void connect1(error_code const& e);
void connect2(error_code const& e);
void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);
void unwrap(error_code const& e, char const* buf, int size);
typedef boost::mutex mutex_t;
mutable mutex_t m_mutex;
udp::socket m_ipv4_sock;
udp::socket m_ipv6_sock;
udp::endpoint m_v4_ep;
udp::endpoint m_v6_ep;
char m_v4_buf[1600];
char m_v6_buf[1600];
int m_bind_port;
uint8_t m_outstanding;
tcp::socket m_socks5_sock;
int m_connection_ticket;
proxy_settings m_proxy_settings;
connection_queue& m_cc;
tcp::resolver m_resolver;
char m_tmp_buf[100];
bool m_tunnel_packets;
udp::endpoint m_proxy_addr;
#ifndef NDEBUG
int m_magic;
#endif
};
}
#endif
<commit_msg>portability fix for udp_socket<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED
#define TORRENT_UDP_SOCKET_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include "libtorrent/session_settings.hpp"
#include <vector>
#include <boost/function.hpp>
#include <boost/thread/mutex.hpp>
namespace libtorrent
{
class connection_queue;
class udp_socket
{
public:
typedef boost::function<void(error_code const& ec
, udp::endpoint const&, char const* buf, int size)> callback_t;
udp_socket(io_service& ios, callback_t const& c, connection_queue& cc);
bool is_open() const { return m_ipv4_sock.is_open() || m_ipv6_sock.is_open(); }
io_service& get_io_service() { return m_ipv4_sock.get_io_service(); }
void send(udp::endpoint const& ep, char const* p, int len, error_code& ec);
void bind(udp::endpoint const& ep, error_code& ec);
void bind(int port);
void close();
int local_port() const { return m_bind_port; }
void set_proxy_settings(proxy_settings const& ps);
proxy_settings const& get_proxy_settings() { return m_proxy_settings; }
#ifndef NDEBUG
~udp_socket() { m_magic = 0; }
#endif
private:
callback_t m_callback;
void on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred);
void on_name_lookup(error_code const& e, tcp::resolver::iterator i);
void on_timeout();
void on_connect(int ticket);
void on_connected(error_code const& ec);
void handshake1(error_code const& e);
void handshake2(error_code const& e);
void handshake3(error_code const& e);
void handshake4(error_code const& e);
void socks_forward_udp();
void connect1(error_code const& e);
void connect2(error_code const& e);
void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);
void unwrap(error_code const& e, char const* buf, int size);
typedef boost::mutex mutex_t;
mutable mutex_t m_mutex;
udp::socket m_ipv4_sock;
udp::socket m_ipv6_sock;
udp::endpoint m_v4_ep;
udp::endpoint m_v6_ep;
char m_v4_buf[1600];
char m_v6_buf[1600];
int m_bind_port;
char m_outstanding;
tcp::socket m_socks5_sock;
int m_connection_ticket;
proxy_settings m_proxy_settings;
connection_queue& m_cc;
tcp::resolver m_resolver;
char m_tmp_buf[100];
bool m_tunnel_packets;
udp::endpoint m_proxy_addr;
#ifndef NDEBUG
int m_magic;
#endif
};
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UTP_STREAM_HPP_INCLUDED
#define TORRENT_UTP_STREAM_HPP_INCLUDED
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/proxy_base.hpp"
#include "libtorrent/udp_socket.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/packet_buffer.hpp"
#include "libtorrent/error_code.hpp"
#include <boost/bind.hpp>
#include <boost/function/function1.hpp>
#include <boost/function/function2.hpp>
#define CCONTROL_TARGET 100
namespace libtorrent
{
struct utp_socket_manager;
// the point of the bif_endian_int is two-fold
// one purpuse is to not have any alignment requirements
// so that any byffer received from the network can be cast
// to it and read as an integer of various sizes without
// triggering a bus error. The other purpose is to convert
// from network byte order to host byte order when read and
// written, to offer a convenient interface to both interpreting
// and writing network packets
template <class T> struct big_endian_int
{
big_endian_int& operator=(T v)
{
char* p = m_storage;
detail::write_impl(v, p);
return *this;
}
operator T() const
{
const char* p = m_storage;
return detail::read_impl(p, detail::type<T>());
}
private:
char m_storage[sizeof(T)];
};
typedef big_endian_int<boost::uint64_t> be_uint64;
typedef big_endian_int<boost::uint32_t> be_uint32;
typedef big_endian_int<boost::uint16_t> be_uint16;
typedef big_endian_int<boost::int64_t> be_int64;
typedef big_endian_int<boost::int32_t> be_int32;
typedef big_endian_int<boost::int16_t> be_int16;
/*
uTP header from BEP 29
0 4 8 16 24 32
+-------+-------+---------------+---------------+---------------+
| ver | type | extension | connection_id |
+-------+-------+---------------+---------------+---------------+
| timestamp_microseconds |
+---------------+---------------+---------------+---------------+
| timestamp_difference_microseconds |
+---------------+---------------+---------------+---------------+
| wnd_size |
+---------------+---------------+---------------+---------------+
| seq_nr | ack_nr |
+---------------+---------------+---------------+---------------+
*/
enum type { ST_DATA = 0, ST_FIN, ST_STATE, ST_RESET, ST_SYN, NUM_TYPES };
struct utp_header
{
unsigned char ver:4;
unsigned char type:4;
unsigned char extension;
be_uint16 connection_id;
be_uint32 timestamp_microseconds;
be_uint32 timestamp_difference_microseconds;
be_uint32 wnd_size;
be_uint16 seq_nr;
be_uint16 ack_nr;
};
struct utp_socket_impl;
utp_socket_impl* construct_utp_impl(boost::uint16_t recv_id
, boost::uint16_t send_id, void* userdata
, utp_socket_manager* sm);
void detach_utp_impl(utp_socket_impl* s);
void delete_utp_impl(utp_socket_impl* s);
bool should_delete(utp_socket_impl* s);
void tick_utp_impl(utp_socket_impl* s, ptime const& now);
bool utp_incoming_packet(utp_socket_impl* s, char const* p
, int size, udp::endpoint const& ep, ptime receive_time);
bool utp_match(utp_socket_impl* s, udp::endpoint const& ep, boost::uint16_t id);
udp::endpoint utp_remote_endpoint(utp_socket_impl* s);
boost::uint16_t utp_receive_id(utp_socket_impl* s);
int utp_socket_state(utp_socket_impl const* s);
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
int socket_impl_size();
#endif
// this is the user-level stream interface to utp sockets.
// the reason why it's split up in a utp_stream class and
// an implementation class is because the socket state has
// to be able to out-live the user level socket. For instance
// when sending data on a stream and then closing it, the
// state holding the send buffer has to be kept around until
// it has been flushed, which may be longer than the client
// will keep the utp_stream object around for.
// for more details, see utp_socket_impl, which is analogous
// to the kernel state for a socket. It's defined in utp_stream.cpp
class utp_stream
{
public:
typedef stream_socket::endpoint_type endpoint_type;
typedef stream_socket::protocol_type protocol_type;
explicit utp_stream(asio::io_service& io_service);
~utp_stream();
// used for incoming connections
void set_impl(utp_socket_impl* s);
utp_socket_impl* get_impl();
#ifndef BOOST_NO_EXCEPTIONS
template <class IO_Control_Command>
void io_control(IO_Control_Command& ioc) {}
#endif
template <class IO_Control_Command>
void io_control(IO_Control_Command& ioc, error_code& ec) {}
#ifndef BOOST_NO_EXCEPTIONS
void bind(endpoint_type const& endpoint) {}
#endif
void bind(endpoint_type const& endpoint, error_code& ec);
#ifndef BOOST_NO_EXCEPTIONS
template <class SettableSocketOption>
void set_option(SettableSocketOption const& opt) {}
#endif
template <class SettableSocketOption>
error_code set_option(SettableSocketOption const& opt, error_code& ec) { return ec; }
void close();
void close(error_code const& ec) { close(); }
bool is_open() const { return m_open; }
int read_buffer_size() const;
static void on_read(void* self, size_t bytes_transferred, error_code const& ec, bool kill);
static void on_write(void* self, size_t bytes_transferred, error_code const& ec, bool kill);
static void on_connect(void* self, error_code const& ec, bool kill);
typedef void(*handler_t)(void*, size_t, error_code const&, bool);
typedef void(*connect_handler_t)(void*, error_code const&, bool);
void add_read_buffer(void* buf, size_t len);
void set_read_handler(handler_t h);
void add_write_buffer(void const* buf, size_t len);
void set_write_handler(handler_t h);
size_t read_some(bool clear_buffers);
void do_connect(tcp::endpoint const& ep, connect_handler_t h);
endpoint_type local_endpoint() const
{
error_code ec;
return local_endpoint(ec);
}
endpoint_type local_endpoint(error_code& ec) const;
endpoint_type remote_endpoint() const
{
error_code ec;
return remote_endpoint(ec);
}
endpoint_type remote_endpoint(error_code& ec) const;
std::size_t available() const;
std::size_t available(error_code& ec) const { return available(); }
asio::io_service& io_service()
{ return m_io_service; }
template <class Handler>
void async_connect(endpoint_type const& endpoint, Handler const& handler)
{
if (!endpoint.address().is_v4())
{
error_code ec = asio::error::operation_not_supported;
m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));
return;
}
if (m_impl == 0)
{
m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));
return;
}
m_connect_handler = handler;
do_connect(endpoint, &utp_stream::on_connect);
}
template <class Mutable_Buffers, class Handler>
void async_read_some(Mutable_Buffers const& buffers, Handler const& handler)
{
if (m_impl == 0)
{
m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));
return;
}
TORRENT_ASSERT(!m_read_handler);
if (m_read_handler)
{
m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));
return;
}
for (typename Mutable_Buffers::const_iterator i = buffers.begin()
, end(buffers.end()); i != end; ++i)
{
using asio::buffer_cast;
using asio::buffer_size;
add_read_buffer(buffer_cast<void*>(*i), buffer_size(*i));
}
m_read_handler = handler;
set_read_handler(&utp_stream::on_read);
}
void do_async_connect(endpoint_type const& ep
, boost::function<void(error_code const&)> const& handler);
template <class Protocol>
void open(Protocol const& p, error_code& ec)
{ m_open = true; }
template <class Protocol>
void open(Protocol const& p)
{ m_open = true; }
template <class Mutable_Buffers>
std::size_t read_some(Mutable_Buffers const& buffers, error_code& ec)
{
TORRENT_ASSERT(!m_read_handler);
if (m_impl == 0)
{
ec = asio::error::not_connected;
return 0;
}
if (read_buffer_size() == 0)
{
ec = asio::error::would_block;
return 0;
}
#ifndef NDEBUG
int buf_size = 0;
#endif
for (typename Mutable_Buffers::const_iterator i = buffers.begin()
, end(buffers.end()); i != end; ++i)
{
using asio::buffer_cast;
using asio::buffer_size;
add_read_buffer(buffer_cast<void*>(*i), buffer_size(*i));
#ifndef NDEBUG
buf_size += buffer_size(*i);
#endif
}
std::size_t ret = read_some(true);
TORRENT_ASSERT(ret <= buf_size);
return ret;
}
template <class Const_Buffers>
std::size_t write_some(Const_Buffers const& buffers, error_code& ec)
{
// TODO: implement
return 0;
}
template <class Const_Buffers, class Handler>
void async_write_some(Const_Buffers const& buffers, Handler const& handler)
{
if (m_impl == 0)
{
m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));
return;
}
TORRENT_ASSERT(!m_write_handler);
if (m_write_handler)
{
m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));
return;
}
for (typename Const_Buffers::const_iterator i = buffers.begin()
, end(buffers.end()); i != end; ++i)
{
using asio::buffer_cast;
using asio::buffer_size;
add_write_buffer((void*)buffer_cast<void const*>(*i), buffer_size(*i));
}
m_write_handler = handler;
set_write_handler(&utp_stream::on_write);
}
//private:
void cancel_handlers(error_code const&);
boost::function1<void, error_code const&> m_connect_handler;
boost::function2<void, error_code const&, std::size_t> m_read_handler;
boost::function2<void, error_code const&, std::size_t> m_write_handler;
asio::io_service& m_io_service;
utp_socket_impl* m_impl;
bool m_open;
};
}
#endif
<commit_msg>fixed minor utp typo<commit_after>/*
Copyright (c) 2009, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UTP_STREAM_HPP_INCLUDED
#define TORRENT_UTP_STREAM_HPP_INCLUDED
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/proxy_base.hpp"
#include "libtorrent/udp_socket.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/packet_buffer.hpp"
#include "libtorrent/error_code.hpp"
#include <boost/bind.hpp>
#include <boost/function/function1.hpp>
#include <boost/function/function2.hpp>
#define CCONTROL_TARGET 100
namespace libtorrent
{
struct utp_socket_manager;
// the point of the bif_endian_int is two-fold
// one purpuse is to not have any alignment requirements
// so that any byffer received from the network can be cast
// to it and read as an integer of various sizes without
// triggering a bus error. The other purpose is to convert
// from network byte order to host byte order when read and
// written, to offer a convenient interface to both interpreting
// and writing network packets
template <class T> struct big_endian_int
{
big_endian_int& operator=(T v)
{
char* p = m_storage;
detail::write_impl(v, p);
return *this;
}
operator T() const
{
const char* p = m_storage;
return detail::read_impl(p, detail::type<T>());
}
private:
char m_storage[sizeof(T)];
};
typedef big_endian_int<boost::uint64_t> be_uint64;
typedef big_endian_int<boost::uint32_t> be_uint32;
typedef big_endian_int<boost::uint16_t> be_uint16;
typedef big_endian_int<boost::int64_t> be_int64;
typedef big_endian_int<boost::int32_t> be_int32;
typedef big_endian_int<boost::int16_t> be_int16;
/*
uTP header from BEP 29
0 4 8 16 24 32
+-------+-------+---------------+---------------+---------------+
| ver | type | extension | connection_id |
+-------+-------+---------------+---------------+---------------+
| timestamp_microseconds |
+---------------+---------------+---------------+---------------+
| timestamp_difference_microseconds |
+---------------+---------------+---------------+---------------+
| wnd_size |
+---------------+---------------+---------------+---------------+
| seq_nr | ack_nr |
+---------------+---------------+---------------+---------------+
*/
enum type { ST_DATA = 0, ST_FIN, ST_STATE, ST_RESET, ST_SYN, NUM_TYPES };
struct utp_header
{
unsigned char ver:4;
unsigned char type:4;
unsigned char extension;
be_uint16 connection_id;
be_uint32 timestamp_microseconds;
be_uint32 timestamp_difference_microseconds;
be_uint32 wnd_size;
be_uint16 seq_nr;
be_uint16 ack_nr;
};
struct utp_socket_impl;
utp_socket_impl* construct_utp_impl(boost::uint16_t recv_id
, boost::uint16_t send_id, void* userdata
, utp_socket_manager* sm);
void detach_utp_impl(utp_socket_impl* s);
void delete_utp_impl(utp_socket_impl* s);
bool should_delete(utp_socket_impl* s);
void tick_utp_impl(utp_socket_impl* s, ptime const& now);
bool utp_incoming_packet(utp_socket_impl* s, char const* p
, int size, udp::endpoint const& ep, ptime receive_time);
bool utp_match(utp_socket_impl* s, udp::endpoint const& ep, boost::uint16_t id);
udp::endpoint utp_remote_endpoint(utp_socket_impl* s);
boost::uint16_t utp_receive_id(utp_socket_impl* s);
int utp_socket_state(utp_socket_impl const* s);
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
int socket_impl_size();
#endif
// this is the user-level stream interface to utp sockets.
// the reason why it's split up in a utp_stream class and
// an implementation class is because the socket state has
// to be able to out-live the user level socket. For instance
// when sending data on a stream and then closing it, the
// state holding the send buffer has to be kept around until
// it has been flushed, which may be longer than the client
// will keep the utp_stream object around for.
// for more details, see utp_socket_impl, which is analogous
// to the kernel state for a socket. It's defined in utp_stream.cpp
class utp_stream
{
public:
typedef stream_socket::endpoint_type endpoint_type;
typedef stream_socket::protocol_type protocol_type;
explicit utp_stream(asio::io_service& io_service);
~utp_stream();
// used for incoming connections
void set_impl(utp_socket_impl* s);
utp_socket_impl* get_impl();
#ifndef BOOST_NO_EXCEPTIONS
template <class IO_Control_Command>
void io_control(IO_Control_Command& ioc) {}
#endif
template <class IO_Control_Command>
void io_control(IO_Control_Command& ioc, error_code& ec) {}
#ifndef BOOST_NO_EXCEPTIONS
void bind(endpoint_type const& endpoint) {}
#endif
void bind(endpoint_type const& endpoint, error_code& ec);
#ifndef BOOST_NO_EXCEPTIONS
template <class SettableSocketOption>
void set_option(SettableSocketOption const& opt) {}
#endif
template <class SettableSocketOption>
error_code set_option(SettableSocketOption const& opt, error_code& ec) { return ec; }
void close();
void close(error_code const& ec) { close(); }
bool is_open() const { return m_open; }
int read_buffer_size() const;
static void on_read(void* self, size_t bytes_transferred, error_code const& ec, bool kill);
static void on_write(void* self, size_t bytes_transferred, error_code const& ec, bool kill);
static void on_connect(void* self, error_code const& ec, bool kill);
typedef void(*handler_t)(void*, size_t, error_code const&, bool);
typedef void(*connect_handler_t)(void*, error_code const&, bool);
void add_read_buffer(void* buf, size_t len);
void set_read_handler(handler_t h);
void add_write_buffer(void const* buf, size_t len);
void set_write_handler(handler_t h);
size_t read_some(bool clear_buffers);
void do_connect(tcp::endpoint const& ep, connect_handler_t h);
endpoint_type local_endpoint() const
{
error_code ec;
return local_endpoint(ec);
}
endpoint_type local_endpoint(error_code& ec) const;
endpoint_type remote_endpoint() const
{
error_code ec;
return remote_endpoint(ec);
}
endpoint_type remote_endpoint(error_code& ec) const;
std::size_t available() const;
std::size_t available(error_code& ec) const { return available(); }
asio::io_service& io_service()
{ return m_io_service; }
template <class Handler>
void async_connect(endpoint_type const& endpoint, Handler const& handler)
{
if (!endpoint.address().is_v4())
{
error_code ec = asio::error::operation_not_supported;
m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));
return;
}
if (m_impl == 0)
{
m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));
return;
}
m_connect_handler = handler;
do_connect(endpoint, &utp_stream::on_connect);
}
template <class Mutable_Buffers, class Handler>
void async_read_some(Mutable_Buffers const& buffers, Handler const& handler)
{
if (m_impl == 0)
{
m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));
return;
}
TORRENT_ASSERT(!m_read_handler);
if (m_read_handler)
{
m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));
return;
}
for (typename Mutable_Buffers::const_iterator i = buffers.begin()
, end(buffers.end()); i != end; ++i)
{
using asio::buffer_cast;
using asio::buffer_size;
add_read_buffer(buffer_cast<void*>(*i), buffer_size(*i));
}
m_read_handler = handler;
set_read_handler(&utp_stream::on_read);
}
void do_async_connect(endpoint_type const& ep
, boost::function<void(error_code const&)> const& handler);
template <class Protocol>
void open(Protocol const& p, error_code& ec)
{ m_open = true; }
template <class Protocol>
void open(Protocol const& p)
{ m_open = true; }
template <class Mutable_Buffers>
std::size_t read_some(Mutable_Buffers const& buffers, error_code& ec)
{
TORRENT_ASSERT(!m_read_handler);
if (m_impl == 0)
{
ec = asio::error::not_connected;
return 0;
}
if (read_buffer_size() == 0)
{
ec = asio::error::would_block;
return 0;
}
#ifdef TORRENT_DEBUG
int buf_size = 0;
#endif
for (typename Mutable_Buffers::const_iterator i = buffers.begin()
, end(buffers.end()); i != end; ++i)
{
using asio::buffer_cast;
using asio::buffer_size;
add_read_buffer(buffer_cast<void*>(*i), buffer_size(*i));
#ifdef TORRENT_DEBUG
buf_size += buffer_size(*i);
#endif
}
std::size_t ret = read_some(true);
TORRENT_ASSERT(ret <= buf_size);
return ret;
}
template <class Const_Buffers>
std::size_t write_some(Const_Buffers const& buffers, error_code& ec)
{
// TODO: implement
return 0;
}
template <class Const_Buffers, class Handler>
void async_write_some(Const_Buffers const& buffers, Handler const& handler)
{
if (m_impl == 0)
{
m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0));
return;
}
TORRENT_ASSERT(!m_write_handler);
if (m_write_handler)
{
m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0));
return;
}
for (typename Const_Buffers::const_iterator i = buffers.begin()
, end(buffers.end()); i != end; ++i)
{
using asio::buffer_cast;
using asio::buffer_size;
add_write_buffer((void*)buffer_cast<void const*>(*i), buffer_size(*i));
}
m_write_handler = handler;
set_write_handler(&utp_stream::on_write);
}
//private:
void cancel_handlers(error_code const&);
boost::function1<void, error_code const&> m_connect_handler;
boost::function2<void, error_code const&, std::size_t> m_read_handler;
boost::function2<void, error_code const&, std::size_t> m_write_handler;
asio::io_service& m_io_service;
utp_socket_impl* m_impl;
bool m_open;
};
}
#endif
<|endoftext|> |
<commit_before>///
/// @file pod_vector.hpp
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef POD_VECTOR_HPP
#define POD_VECTOR_HPP
#include "macros.hpp"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <stdint.h>
#include <type_traits>
#include <utility>
namespace primesieve {
/// pod_vector is a dynamically growing array.
/// It has the same API (though not complete) as std::vector but its
/// resize() method does not default initialize memory for built-in
/// integer types. It does however default initialize classes and
/// struct types if they have a constructor. It also prevents
/// bounds checks which is important for primesieve's performance, e.g.
/// the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS
/// which enables std::vector bounds checks.
///
template <typename T,
typename Allocator = std::allocator<T>>
class pod_vector
{
public:
// The default C++ std::allocator is stateless. We use this
// allocator and do not support other statefull allocators,
// which simplifies our implementation.
//
// "The default allocator is stateless, that is, all instances
// of the given allocator are interchangeable, compare equal
// and can deallocate memory allocated by any other instance
// of the same allocator type."
// https://en.cppreference.com/w/cpp/memory/allocator
//
// "The member type is_always_equal of std::allocator_traits
// is intendedly used for determining whether an allocator
// type is stateless."
// https://en.cppreference.com/w/cpp/named_req/Allocator
static_assert(std::allocator_traits<Allocator>::is_always_equal::value,
"pod_vector<T> only supports stateless allocators!");
using value_type = T;
pod_vector() noexcept = default;
pod_vector(std::size_t size)
{
resize(size);
}
~pod_vector()
{
destroy(array_, end_);
Allocator().deallocate(array_, capacity());
}
/// Free all memory, the pod_vector
/// can be reused afterwards.
void deallocate() noexcept
{
this->~pod_vector<T>();
array_ = nullptr;
end_ = nullptr;
capacity_ = nullptr;
}
/// Reset the pod_vector, but do not free its
/// memory. Same as std::vector.clear().
void clear() noexcept
{
destroy(array_, end_);
end_ = array_;
}
/// Copying is slow, we prevent it
pod_vector(const pod_vector&) = delete;
pod_vector& operator=(const pod_vector&) = delete;
/// Move constructor
pod_vector(pod_vector&& other) noexcept
{
swap(other);
}
/// Move assignment operator
pod_vector& operator=(pod_vector&& other) noexcept
{
if (this != &other)
swap(other);
return *this;
}
/// Better assembly than: std::swap(vect1, vect2)
void swap(pod_vector& other) noexcept
{
T* tmp_array = array_;
T* tmp_end = end_;
T* tmp_capacity = capacity_;
array_ = other.array_;
end_ = other.end_;
capacity_ = other.capacity_;
other.array_ = tmp_array;
other.end_ = tmp_end;
other.capacity_ = tmp_capacity;
}
bool empty() const noexcept
{
return array_ == end_;
}
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
T* data() noexcept
{
return array_;
}
const T* data() const noexcept
{
return array_;
}
std::size_t size() const noexcept
{
ASSERT(end_ >= array_);
return (std::size_t)(end_ - array_);
}
std::size_t capacity() const noexcept
{
ASSERT(capacity_ >= array_);
return (std::size_t)(capacity_ - array_);
}
T* begin() noexcept
{
return array_;
}
const T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return end_;
}
const T* end() const noexcept
{
return end_;
}
T& front() noexcept
{
ASSERT(!empty());
return *array_;
}
const T& front() const noexcept
{
ASSERT(!empty());
return *array_;
}
T& back() noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
const T& back() const noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
ALWAYS_INLINE void push_back(const T& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Placement new
new(end_) T(value);
end_++;
}
ALWAYS_INLINE void push_back(T&& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Without std::move() the copy constructor will
// be called instead of the move constructor.
new(end_) T(std::move(value));
end_++;
}
template <class... Args>
ALWAYS_INLINE void emplace_back(Args&&... args)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Placement new
new(end_) T(std::forward<Args>(args)...);
end_++;
}
template <class InputIt>
void insert(T* const pos, InputIt first, InputIt last)
{
static_assert(std::is_trivially_copyable<T>::value,
"pod_vector<T>::insert() supports only trivially copyable types!");
// We only support appending to the vector
ASSERT(pos == end_);
(void) pos;
if (first < last)
{
std::size_t new_size = size() + (std::size_t) (last - first);
reserve(new_size);
std::uninitialized_copy(first, last, end_);
end_ = array_ + new_size;
}
}
void reserve(std::size_t n)
{
if (n > capacity())
reserve_unchecked(n);
}
void resize(std::size_t n)
{
if (n > size())
{
if (n > capacity())
reserve_unchecked(n);
// This default initializes memory of classes and structs
// with constructors (and with in-class initialization of
// non-static members). But it does not default initialize
// memory for POD types like int, long.
if (!std::is_trivial<T>::value)
uninitialized_default_construct(end_, array_ + n);
}
else if (n < size())
destroy(array_ + n, end_);
end_ = array_ + n;
}
private:
T* array_ = nullptr;
T* end_ = nullptr;
T* capacity_ = nullptr;
void reserve_unchecked(std::size_t n)
{
ASSERT(n > capacity());
std::size_t old_size = size();
std::size_t old_capacity = capacity();
std::size_t new_capacity = get_new_capacity<T>(n);
ASSERT(new_capacity >= n);
ASSERT(new_capacity > old_size);
T* old = array_;
array_ = Allocator().allocate(new_capacity);
end_ = array_ + old_size;
capacity_ = array_ + new_capacity;
// Both primesieve & primecount require that byte arrays are
// aligned to at least a alignof(uint64_t) boundary. This is
// needed because our code casts byte arrays into uint64_t arrays
// in some places in order to improve performance. The default
// allocator guarantees that each memory allocation is at least
// aligned to the largest built-in type (usually 16 or 32).
ASSERT(((uintptr_t) (void*) array_) % sizeof(uint64_t) == 0);
if (old)
{
static_assert(std::is_nothrow_move_constructible<T>::value,
"pod_vector<T> only supports nothrow moveable types!");
uninitialized_move_n(old, old_size, array_);
Allocator().deallocate(old, old_capacity);
}
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<std::is_trivial<U>::value, std::size_t>::type
get_new_capacity(std::size_t size)
{
ASSERT(size > 0);
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (std::size_t)(capacity() * 1.5);
constexpr std::size_t min_alignment = sizeof(long) * 2;
constexpr std::size_t min_capacity = min_alignment / sizeof(U);
return std::max({min_capacity, size, new_capacity});
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<!std::is_trivial<U>::value, std::size_t>::type
get_new_capacity(std::size_t size)
{
ASSERT(size > 0);
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (std::size_t)(capacity() * 1.5);
return std::max(size, new_capacity);
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<std::is_trivially_copyable<U>::value, void>::type
uninitialized_move_n(U* __restrict first,
std::size_t count,
U* __restrict d_first)
{
// We can use memcpy to move trivially copyable types.
// https://en.cppreference.com/w/cpp/language/classes#Trivially_copyable_class
// https://stackoverflow.com/questions/17625635/moving-an-object-in-memory-using-stdmemcpy
std::uninitialized_copy_n(first, count, d_first);
}
/// Same as std::uninitialized_move_n() from C++17.
/// https://en.cppreference.com/w/cpp/memory/uninitialized_move_n
///
/// Unlike std::uninitialized_move_n() our implementation uses
/// __restrict pointers which improves the generated assembly
/// (using GCC & Clang). We can do this because we only use this
/// method for non-overlapping arrays.
template <typename U>
ALWAYS_INLINE typename std::enable_if<!std::is_trivially_copyable<U>::value, void>::type
uninitialized_move_n(U* __restrict first,
std::size_t count,
U* __restrict d_first)
{
for (std::size_t i = 0; i < count; i++)
new (d_first++) T(std::move(*first++));
}
/// Same as std::uninitialized_default_construct() from C++17.
/// https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct
ALWAYS_INLINE void uninitialized_default_construct(T* first, T* last)
{
// Default initialize array using placement new.
// Note that `new (first) T();` zero initializes built-in integer types,
// whereas `new (first) T;` does not initialize built-in integer types.
for (; first != last; first++)
new (first) T;
}
/// Same as std::destroy() from C++17.
/// https://en.cppreference.com/w/cpp/memory/destroy
ALWAYS_INLINE void destroy(T* first, T* last)
{
if (!std::is_trivially_destructible<T>::value)
{
// Theoretically deallocating in reverse order is more
// cache efficient. Clang's std::vector implementation
// also deallocates in reverse order.
while (first != last)
(--last)->~T();
}
}
};
template <typename T, std::size_t N>
class pod_array
{
public:
using value_type = T;
T array_[N];
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
void fill(const T& value)
{
std::fill_n(begin(), size(), value);
}
T* data() noexcept
{
return array_;
}
const T* data() const noexcept
{
return array_;
}
T* begin() noexcept
{
return array_;
}
const T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return array_ + N;
}
const T* end() const noexcept
{
return array_ + N;
}
T& back() noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
const T& back() const noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
constexpr std::size_t size() const noexcept
{
return N;
}
};
} // namespace
#endif
<commit_msg>Improve pod_vector::resize()<commit_after>///
/// @file pod_vector.hpp
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef POD_VECTOR_HPP
#define POD_VECTOR_HPP
#include "macros.hpp"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <stdint.h>
#include <type_traits>
#include <utility>
namespace primesieve {
/// pod_vector is a dynamically growing array.
/// It has the same API (though not complete) as std::vector but its
/// resize() method does not default initialize memory for built-in
/// integer types. It does however default initialize classes and
/// struct types if they have a constructor. It also prevents
/// bounds checks which is important for primesieve's performance, e.g.
/// the Fedora Linux distribution compiles with -D_GLIBCXX_ASSERTIONS
/// which enables std::vector bounds checks.
///
template <typename T,
typename Allocator = std::allocator<T>>
class pod_vector
{
public:
// The default C++ std::allocator is stateless. We use this
// allocator and do not support other statefull allocators,
// which simplifies our implementation.
//
// "The default allocator is stateless, that is, all instances
// of the given allocator are interchangeable, compare equal
// and can deallocate memory allocated by any other instance
// of the same allocator type."
// https://en.cppreference.com/w/cpp/memory/allocator
//
// "The member type is_always_equal of std::allocator_traits
// is intendedly used for determining whether an allocator
// type is stateless."
// https://en.cppreference.com/w/cpp/named_req/Allocator
static_assert(std::allocator_traits<Allocator>::is_always_equal::value,
"pod_vector<T> only supports stateless allocators!");
using value_type = T;
pod_vector() noexcept = default;
pod_vector(std::size_t size)
{
resize(size);
}
~pod_vector()
{
destroy(array_, end_);
Allocator().deallocate(array_, capacity());
}
/// Free all memory, the pod_vector
/// can be reused afterwards.
void deallocate() noexcept
{
this->~pod_vector<T>();
array_ = nullptr;
end_ = nullptr;
capacity_ = nullptr;
}
/// Reset the pod_vector, but do not free its
/// memory. Same as std::vector.clear().
void clear() noexcept
{
destroy(array_, end_);
end_ = array_;
}
/// Copying is slow, we prevent it
pod_vector(const pod_vector&) = delete;
pod_vector& operator=(const pod_vector&) = delete;
/// Move constructor
pod_vector(pod_vector&& other) noexcept
{
swap(other);
}
/// Move assignment operator
pod_vector& operator=(pod_vector&& other) noexcept
{
if (this != &other)
swap(other);
return *this;
}
/// Better assembly than: std::swap(vect1, vect2)
void swap(pod_vector& other) noexcept
{
T* tmp_array = array_;
T* tmp_end = end_;
T* tmp_capacity = capacity_;
array_ = other.array_;
end_ = other.end_;
capacity_ = other.capacity_;
other.array_ = tmp_array;
other.end_ = tmp_end;
other.capacity_ = tmp_capacity;
}
bool empty() const noexcept
{
return array_ == end_;
}
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
T* data() noexcept
{
return array_;
}
const T* data() const noexcept
{
return array_;
}
std::size_t size() const noexcept
{
ASSERT(end_ >= array_);
return (std::size_t)(end_ - array_);
}
std::size_t capacity() const noexcept
{
ASSERT(capacity_ >= array_);
return (std::size_t)(capacity_ - array_);
}
T* begin() noexcept
{
return array_;
}
const T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return end_;
}
const T* end() const noexcept
{
return end_;
}
T& front() noexcept
{
ASSERT(!empty());
return *array_;
}
const T& front() const noexcept
{
ASSERT(!empty());
return *array_;
}
T& back() noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
const T& back() const noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
ALWAYS_INLINE void push_back(const T& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Placement new
new(end_) T(value);
end_++;
}
ALWAYS_INLINE void push_back(T&& value)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Without std::move() the copy constructor will
// be called instead of the move constructor.
new(end_) T(std::move(value));
end_++;
}
template <class... Args>
ALWAYS_INLINE void emplace_back(Args&&... args)
{
if_unlikely(end_ == capacity_)
reserve_unchecked(std::max((std::size_t) 1, capacity() * 2));
// Placement new
new(end_) T(std::forward<Args>(args)...);
end_++;
}
template <class InputIt>
void insert(T* const pos, InputIt first, InputIt last)
{
static_assert(std::is_trivially_copyable<T>::value,
"pod_vector<T>::insert() supports only trivially copyable types!");
// We only support appending to the vector
ASSERT(pos == end_);
(void) pos;
if (first < last)
{
std::size_t new_size = size() + (std::size_t) (last - first);
reserve(new_size);
std::uninitialized_copy(first, last, end_);
end_ = array_ + new_size;
}
}
void reserve(std::size_t n)
{
if (n > capacity())
reserve_unchecked(n);
}
void resize(std::size_t n)
{
if (n > size())
{
if (n > capacity())
reserve_unchecked(n);
// This default initializes memory of classes and structs
// with constructors (and with in-class initialization of
// non-static members). But it does not default initialize
// memory for POD types like int, long.
if (!std::is_trivial<T>::value)
uninitialized_default_construct(end_, array_ + n);
end_ = array_ + n;
}
else if (n < size())
{
destroy(array_ + n, end_);
end_ = array_ + n;
}
}
private:
T* array_ = nullptr;
T* end_ = nullptr;
T* capacity_ = nullptr;
void reserve_unchecked(std::size_t n)
{
ASSERT(n > capacity());
std::size_t old_size = size();
std::size_t old_capacity = capacity();
// GCC & Clang's std::vector grow the capacity by at least
// 2x for every call to resize() with n > capacity(). We
// grow by at least 1.5x as we tend to accurately calculate
// the amount of memory we need upfront.
std::size_t new_capacity = (old_capacity * 3) / 2;
new_capacity = std::max(new_capacity, n);
ASSERT(new_capacity > old_size);
T* old = array_;
array_ = Allocator().allocate(new_capacity);
end_ = array_ + old_size;
capacity_ = array_ + new_capacity;
// Both primesieve & primecount require that byte arrays are
// aligned to at least a alignof(uint64_t) boundary. This is
// needed because our code casts byte arrays into uint64_t arrays
// in some places in order to improve performance. The default
// allocator guarantees that each memory allocation is at least
// aligned to the largest built-in type (usually 16 or 32).
ASSERT(((uintptr_t) (void*) array_) % sizeof(uint64_t) == 0);
if (old)
{
static_assert(std::is_nothrow_move_constructible<T>::value,
"pod_vector<T> only supports nothrow moveable types!");
uninitialized_move_n(old, old_size, array_);
Allocator().deallocate(old, old_capacity);
}
}
template <typename U>
ALWAYS_INLINE typename std::enable_if<std::is_trivially_copyable<U>::value, void>::type
uninitialized_move_n(U* __restrict first,
std::size_t count,
U* __restrict d_first)
{
// We can use memcpy to move trivially copyable types.
// https://en.cppreference.com/w/cpp/language/classes#Trivially_copyable_class
// https://stackoverflow.com/questions/17625635/moving-an-object-in-memory-using-stdmemcpy
std::uninitialized_copy_n(first, count, d_first);
}
/// Same as std::uninitialized_move_n() from C++17.
/// https://en.cppreference.com/w/cpp/memory/uninitialized_move_n
///
/// Unlike std::uninitialized_move_n() our implementation uses
/// __restrict pointers which improves the generated assembly
/// (using GCC & Clang). We can do this because we only use this
/// method for non-overlapping arrays.
template <typename U>
ALWAYS_INLINE typename std::enable_if<!std::is_trivially_copyable<U>::value, void>::type
uninitialized_move_n(U* __restrict first,
std::size_t count,
U* __restrict d_first)
{
for (std::size_t i = 0; i < count; i++)
new (d_first++) T(std::move(*first++));
}
/// Same as std::uninitialized_default_construct() from C++17.
/// https://en.cppreference.com/w/cpp/memory/uninitialized_default_construct
ALWAYS_INLINE void uninitialized_default_construct(T* first, T* last)
{
// Default initialize array using placement new.
// Note that `new (first) T();` zero initializes built-in integer types,
// whereas `new (first) T;` does not initialize built-in integer types.
for (; first != last; first++)
new (first) T;
}
/// Same as std::destroy() from C++17.
/// https://en.cppreference.com/w/cpp/memory/destroy
ALWAYS_INLINE void destroy(T* first, T* last)
{
if (!std::is_trivially_destructible<T>::value)
{
// Theoretically deallocating in reverse order is more
// cache efficient. Clang's std::vector implementation
// also deallocates in reverse order.
while (first != last)
(--last)->~T();
}
}
};
template <typename T, std::size_t N>
class pod_array
{
public:
using value_type = T;
T array_[N];
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
void fill(const T& value)
{
std::fill_n(begin(), size(), value);
}
T* data() noexcept
{
return array_;
}
const T* data() const noexcept
{
return array_;
}
T* begin() noexcept
{
return array_;
}
const T* begin() const noexcept
{
return array_;
}
T* end() noexcept
{
return array_ + N;
}
const T* end() const noexcept
{
return array_ + N;
}
T& back() noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
const T& back() const noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
constexpr std::size_t size() const noexcept
{
return N;
}
};
} // namespace
#endif
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Scylladb, Ltd.
*/
#pragma once
#include <algorithm>
#include <endian.h>
#include <seastar/core/unaligned.hh>
namespace seastar {
inline uint8_t cpu_to_le(uint8_t x) { return x; }
inline uint8_t le_to_cpu(uint8_t x) { return x; }
inline uint16_t cpu_to_le(uint16_t x) { return htole16(x); }
inline uint16_t le_to_cpu(uint16_t x) { return le16toh(x); }
inline uint32_t cpu_to_le(uint32_t x) { return htole32(x); }
inline uint32_t le_to_cpu(uint32_t x) { return le32toh(x); }
inline uint64_t cpu_to_le(uint64_t x) { return htole64(x); }
inline uint64_t le_to_cpu(uint64_t x) { return le64toh(x); }
inline int8_t cpu_to_le(int8_t x) { return x; }
inline int8_t le_to_cpu(int8_t x) { return x; }
inline int16_t cpu_to_le(int16_t x) { return htole16(x); }
inline int16_t le_to_cpu(int16_t x) { return le16toh(x); }
inline int32_t cpu_to_le(int32_t x) { return htole32(x); }
inline int32_t le_to_cpu(int32_t x) { return le32toh(x); }
inline int64_t cpu_to_le(int64_t x) { return htole64(x); }
inline int64_t le_to_cpu(int64_t x) { return le64toh(x); }
inline uint8_t cpu_to_be(uint8_t x) { return x; }
inline uint8_t be_to_cpu(uint8_t x) { return x; }
inline uint16_t cpu_to_be(uint16_t x) { return htobe16(x); }
inline uint16_t be_to_cpu(uint16_t x) { return be16toh(x); }
inline uint32_t cpu_to_be(uint32_t x) { return htobe32(x); }
inline uint32_t be_to_cpu(uint32_t x) { return be32toh(x); }
inline uint64_t cpu_to_be(uint64_t x) { return htobe64(x); }
inline uint64_t be_to_cpu(uint64_t x) { return be64toh(x); }
inline int8_t cpu_to_be(int8_t x) { return x; }
inline int8_t be_to_cpu(int8_t x) { return x; }
inline int16_t cpu_to_be(int16_t x) { return htobe16(x); }
inline int16_t be_to_cpu(int16_t x) { return be16toh(x); }
inline int32_t cpu_to_be(int32_t x) { return htobe32(x); }
inline int32_t be_to_cpu(int32_t x) { return be32toh(x); }
inline int64_t cpu_to_be(int64_t x) { return htobe64(x); }
inline int64_t be_to_cpu(int64_t x) { return be64toh(x); }
template <typename T>
inline T cpu_to_le(const unaligned<T>& v) {
return cpu_to_le(T(v));
}
template <typename T>
inline T le_to_cpu(const unaligned<T>& v) {
return le_to_cpu(T(v));
}
template <typename T>
inline
T
read_le(const char* p) {
T datum;
std::copy_n(p, sizeof(T), reinterpret_cast<char*>(&datum));
return le_to_cpu(datum);
}
template <typename T>
inline
void
write_le(char* p, T datum) {
datum = cpu_to_le(datum);
std::copy_n(reinterpret_cast<const char*>(&datum), sizeof(T), p);
}
template <typename T>
inline
T
read_be(const char* p) {
T datum;
std::copy_n(p, sizeof(T), reinterpret_cast<char*>(&datum));
return be_to_cpu(datum);
}
template <typename T>
inline
void
write_be(char* p, T datum) {
datum = cpu_to_be(datum);
std::copy_n(reinterpret_cast<const char*>(&datum), sizeof(T), p);
}
template <typename T>
inline
T
consume_be(const char*& p) {
auto ret = read_be<T>(p);
p += sizeof(T);
return ret;
}
template <typename T>
inline
void
produce_be(char*& p, T datum) {
write_be<T>(p, datum);
p += sizeof(T);
}
}
<commit_msg>byteorder: Mark functions as noexcept<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Scylladb, Ltd.
*/
#pragma once
#include <algorithm>
#include <endian.h>
#include <seastar/core/unaligned.hh>
namespace seastar {
inline uint8_t cpu_to_le(uint8_t x) noexcept { return x; }
inline uint8_t le_to_cpu(uint8_t x) noexcept { return x; }
inline uint16_t cpu_to_le(uint16_t x) noexcept { return htole16(x); }
inline uint16_t le_to_cpu(uint16_t x) noexcept { return le16toh(x); }
inline uint32_t cpu_to_le(uint32_t x) noexcept { return htole32(x); }
inline uint32_t le_to_cpu(uint32_t x) noexcept { return le32toh(x); }
inline uint64_t cpu_to_le(uint64_t x) noexcept { return htole64(x); }
inline uint64_t le_to_cpu(uint64_t x) noexcept { return le64toh(x); }
inline int8_t cpu_to_le(int8_t x) noexcept { return x; }
inline int8_t le_to_cpu(int8_t x) noexcept { return x; }
inline int16_t cpu_to_le(int16_t x) noexcept { return htole16(x); }
inline int16_t le_to_cpu(int16_t x) noexcept { return le16toh(x); }
inline int32_t cpu_to_le(int32_t x) noexcept { return htole32(x); }
inline int32_t le_to_cpu(int32_t x) noexcept { return le32toh(x); }
inline int64_t cpu_to_le(int64_t x) noexcept { return htole64(x); }
inline int64_t le_to_cpu(int64_t x) noexcept { return le64toh(x); }
inline uint8_t cpu_to_be(uint8_t x) noexcept { return x; }
inline uint8_t be_to_cpu(uint8_t x) noexcept { return x; }
inline uint16_t cpu_to_be(uint16_t x) noexcept { return htobe16(x); }
inline uint16_t be_to_cpu(uint16_t x) noexcept { return be16toh(x); }
inline uint32_t cpu_to_be(uint32_t x) noexcept { return htobe32(x); }
inline uint32_t be_to_cpu(uint32_t x) noexcept { return be32toh(x); }
inline uint64_t cpu_to_be(uint64_t x) noexcept { return htobe64(x); }
inline uint64_t be_to_cpu(uint64_t x) noexcept { return be64toh(x); }
inline int8_t cpu_to_be(int8_t x) noexcept { return x; }
inline int8_t be_to_cpu(int8_t x) noexcept { return x; }
inline int16_t cpu_to_be(int16_t x) noexcept { return htobe16(x); }
inline int16_t be_to_cpu(int16_t x) noexcept { return be16toh(x); }
inline int32_t cpu_to_be(int32_t x) noexcept { return htobe32(x); }
inline int32_t be_to_cpu(int32_t x) noexcept { return be32toh(x); }
inline int64_t cpu_to_be(int64_t x) noexcept { return htobe64(x); }
inline int64_t be_to_cpu(int64_t x) noexcept { return be64toh(x); }
template <typename T>
inline T cpu_to_le(const unaligned<T>& v) noexcept {
return cpu_to_le(T(v));
}
template <typename T>
inline T le_to_cpu(const unaligned<T>& v) noexcept {
return le_to_cpu(T(v));
}
template <typename T>
inline
T
read_le(const char* p) noexcept {
T datum;
std::copy_n(p, sizeof(T), reinterpret_cast<char*>(&datum));
return le_to_cpu(datum);
}
template <typename T>
inline
void
write_le(char* p, T datum) noexcept {
datum = cpu_to_le(datum);
std::copy_n(reinterpret_cast<const char*>(&datum), sizeof(T), p);
}
template <typename T>
inline
T
read_be(const char* p) noexcept {
T datum;
std::copy_n(p, sizeof(T), reinterpret_cast<char*>(&datum));
return be_to_cpu(datum);
}
template <typename T>
inline
void
write_be(char* p, T datum) noexcept {
datum = cpu_to_be(datum);
std::copy_n(reinterpret_cast<const char*>(&datum), sizeof(T), p);
}
template <typename T>
inline
T
consume_be(const char*& p) noexcept {
auto ret = read_be<T>(p);
p += sizeof(T);
return ret;
}
template <typename T>
inline
void
produce_be(char*& p, T datum) noexcept {
write_be<T>(p, datum);
p += sizeof(T);
}
}
<|endoftext|> |
<commit_before>//===- ModuleIndex.hpp - Allow Module lookups by index -------------- C++ -===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_UTIL_MODULEINDEX_HPP
#define SEEC_UTIL_MODULEINDEX_HPP
#include "seec/Util/Maybe.hpp"
#include "llvm/Module.h"
#include "llvm/ADT/DenseMap.h"
#include <vector>
namespace seec {
/// \brief Index for an llvm::Function.
class FunctionIndex {
/// Lookup Instruction pointers by their index.
std::vector<llvm::Instruction *> InstructionPtrByIdx;
/// Map Instruction pointers to their indices.
llvm::DenseMap<llvm::Instruction const *, uint32_t> InstructionIdxByPtr;
/// Lookup Argument pointers by their index.
std::vector<llvm::Argument *> ArgumentPtrByIdx;
public:
/// \brief Constructor.
FunctionIndex(llvm::Function &Function)
: InstructionPtrByIdx(),
InstructionIdxByPtr(),
ArgumentPtrByIdx()
{
for (auto &BasicBlock: Function) {
for (auto &Instruction: BasicBlock) {
uint32_t Idx = static_cast<uint32_t>(InstructionPtrByIdx.size());
InstructionIdxByPtr[&Instruction] = Idx;
InstructionPtrByIdx.push_back(&Instruction);
}
}
for (auto &Argument : Function.getArgumentList()) {
ArgumentPtrByIdx.push_back(&Argument);
}
}
/// \name Instruction mapping.
/// @{
/// \brief Get the number of Instructions in the indexed Function.
size_t getInstructionCount() const { return InstructionPtrByIdx.size(); }
/// \brief Get the Instruction at the given Index in the indexed Function.
llvm::Instruction *getInstruction(uint32_t Index) const {
if (Index < InstructionPtrByIdx.size())
return InstructionPtrByIdx[Index];
return nullptr;
}
/// \brief Get the index of the given Instruction in the indexed Function.
///
/// If the Instruction does not exist in the Function, then the Maybe returned
/// will be unassigned.
util::Maybe<uint32_t>
getIndexOfInstruction(llvm::Instruction const *Instruction) const {
auto It = InstructionIdxByPtr.find(Instruction);
if (It != InstructionIdxByPtr.end())
return util::Maybe<uint32_t>(It->second);
return util::Maybe<uint32_t>();
}
/// @}
/// \name Argument mapping.
/// @{
/// \brief Get the Argument at the given Index in the indexed Function.
llvm::Argument *getArgument(uint32_t Index) const {
if (Index < ArgumentPtrByIdx.size())
return ArgumentPtrByIdx[Index];
return nullptr;
}
/// @}
};
/// \brief Index for an llvm::Module.
class ModuleIndex {
/// The indexed Module.
llvm::Module const &Module;
/// Lookup GlobalVariables by their index.
std::vector<llvm::GlobalVariable *> GlobalPtrByIdx;
/// Map GlobalVariables to their indices.
llvm::DenseMap<llvm::GlobalVariable const *, uint32_t> GlobalIdxByPtr;
/// Lookup Functions by their index.
std::vector<llvm::Function *> mutable FunctionPtrByIdx;
/// Map Functions to their indices.
llvm::DenseMap<llvm::Function const *, uint32_t> mutable FunctionIdxByPtr;
/// Store FunctionIndexs by the index of the Function.
std::vector<std::unique_ptr<FunctionIndex>> mutable FunctionIndexByIdx;
// do not implement
ModuleIndex(ModuleIndex const &Other) = delete;
ModuleIndex &operator=(ModuleIndex const &RHS) = delete;
public:
/// \brief Constructor.
ModuleIndex(llvm::Module &Module,
bool const GenerateFunctionIndexForAll = false)
: Module(Module),
FunctionPtrByIdx(),
FunctionIdxByPtr(),
FunctionIndexByIdx()
{
// Index all GlobalVariables
for (auto GIt = Module.global_begin(), GEnd = Module.global_end();
GIt != GEnd; ++GIt) {
auto GPtr = &*GIt;
GlobalIdxByPtr[GPtr] = GlobalPtrByIdx.size();
GlobalPtrByIdx.push_back(GPtr);
}
// Index all Functions
for (auto &Function: Module) {
FunctionIdxByPtr[&Function] = FunctionPtrByIdx.size();
FunctionPtrByIdx.push_back(&Function);
if (GenerateFunctionIndexForAll) {
FunctionIndexByIdx.emplace_back(new FunctionIndex(Function));
}
else {
FunctionIndexByIdx.emplace_back(nullptr); // will be lazily constructed
}
}
}
/// \brief Get the Module.
llvm::Module const &getModule() const { return Module; }
/// \brief Get the number of global variables in the indexed Module.
size_t getGlobalCount() const { return GlobalPtrByIdx.size(); }
/// Get the llvm::GlobalVariable at the given Index, or nullptr, if the Index
/// is invalid.
llvm::GlobalVariable *getGlobal(uint32_t Index) const {
if (Index < GlobalPtrByIdx.size())
return GlobalPtrByIdx[Index];
return nullptr;
}
/// \brief Get the Index of the given llvm::GlobalVariable.
util::Maybe<uint32_t>
getIndexOfGlobal(llvm::GlobalVariable const *Global) const {
auto It = GlobalIdxByPtr.find(Global);
if (It != GlobalIdxByPtr.end())
return util::Maybe<uint32_t>(It->second);
return util::Maybe<uint32_t>();
}
/// \brief Get the number of functions in the indexed Module.
size_t getFunctionCount() const { return FunctionPtrByIdx.size(); }
/// Get the llvm::Function at the given Index, or nullptr, if the Index is
/// invalid.
llvm::Function *getFunction(uint32_t Index) const {
if (Index < FunctionPtrByIdx.size())
return FunctionPtrByIdx[Index];
return nullptr;
}
/// \brief Get the Index of the given llvm::Function.
util::Maybe<uint32_t> getIndexOfFunction(llvm::Function const *Function) const {
auto It = FunctionIdxByPtr.find(Function);
if (It != FunctionIdxByPtr.end())
return util::Maybe<uint32_t>(It->second);
return util::Maybe<uint32_t>();
}
/// \brief Generate the FunctionIndex for all llvm::Functions.
void generateFunctionIndexForAll() const {
for (std::size_t i = 0; i < FunctionIndexByIdx.size(); ++i) {
if (!FunctionIndexByIdx[i]) {
auto &Function = *(FunctionPtrByIdx[i]);
FunctionIndexByIdx[i].reset(new FunctionIndex(Function));
}
}
}
/// \brief Get the FunctionIndex for the llvm::Function with the given Index.
FunctionIndex *getFunctionIndex(uint32_t Index) const {
if (Index >= FunctionIndexByIdx.size())
return nullptr;
// if no FunctionIndex exists, construct one now
if (!FunctionIndexByIdx[Index]) {
auto &Function = *(FunctionPtrByIdx[Index]);
FunctionIndexByIdx[Index].reset(new FunctionIndex(Function));
}
return FunctionIndexByIdx[Index].get();
}
/// \brief Get the FunctionIndex for the given llvm::Function.
FunctionIndex *getFunctionIndex(llvm::Function const *Function) const {
auto Idx = getIndexOfFunction(Function);
if (!Idx.assigned())
return nullptr;
return getFunctionIndex(Idx.get<0>());
}
};
}
#endif // SEEC_UTIL_MODULEINDEX_HPP
<commit_msg>Add seec::FunctionIndex::getArguments(), which returns a seec::Range<> containing pointers to all of the Function's Arguments.<commit_after>//===- ModuleIndex.hpp - Allow Module lookups by index -------------- C++ -===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_UTIL_MODULEINDEX_HPP
#define SEEC_UTIL_MODULEINDEX_HPP
#include "seec/Util/Maybe.hpp"
#include "seec/Util/Range.hpp"
#include "llvm/Module.h"
#include "llvm/ADT/DenseMap.h"
#include <vector>
namespace seec {
/// \brief Index for an llvm::Function.
class FunctionIndex {
/// Lookup Instruction pointers by their index.
std::vector<llvm::Instruction *> InstructionPtrByIdx;
/// Map Instruction pointers to their indices.
llvm::DenseMap<llvm::Instruction const *, uint32_t> InstructionIdxByPtr;
/// Lookup Argument pointers by their index.
std::vector<llvm::Argument *> ArgumentPtrByIdx;
public:
/// \brief Constructor.
FunctionIndex(llvm::Function &Function)
: InstructionPtrByIdx(),
InstructionIdxByPtr(),
ArgumentPtrByIdx()
{
for (auto &BasicBlock: Function) {
for (auto &Instruction: BasicBlock) {
uint32_t Idx = static_cast<uint32_t>(InstructionPtrByIdx.size());
InstructionIdxByPtr[&Instruction] = Idx;
InstructionPtrByIdx.push_back(&Instruction);
}
}
for (auto &Argument : Function.getArgumentList()) {
ArgumentPtrByIdx.push_back(&Argument);
}
}
/// \name Instruction mapping.
/// @{
/// \brief Get the number of Instructions in the indexed Function.
size_t getInstructionCount() const { return InstructionPtrByIdx.size(); }
/// \brief Get the Instruction at the given Index in the indexed Function.
llvm::Instruction *getInstruction(uint32_t Index) const {
if (Index < InstructionPtrByIdx.size())
return InstructionPtrByIdx[Index];
return nullptr;
}
/// \brief Get the index of the given Instruction in the indexed Function.
///
/// If the Instruction does not exist in the Function, then the Maybe returned
/// will be unassigned.
util::Maybe<uint32_t>
getIndexOfInstruction(llvm::Instruction const *Instruction) const {
auto It = InstructionIdxByPtr.find(Instruction);
if (It != InstructionIdxByPtr.end())
return util::Maybe<uint32_t>(It->second);
return util::Maybe<uint32_t>();
}
/// @}
/// \name Argument mapping.
/// @{
/// \brief Get the Argument at the given Index in the indexed Function.
llvm::Argument *getArgument(uint32_t Index) const {
if (Index < ArgumentPtrByIdx.size())
return ArgumentPtrByIdx[Index];
return nullptr;
}
/// \brief Get a range containing all Arguments.
seec::Range<typename decltype(ArgumentPtrByIdx)::const_iterator>
getArguments() const {
return seec::range(ArgumentPtrByIdx.cbegin(), ArgumentPtrByIdx.cend());
}
/// @}
};
/// \brief Index for an llvm::Module.
class ModuleIndex {
/// The indexed Module.
llvm::Module const &Module;
/// Lookup GlobalVariables by their index.
std::vector<llvm::GlobalVariable *> GlobalPtrByIdx;
/// Map GlobalVariables to their indices.
llvm::DenseMap<llvm::GlobalVariable const *, uint32_t> GlobalIdxByPtr;
/// Lookup Functions by their index.
std::vector<llvm::Function *> mutable FunctionPtrByIdx;
/// Map Functions to their indices.
llvm::DenseMap<llvm::Function const *, uint32_t> mutable FunctionIdxByPtr;
/// Store FunctionIndexs by the index of the Function.
std::vector<std::unique_ptr<FunctionIndex>> mutable FunctionIndexByIdx;
// do not implement
ModuleIndex(ModuleIndex const &Other) = delete;
ModuleIndex &operator=(ModuleIndex const &RHS) = delete;
public:
/// \brief Constructor.
ModuleIndex(llvm::Module &Module,
bool const GenerateFunctionIndexForAll = false)
: Module(Module),
FunctionPtrByIdx(),
FunctionIdxByPtr(),
FunctionIndexByIdx()
{
// Index all GlobalVariables
for (auto GIt = Module.global_begin(), GEnd = Module.global_end();
GIt != GEnd; ++GIt) {
auto GPtr = &*GIt;
GlobalIdxByPtr[GPtr] = GlobalPtrByIdx.size();
GlobalPtrByIdx.push_back(GPtr);
}
// Index all Functions
for (auto &Function: Module) {
FunctionIdxByPtr[&Function] = FunctionPtrByIdx.size();
FunctionPtrByIdx.push_back(&Function);
if (GenerateFunctionIndexForAll) {
FunctionIndexByIdx.emplace_back(new FunctionIndex(Function));
}
else {
FunctionIndexByIdx.emplace_back(nullptr); // will be lazily constructed
}
}
}
/// \brief Get the Module.
llvm::Module const &getModule() const { return Module; }
/// \brief Get the number of global variables in the indexed Module.
size_t getGlobalCount() const { return GlobalPtrByIdx.size(); }
/// Get the llvm::GlobalVariable at the given Index, or nullptr, if the Index
/// is invalid.
llvm::GlobalVariable *getGlobal(uint32_t Index) const {
if (Index < GlobalPtrByIdx.size())
return GlobalPtrByIdx[Index];
return nullptr;
}
/// \brief Get the Index of the given llvm::GlobalVariable.
util::Maybe<uint32_t>
getIndexOfGlobal(llvm::GlobalVariable const *Global) const {
auto It = GlobalIdxByPtr.find(Global);
if (It != GlobalIdxByPtr.end())
return util::Maybe<uint32_t>(It->second);
return util::Maybe<uint32_t>();
}
/// \brief Get the number of functions in the indexed Module.
size_t getFunctionCount() const { return FunctionPtrByIdx.size(); }
/// Get the llvm::Function at the given Index, or nullptr, if the Index is
/// invalid.
llvm::Function *getFunction(uint32_t Index) const {
if (Index < FunctionPtrByIdx.size())
return FunctionPtrByIdx[Index];
return nullptr;
}
/// \brief Get the Index of the given llvm::Function.
util::Maybe<uint32_t> getIndexOfFunction(llvm::Function const *Function) const {
auto It = FunctionIdxByPtr.find(Function);
if (It != FunctionIdxByPtr.end())
return util::Maybe<uint32_t>(It->second);
return util::Maybe<uint32_t>();
}
/// \brief Generate the FunctionIndex for all llvm::Functions.
void generateFunctionIndexForAll() const {
for (std::size_t i = 0; i < FunctionIndexByIdx.size(); ++i) {
if (!FunctionIndexByIdx[i]) {
auto &Function = *(FunctionPtrByIdx[i]);
FunctionIndexByIdx[i].reset(new FunctionIndex(Function));
}
}
}
/// \brief Get the FunctionIndex for the llvm::Function with the given Index.
FunctionIndex *getFunctionIndex(uint32_t Index) const {
if (Index >= FunctionIndexByIdx.size())
return nullptr;
// if no FunctionIndex exists, construct one now
if (!FunctionIndexByIdx[Index]) {
auto &Function = *(FunctionPtrByIdx[Index]);
FunctionIndexByIdx[Index].reset(new FunctionIndex(Function));
}
return FunctionIndexByIdx[Index].get();
}
/// \brief Get the FunctionIndex for the given llvm::Function.
FunctionIndex *getFunctionIndex(llvm::Function const *Function) const {
auto Idx = getIndexOfFunction(Function);
if (!Idx.assigned())
return nullptr;
return getFunctionIndex(Idx.get<0>());
}
};
}
#endif // SEEC_UTIL_MODULEINDEX_HPP
<|endoftext|> |
<commit_before>#ifndef _SOT_CORE_CAUSAL_FILTER_H_
#define _SOT_CORE_CAUSAL_FILTER_H_
/*
* Copyright 2017-, Rohan Budhirja, LAAS-CNRS
*
* This file is part of sot-torque-control.
* sot-torque-control 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.
* sot-torque-control 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 sot-torque-control. If not, see <http://www.gnu.org/licenses/>.
*/
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#include <Eigen/Core>
/** \addtogroup Filters
\section subsec_causalfilter CausalFilter
Filter data with an IIR or FIR filter.
Filter a data sequence, \f$x\f$, using a digital filter.
The filter is a direct form II transposed implementation
of the standard difference equation.
This means that the filter implements:
\f$ a[0]*y[N] = b[0]*x[N] + b[1]*x[N-1] + ... + b[m-1]*x[N-(m-1)]
- a[1]*y[N-1] - ... - a[n-1]*y[N-(n-1)] \f$
where \f$m\f$ is the degree of the numerator,
\f$n\f$ is the degree of the denominator,
and \f$N\f$ is the sample number
*/
namespace dynamicgraph {
namespace sot {
class CausalFilter
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/** --- CONSTRUCTOR ----
\param[in] timestep
\param[in] xSize
\param[in] filter_numerator
\param[in] filter_denominator
xSize is
*/
CausalFilter(const double ×tep,
const int& xSize,
const Eigen::VectorXd& filter_numerator,
const Eigen::VectorXd& filter_denominator);
void get_x_dx_ddx(const Eigen::VectorXd& base_x,
Eigen::VectorXd& x_output_dx_ddx);
void switch_filter(const Eigen::VectorXd& filter_numerator,
const Eigen::VectorXd& filter_denominator);
private:
/// sampling timestep of the input signal
double m_dt;
/// Size
int m_x_size;
/// Size of the numerator \f$m\f$
Eigen::Index m_filter_order_m;
/// Size of the denominator \f$n\f$
Eigen::Index m_filter_order_n;
/// Coefficients of the numerator \f$b\f$
Eigen::VectorXd m_filter_numerator;
/// Coefficients of the denominator \f$a\f$
Eigen::VectorXd m_filter_denominator;
bool m_first_sample;
///
int m_pt_numerator;
int m_pt_denominator;
Eigen::MatrixXd m_input_buffer;
Eigen::MatrixXd m_output_buffer;
}; // class CausalFilter
} /// core
} /// sot
#endif /* _SOT_CORE_CAUSAL_FILTER_H_ */
<commit_msg>[filter] Causal-filter fix Eigen::Index to Eigen::VectorXd::Index<commit_after>#ifndef _SOT_CORE_CAUSAL_FILTER_H_
#define _SOT_CORE_CAUSAL_FILTER_H_
/*
* Copyright 2017-, Rohan Budhirja, LAAS-CNRS
*
* This file is part of sot-torque-control.
* sot-torque-control 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.
* sot-torque-control 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 sot-torque-control. If not, see <http://www.gnu.org/licenses/>.
*/
/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#include <Eigen/Core>
/** \addtogroup Filters
\section subsec_causalfilter CausalFilter
Filter data with an IIR or FIR filter.
Filter a data sequence, \f$x\f$, using a digital filter.
The filter is a direct form II transposed implementation
of the standard difference equation.
This means that the filter implements:
\f$ a[0]*y[N] = b[0]*x[N] + b[1]*x[N-1] + ... + b[m-1]*x[N-(m-1)]
- a[1]*y[N-1] - ... - a[n-1]*y[N-(n-1)] \f$
where \f$m\f$ is the degree of the numerator,
\f$n\f$ is the degree of the denominator,
and \f$N\f$ is the sample number
*/
namespace dynamicgraph {
namespace sot {
class CausalFilter
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
/** --- CONSTRUCTOR ----
\param[in] timestep
\param[in] xSize
\param[in] filter_numerator
\param[in] filter_denominator
xSize is
*/
CausalFilter(const double ×tep,
const int& xSize,
const Eigen::VectorXd& filter_numerator,
const Eigen::VectorXd& filter_denominator);
void get_x_dx_ddx(const Eigen::VectorXd& base_x,
Eigen::VectorXd& x_output_dx_ddx);
void switch_filter(const Eigen::VectorXd& filter_numerator,
const Eigen::VectorXd& filter_denominator);
private:
/// sampling timestep of the input signal
double m_dt;
/// Size
int m_x_size;
/// Size of the numerator \f$m\f$
Eigen::VectorXd::Index m_filter_order_m;
/// Size of the denominator \f$n\f$
Eigen::VectorXd::Index m_filter_order_n;
/// Coefficients of the numerator \f$b\f$
Eigen::VectorXd m_filter_numerator;
/// Coefficients of the denominator \f$a\f$
Eigen::VectorXd m_filter_denominator;
bool m_first_sample;
///
int m_pt_numerator;
int m_pt_denominator;
Eigen::MatrixXd m_input_buffer;
Eigen::MatrixXd m_output_buffer;
}; // class CausalFilter
} /// core
} /// sot
#endif /* _SOT_CORE_CAUSAL_FILTER_H_ */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: pyuno_gc.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2005-02-11 16:40:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Ralph Thomas
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Ralph Thomas, Joerg Budischewski
*
*
************************************************************************/
#include <osl/thread.hxx>
#include <pyuno_impl.hxx>
namespace pyuno
{
bool g_destructorsOfStaticObjectsHaveBeenCalled;
class StaticDestructorGuard
{
public:
~StaticDestructorGuard()
{
g_destructorsOfStaticObjectsHaveBeenCalled = true;
}
};
StaticDestructorGuard guard;
class GCThread : public ::osl::Thread
{
PyObject *mPyObject;
PyInterpreterState *mPyInterpreter;
GCThread( const GCThread & ); // not implemented
GCThread &operator =( const GCThread & ); // not implemented
public:
GCThread( PyInterpreterState *interpreter, PyObject * object );
virtual void SAL_CALL run();
virtual void SAL_CALL onTerminated();
};
GCThread::GCThread( PyInterpreterState *interpreter, PyObject * object ) :
mPyInterpreter( interpreter ), mPyObject( object )
{}
void GCThread::run()
{
// otherwise we crash here, when main has been left already
if( g_destructorsOfStaticObjectsHaveBeenCalled )
return;
try
{
PyThreadAttach guard( (PyInterpreterState*)mPyInterpreter );
{
Runtime runtime;
// remove the reference from the pythonobject2adapter map
PyRef2Adapter::iterator ii =
runtime.getImpl()->cargo->mappedObjects.find( mPyObject );
if( ii != runtime.getImpl()->cargo->mappedObjects.end() )
{
runtime.getImpl()->cargo->mappedObjects.erase( ii );
}
Py_XDECREF( mPyObject );
}
}
catch( com::sun::star::uno::RuntimeException & e )
{
rtl::OString msg;
msg = rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
fprintf( stderr, "Leaking python objects bridged to UNO for reason %s\n",msg.getStr());
}
}
void GCThread::onTerminated()
{
delete this;
}
void decreaseRefCount( PyInterpreterState *interpreter, PyObject *object )
{
// otherwise we crash in the last after main ...
if( g_destructorsOfStaticObjectsHaveBeenCalled )
return;
// delegate to a new thread, because there does not seem
// to be a method, which tells, whether the global
// interpreter lock is held or not
// TODO: Look for a more efficient solution
osl::Thread *t = new GCThread( interpreter, object );
t->create();
}
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.14); FILE MERGED 2005/09/05 18:39:21 rt 1.3.14.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pyuno_gc.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:52:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <osl/thread.hxx>
#include <pyuno_impl.hxx>
namespace pyuno
{
bool g_destructorsOfStaticObjectsHaveBeenCalled;
class StaticDestructorGuard
{
public:
~StaticDestructorGuard()
{
g_destructorsOfStaticObjectsHaveBeenCalled = true;
}
};
StaticDestructorGuard guard;
class GCThread : public ::osl::Thread
{
PyObject *mPyObject;
PyInterpreterState *mPyInterpreter;
GCThread( const GCThread & ); // not implemented
GCThread &operator =( const GCThread & ); // not implemented
public:
GCThread( PyInterpreterState *interpreter, PyObject * object );
virtual void SAL_CALL run();
virtual void SAL_CALL onTerminated();
};
GCThread::GCThread( PyInterpreterState *interpreter, PyObject * object ) :
mPyInterpreter( interpreter ), mPyObject( object )
{}
void GCThread::run()
{
// otherwise we crash here, when main has been left already
if( g_destructorsOfStaticObjectsHaveBeenCalled )
return;
try
{
PyThreadAttach guard( (PyInterpreterState*)mPyInterpreter );
{
Runtime runtime;
// remove the reference from the pythonobject2adapter map
PyRef2Adapter::iterator ii =
runtime.getImpl()->cargo->mappedObjects.find( mPyObject );
if( ii != runtime.getImpl()->cargo->mappedObjects.end() )
{
runtime.getImpl()->cargo->mappedObjects.erase( ii );
}
Py_XDECREF( mPyObject );
}
}
catch( com::sun::star::uno::RuntimeException & e )
{
rtl::OString msg;
msg = rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );
fprintf( stderr, "Leaking python objects bridged to UNO for reason %s\n",msg.getStr());
}
}
void GCThread::onTerminated()
{
delete this;
}
void decreaseRefCount( PyInterpreterState *interpreter, PyObject *object )
{
// otherwise we crash in the last after main ...
if( g_destructorsOfStaticObjectsHaveBeenCalled )
return;
// delegate to a new thread, because there does not seem
// to be a method, which tells, whether the global
// interpreter lock is held or not
// TODO: Look for a more efficient solution
osl::Thread *t = new GCThread( interpreter, object );
t->create();
}
}
<|endoftext|> |
<commit_before>#include "QmitkFunctionality.h"
#include <qlcdnumber.h>
#include <qslider.h>
#include <itkCommand.h>
QmitkFunctionality::QmitkFunctionality(QObject *parent, const char *name, mitk::DataTreeIteratorBase* dataIt) :
QObject(parent, name), m_Available(false), m_Activated(false), m_DataTreeIterator(NULL), m_TreeChangedWhileInActive(false), m_ObserverTag(0)
{
setDataTree(dataIt);
}
QmitkFunctionality::~QmitkFunctionality()
{
}
QString QmitkFunctionality::getFunctionalityName()
{
return name();
}
void QmitkFunctionality::activated()
{
m_Activated = true;
if(m_TreeChangedWhileInActive)
{
treeChanged();
m_TreeChangedWhileInActive = false;
}
}
void QmitkFunctionality::deactivated()
{
m_Activated = false;
}
bool QmitkFunctionality::isActivated()
{
return m_Activated;
}
bool QmitkFunctionality::isAvailable()
{
return m_Available;
}
void QmitkFunctionality::setAvailability(bool available)
{
this->m_Available=available;
emit availabilityChanged(this);
emit availabilityChanged();
}
void QmitkFunctionality::setDataTree(mitk::DataTreeIteratorBase* it)
{
if(m_DataTreeIterator.IsNotNull()! )
{
m_DataTreeIterator->GetTree()->RemoveObserver(m_ObserverTag);
}
m_DataTreeIterator = it;
if(m_DataTreeIterator.IsNotNull())
{
itk::ReceptorMemberCommand<QmitkFunctionality>::Pointer command = itk::ReceptorMemberCommand<QmitkFunctionality>::New();
command->SetCallbackFunction(this, &QmitkFunctionality::treeChanged);
m_ObserverTag = m_DataTreeIterator->GetTree()->AddObserver(itk::TreeChangeEvent<mitk::DataTreeBase>(), command);
}
}
mitk::DataTreeIteratorBase* QmitkFunctionality::getDataTree()
{
return m_DataTreeIterator.GetPointer();
}
void QmitkFunctionality::treeChanged(const itk::EventObject & treeChangedEvent)
{
if(isActivated())
{
m_TreeChangedWhileInActive = false;
treeChanged();
}
else
m_TreeChangedWhileInActive = true;
}
void QmitkFunctionality::treeChanged()
{
}
<commit_msg>FIX: bug during warning fix<commit_after>#include "QmitkFunctionality.h"
#include <qlcdnumber.h>
#include <qslider.h>
#include <itkCommand.h>
QmitkFunctionality::QmitkFunctionality(QObject *parent, const char *name, mitk::DataTreeIteratorBase* dataIt) :
QObject(parent, name), m_Available(false), m_Activated(false), m_DataTreeIterator(NULL), m_TreeChangedWhileInActive(false), m_ObserverTag(0)
{
setDataTree(dataIt);
}
QmitkFunctionality::~QmitkFunctionality()
{
}
QString QmitkFunctionality::getFunctionalityName()
{
return name();
}
void QmitkFunctionality::activated()
{
m_Activated = true;
if(m_TreeChangedWhileInActive)
{
treeChanged();
m_TreeChangedWhileInActive = false;
}
}
void QmitkFunctionality::deactivated()
{
m_Activated = false;
}
bool QmitkFunctionality::isActivated()
{
return m_Activated;
}
bool QmitkFunctionality::isAvailable()
{
return m_Available;
}
void QmitkFunctionality::setAvailability(bool available)
{
this->m_Available=available;
emit availabilityChanged(this);
emit availabilityChanged();
}
void QmitkFunctionality::setDataTree(mitk::DataTreeIteratorBase* it)
{
if(m_DataTreeIterator.IsNotNull() )
{
m_DataTreeIterator->GetTree()->RemoveObserver(m_ObserverTag);
}
m_DataTreeIterator = it;
if(m_DataTreeIterator.IsNotNull())
{
itk::ReceptorMemberCommand<QmitkFunctionality>::Pointer command = itk::ReceptorMemberCommand<QmitkFunctionality>::New();
command->SetCallbackFunction(this, &QmitkFunctionality::treeChanged);
m_ObserverTag = m_DataTreeIterator->GetTree()->AddObserver(itk::TreeChangeEvent<mitk::DataTreeBase>(), command);
}
}
mitk::DataTreeIteratorBase* QmitkFunctionality::getDataTree()
{
return m_DataTreeIterator.GetPointer();
}
void QmitkFunctionality::treeChanged(const itk::EventObject & treeChangedEvent)
{
if(isActivated())
{
m_TreeChangedWhileInActive = false;
treeChanged();
}
else
m_TreeChangedWhileInActive = true;
}
void QmitkFunctionality::treeChanged()
{
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
struct SplitnetsWorker
{
std::map<RTLIL::Wire*, std::vector<RTLIL::Wire*>> splitmap;
void operator()(RTLIL::SigSpec &sig)
{
sig.expand();
for (auto &c : sig.chunks)
if (splitmap.count(c.wire) > 0) {
c.wire = splitmap.at(c.wire).at(c.offset);
c.offset = 0;
}
sig.optimize();
}
};
struct SplitnetsPass : public Pass {
SplitnetsPass() : Pass("splitnets", "split up multi-bit nets") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" splitnets [options] [selection]\n");
log("\n");
log("This command splits multi-bit nets into single-bit nets.\n");
log("\n");
log(" -ports\n");
log(" also split module ports. per default only internal signals are split.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
bool flag_ports = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-ports") {
flag_ports = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto &mod_it : design->modules)
{
RTLIL::Module *module = mod_it.second;
if (!design->selected(module))
continue;
SplitnetsWorker worker;
for (auto &w : module->wires) {
RTLIL::Wire *wire = w.second;
if (wire->width > 1 && (wire->port_id == 0 || flag_ports))
worker.splitmap[wire] = std::vector<RTLIL::Wire*>();
}
for (auto &it : worker.splitmap)
for (int i = 0; i < it.first->width; i++) {
RTLIL::Wire *wire = new RTLIL::Wire;
wire->port_id = it.first->port_id;
wire->port_input = it.first->port_input;
wire->port_output = it.first->port_output;
wire->name = it.first->name + stringf("[%d]", i);
while (module->count_id(wire->name) > 0)
wire->name = wire->name + "_";
module->add(wire);
it.second.push_back(wire);
}
module->rewrite_sigspecs(worker);
for (auto &it : worker.splitmap) {
module->wires.erase(it.first->name);
delete it.first;
}
module->fixup_ports();
}
}
} SplitnetsPass;
<commit_msg>Added -format option to splitnets<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
struct SplitnetsWorker
{
std::map<RTLIL::Wire*, std::vector<RTLIL::Wire*>> splitmap;
void operator()(RTLIL::SigSpec &sig)
{
sig.expand();
for (auto &c : sig.chunks)
if (splitmap.count(c.wire) > 0) {
c.wire = splitmap.at(c.wire).at(c.offset);
c.offset = 0;
}
sig.optimize();
}
};
struct SplitnetsPass : public Pass {
SplitnetsPass() : Pass("splitnets", "split up multi-bit nets") { }
virtual void help()
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" splitnets [options] [selection]\n");
log("\n");
log("This command splits multi-bit nets into single-bit nets.\n");
log("\n");
log(" -format char1[char2]\n");
log(" the first char is inserted between the net name and the bit index, the\n");
log(" second char is appended to the netname. e.g. -format () creates net\n");
log(" names like 'mysignal(42)'. the default is '[]'.\n");
log("\n");
log(" -ports\n");
log(" also split module ports. per default only internal signals are split.\n");
log("\n");
}
virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
{
bool flag_ports = false;
std::string format = "[]";
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-format" && argidx+1 < args.size()) {
format = args[++argidx];
continue;
}
if (args[argidx] == "-ports") {
flag_ports = true;
continue;
}
break;
}
extra_args(args, argidx, design);
for (auto &mod_it : design->modules)
{
RTLIL::Module *module = mod_it.second;
if (!design->selected(module))
continue;
SplitnetsWorker worker;
for (auto &w : module->wires) {
RTLIL::Wire *wire = w.second;
if (wire->width > 1 && (wire->port_id == 0 || flag_ports))
worker.splitmap[wire] = std::vector<RTLIL::Wire*>();
}
for (auto &it : worker.splitmap)
for (int i = 0; i < it.first->width; i++) {
RTLIL::Wire *wire = new RTLIL::Wire;
wire->port_id = it.first->port_id;
wire->port_input = it.first->port_input;
wire->port_output = it.first->port_output;
wire->name = it.first->name;
if (format.size() > 0)
wire->name += format.substr(0, 1);
wire->name += stringf("%d", i);
if (format.size() > 0)
wire->name += format.substr(1);
while (module->count_id(wire->name) > 0)
wire->name = wire->name + "_";
module->add(wire);
it.second.push_back(wire);
}
module->rewrite_sigspecs(worker);
for (auto &it : worker.splitmap) {
module->wires.erase(it.first->name);
delete it.first;
}
module->fixup_ports();
}
}
} SplitnetsPass;
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// Copyright (C) 2014 Glenn Smith
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/time.h>
#include "io.h"
#include "types.h"
#include "dif.h"
#include <SDL2/SDL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <glm/matrix.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/vec3.hpp>
//TRIGGER WARNING: LOTS OF GLOBAL VARIABLES. I BET "NOBODY" WOULD LOVE THIS.
U32 gDifCount;
DIF **gDifs;
U32 gTriangleCount;
Triangle *gTriangles;
bool gRunning;
SDL_Window *gWindow;
SDL_GLContext gContext;
GLfloat gAngle;
float gYaw, gPitch;
glm::vec3 gCameraPosition;
static float gCameraSpeed = 0.1f;
static float gMovementSpeed = 0.2f;
bool mouseButtons[3] = {false, false, false};
bool movement[4] = {false, false, false, false};
void render() {
//Load the model matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_CULL_FACE);
//Camera
glm::mat4x4 cameraMatrix = glm::mat4x4(1);
cameraMatrix = glm::rotate(cameraMatrix, gPitch, glm::vec3(1, 0, 0));
cameraMatrix = glm::rotate(cameraMatrix, gYaw, glm::vec3(0, 1, 0));
cameraMatrix = glm::translate(cameraMatrix, gCameraPosition);
glLoadMatrixf(&cameraMatrix[0][0]);
//Clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0, 0, 0, -1.0f);
//Actual rendering is here (GL 1.1 in a 2.1 context. Take THAT, good practice!)
//TODO: VBOs
glBegin(GL_TRIANGLES);
for (U32 i = 0; i < gTriangleCount; i ++) {
glColor4f(gTriangles[i].color.red, gTriangles[i].color.green, gTriangles[i].color.blue, gTriangles[i].color.alpha);
glNormal3f(gTriangles[i].normal.x, gTriangles[i].normal.z, gTriangles[i].normal.y);
//Lazy, also wrong because Torque swaps y/z
glVertex3f(gTriangles[i].point0.x, gTriangles[i].point0.z, -gTriangles[i].point0.y);
glVertex3f(gTriangles[i].point1.x, gTriangles[i].point1.z, -gTriangles[i].point1.y);
glVertex3f(gTriangles[i].point2.x, gTriangles[i].point2.z, -gTriangles[i].point2.y);
}
glEnd();
glDisable(GL_CULL_FACE);
}
void loop() {
//Basic movement
glm::mat4x4 delta = glm::mat4x4(1);
delta = glm::rotate(delta, -gYaw, glm::vec3(0, 1, 0));
delta = glm::rotate(delta, -gPitch, glm::vec3(1, 0, 0));
float speed = gMovementSpeed;
if (mouseButtons[1])
speed *= 2.f;
if (movement[0]) delta = glm::translate(delta, glm::vec3(0, 0, speed));
if (movement[1]) delta = glm::translate(delta, glm::vec3(0, 0, -speed));
if (movement[2]) delta = glm::translate(delta, glm::vec3(speed, 0, 0));
if (movement[3]) delta = glm::translate(delta, glm::vec3(-speed, 0, 0));
gCameraPosition += glm::vec3(delta[3]);
}
bool initGL() {
//Initialize clear color
glClearColor(0.f, 0.f, 0.f, 1.f);
glClearDepth(1.0f);
//Enable and set some shit for rendering
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glShadeModel(GL_SMOOTH);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
//Window size for viewport
int w, h;
SDL_GetWindowSize(gWindow, &w, &h);
GLfloat aspect = (GLfloat)w / (GLfloat)h;
glViewport(0, 0, w, h);
//Initialize Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.0f, aspect, 0.1f, 1000.f);
return glGetError() == GL_NO_ERROR;
}
void handleEvent(SDL_Event *event) {
//Quit
if (event->type == SDL_QUIT) {
gRunning = false;
}
//Window resize
if (event->type == SDL_WINDOWEVENT) {
//Just reinit (lazy)
initGL();
}
//Key events, movement
if (event->type == SDL_KEYDOWN) {
switch (((SDL_KeyboardEvent *)event)->keysym.scancode) {
//Same for Colemak...
case SDL_SCANCODE_W: movement[0] = true; break;
case SDL_SCANCODE_S: movement[1] = true; break;
case SDL_SCANCODE_A: movement[2] = true; break;
case SDL_SCANCODE_D: movement[3] = true; break;
}
} else if (event->type == SDL_KEYUP) {
switch (((SDL_KeyboardEvent *)event)->keysym.scancode) {
case SDL_SCANCODE_W: movement[0] = false; break;
case SDL_SCANCODE_S: movement[1] = false; break;
case SDL_SCANCODE_A: movement[2] = false; break;
case SDL_SCANCODE_D: movement[3] = false; break;
}
}
//Mouse for rotation
if (event->type == SDL_MOUSEMOTION) {
gYaw += (GLfloat)((SDL_MouseMotionEvent *)event)->xrel * gCameraSpeed;
gPitch += (GLfloat)((SDL_MouseMotionEvent *)event)->yrel * gCameraSpeed;
}
if (event->type == SDL_MOUSEBUTTONDOWN) {
mouseButtons[((SDL_MouseButtonEvent *)event)->button] = true;
} else if (event->type == SDL_MOUSEBUTTONUP) {
mouseButtons[((SDL_MouseButtonEvent *)event)->button] = false;
}
}
bool init() {
//Load our map into triangles (global var warning)
gTriangles = interior_generate_triangles(gDifs[0]->interior[0], &gTriangleCount);
gRunning = true;
//Init SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
return false;
}
//Use OpenGL 2.1
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_Rect bounds;
SDL_GetDisplayBounds(0, &bounds);
//Create the window
if ((gWindow = SDL_CreateWindow("DIF Viewer", (bounds.w - 1280) / 2, (bounds.h - 720) / 2, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE)) == NULL) {
return false;
}
//Create context
if ((gContext = SDL_GL_CreateContext(gWindow)) == NULL) {
return false;
}
//Use Vsync
if (SDL_GL_SetSwapInterval(1) < 0) {
return false;
}
//Lock cursor
SDL_SetRelativeMouseMode(SDL_TRUE);
//Initialize OpenGL
if (!initGL()) {
return false;
}
return true;
}
void cleanup() {
//Destroy the SDL
SDL_Quit();
}
void run() {
//Init SDL
if (!init()) {
exit(-1);
}
SDL_Event event;
//Main loop
while (gRunning) {
//Profiling
struct timeval startTime, endTime;
gettimeofday(&startTime, NULL);
//Input
while (SDL_PollEvent(&event)) {
handleEvent(&event);
}
//Hard work
loop();
render();
//Flip buffers
SDL_GL_SwapWindow(gWindow);
//Profiling
gettimeofday(&endTime, NULL);
long long start = startTime.tv_usec + (startTime.tv_sec * 1000000ULL);
long long end = endTime.tv_usec + (endTime.tv_sec * 1000000ULL);
// printf("%f FPS, %f mspf\n", (1000.f / ((double)(end - start) / 1000.0f)), ((double)(end - start) / 1000.0f));
}
//Clean up (duh)
cleanup();
}
int main(int argc, const char * argv[])
{
//Usage prompt
if (argc < 2) {
printf("Usage: %s <file>\n", argv[0]);
return 1;
}
gDifCount = 0;
gDifs = (DIF **)malloc(sizeof(DIF *) * (argc - 1));
for (U32 i = 0; i < (argc - 1); i ++) {
//Open file
FILE *file = fopen(argv[i + 1], "r");
//Read the .dif
gDifs[i] = dif_read_file(file);
if (gDifs[i]) {
gDifCount ++;
}
//Clean up
fclose(file);
}
FILE *test = fopen(argv[2], "w");
interior_export_obj(gDifs[0]->interior[0], test);
fclose(test);
}
//Init SDL and go!
run();
//Clean up
for (U32 i = 0; i < gDifCount; i ++) {
dif_release(gDifs[i]);
}
free(gDifs);
return 0;
}
<commit_msg>Add -o arg<commit_after>//------------------------------------------------------------------------------
// Copyright (C) 2014 Glenn Smith
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/time.h>
#include "io.h"
#include "types.h"
#include "dif.h"
#include <SDL2/SDL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <glm/matrix.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/vec3.hpp>
//TRIGGER WARNING: LOTS OF GLOBAL VARIABLES. I BET "NOBODY" WOULD LOVE THIS.
U32 gDifCount;
DIF **gDifs;
U32 gTriangleCount;
Triangle *gTriangles;
bool gRunning;
SDL_Window *gWindow;
SDL_GLContext gContext;
GLfloat gAngle;
float gYaw, gPitch;
glm::vec3 gCameraPosition;
static float gCameraSpeed = 0.1f;
static float gMovementSpeed = 0.2f;
bool mouseButtons[3] = {false, false, false};
bool movement[4] = {false, false, false, false};
void render() {
//Load the model matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_CULL_FACE);
//Camera
glm::mat4x4 cameraMatrix = glm::mat4x4(1);
cameraMatrix = glm::rotate(cameraMatrix, gPitch, glm::vec3(1, 0, 0));
cameraMatrix = glm::rotate(cameraMatrix, gYaw, glm::vec3(0, 1, 0));
cameraMatrix = glm::translate(cameraMatrix, gCameraPosition);
glLoadMatrixf(&cameraMatrix[0][0]);
//Clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0, 0, 0, -1.0f);
//Actual rendering is here (GL 1.1 in a 2.1 context. Take THAT, good practice!)
//TODO: VBOs
glBegin(GL_TRIANGLES);
for (U32 i = 0; i < gTriangleCount; i ++) {
glColor4f(gTriangles[i].color.red, gTriangles[i].color.green, gTriangles[i].color.blue, gTriangles[i].color.alpha);
glNormal3f(gTriangles[i].normal.x, gTriangles[i].normal.z, gTriangles[i].normal.y);
//Lazy, also wrong because Torque swaps y/z
glVertex3f(gTriangles[i].point0.x, gTriangles[i].point0.z, -gTriangles[i].point0.y);
glVertex3f(gTriangles[i].point1.x, gTriangles[i].point1.z, -gTriangles[i].point1.y);
glVertex3f(gTriangles[i].point2.x, gTriangles[i].point2.z, -gTriangles[i].point2.y);
}
glEnd();
glDisable(GL_CULL_FACE);
}
void loop() {
//Basic movement
glm::mat4x4 delta = glm::mat4x4(1);
delta = glm::rotate(delta, -gYaw, glm::vec3(0, 1, 0));
delta = glm::rotate(delta, -gPitch, glm::vec3(1, 0, 0));
float speed = gMovementSpeed;
if (mouseButtons[1])
speed *= 2.f;
if (movement[0]) delta = glm::translate(delta, glm::vec3(0, 0, speed));
if (movement[1]) delta = glm::translate(delta, glm::vec3(0, 0, -speed));
if (movement[2]) delta = glm::translate(delta, glm::vec3(speed, 0, 0));
if (movement[3]) delta = glm::translate(delta, glm::vec3(-speed, 0, 0));
gCameraPosition += glm::vec3(delta[3]);
}
bool initGL() {
//Initialize clear color
glClearColor(0.f, 0.f, 0.f, 1.f);
glClearDepth(1.0f);
//Enable and set some shit for rendering
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glShadeModel(GL_SMOOTH);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
//Window size for viewport
int w, h;
SDL_GetWindowSize(gWindow, &w, &h);
GLfloat aspect = (GLfloat)w / (GLfloat)h;
glViewport(0, 0, w, h);
//Initialize Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.0f, aspect, 0.1f, 1000.f);
return glGetError() == GL_NO_ERROR;
}
void handleEvent(SDL_Event *event) {
//Quit
if (event->type == SDL_QUIT) {
gRunning = false;
}
//Window resize
if (event->type == SDL_WINDOWEVENT) {
//Just reinit (lazy)
initGL();
}
//Key events, movement
if (event->type == SDL_KEYDOWN) {
switch (((SDL_KeyboardEvent *)event)->keysym.scancode) {
//Same for Colemak...
case SDL_SCANCODE_W: movement[0] = true; break;
case SDL_SCANCODE_S: movement[1] = true; break;
case SDL_SCANCODE_A: movement[2] = true; break;
case SDL_SCANCODE_D: movement[3] = true; break;
}
} else if (event->type == SDL_KEYUP) {
switch (((SDL_KeyboardEvent *)event)->keysym.scancode) {
case SDL_SCANCODE_W: movement[0] = false; break;
case SDL_SCANCODE_S: movement[1] = false; break;
case SDL_SCANCODE_A: movement[2] = false; break;
case SDL_SCANCODE_D: movement[3] = false; break;
}
}
//Mouse for rotation
if (event->type == SDL_MOUSEMOTION) {
gYaw += (GLfloat)((SDL_MouseMotionEvent *)event)->xrel * gCameraSpeed;
gPitch += (GLfloat)((SDL_MouseMotionEvent *)event)->yrel * gCameraSpeed;
}
if (event->type == SDL_MOUSEBUTTONDOWN) {
mouseButtons[((SDL_MouseButtonEvent *)event)->button] = true;
} else if (event->type == SDL_MOUSEBUTTONUP) {
mouseButtons[((SDL_MouseButtonEvent *)event)->button] = false;
}
}
bool init() {
//Load our map into triangles (global var warning)
gTriangles = interior_generate_triangles(gDifs[0]->interior[0], &gTriangleCount);
gRunning = true;
//Init SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
return false;
}
//Use OpenGL 2.1
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_Rect bounds;
SDL_GetDisplayBounds(0, &bounds);
//Create the window
if ((gWindow = SDL_CreateWindow("DIF Viewer", (bounds.w - 1280) / 2, (bounds.h - 720) / 2, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE)) == NULL) {
return false;
}
//Create context
if ((gContext = SDL_GL_CreateContext(gWindow)) == NULL) {
return false;
}
//Use Vsync
if (SDL_GL_SetSwapInterval(1) < 0) {
return false;
}
//Lock cursor
SDL_SetRelativeMouseMode(SDL_TRUE);
//Initialize OpenGL
if (!initGL()) {
return false;
}
return true;
}
void cleanup() {
//Destroy the SDL
SDL_Quit();
}
void run() {
//Init SDL
if (!init()) {
exit(-1);
}
SDL_Event event;
//Main loop
while (gRunning) {
//Profiling
struct timeval startTime, endTime;
gettimeofday(&startTime, NULL);
//Input
while (SDL_PollEvent(&event)) {
handleEvent(&event);
}
//Hard work
loop();
render();
//Flip buffers
SDL_GL_SwapWindow(gWindow);
//Profiling
gettimeofday(&endTime, NULL);
long long start = startTime.tv_usec + (startTime.tv_sec * 1000000ULL);
long long end = endTime.tv_usec + (endTime.tv_sec * 1000000ULL);
// printf("%f FPS, %f mspf\n", (1000.f / ((double)(end - start) / 1000.0f)), ((double)(end - start) / 1000.0f));
}
//Clean up (duh)
cleanup();
}
int main(int argc, const char * argv[])
{
//Usage prompt
if (argc < 2) {
printf("Usage: %s <file>\n", argv[0]);
return 1;
}
U32 argstart = 1;
if (!strcmp(argv[1], "-o")) {
argstart += 2;
}
gDifCount = 0;
gDifs = (DIF **)malloc(sizeof(DIF *) * (argc - argstart));
for (U32 i = 0; i < (argc - argstart); i ++) {
//Open file
FILE *file = fopen(argv[i + argstart], "r");
//Read the .dif
gDifs[i] = dif_read_file(file);
if (gDifs[i]) {
gDifCount ++;
}
//Clean up
fclose(file);
}
if (!strcmp(argv[1], "-o")) {
FILE *test = fopen(argv[2], "w");
interior_export_obj(gDifs[0]->interior[0], test);
fclose(test);
} else {
//Init SDL and go!
run();
}
//Clean up
for (U32 i = 0; i < gDifCount; i ++) {
dif_release(gDifs[i]);
}
free(gDifs);
return 0;
}
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_APP_CONN_HPP
#define SRS_APP_CONN_HPP
/*
#include <srs_app_conn.hpp>
*/
#include <srs_core.hpp>
#include <string>
#include <srs_app_st.hpp>
#include <srs_app_thread.hpp>
#include <srs_protocol_kbps.hpp>
class SrsConnection;
/**
* the manager for connection.
*/
class IConnectionManager
{
public:
IConnectionManager();
virtual ~IConnectionManager();
public:
/**
* remove the specified connection.
*/
virtual void remove(SrsConnection* c) = 0;
};
/**
* the basic connection of SRS,
* all connections accept from listener must extends from this base class,
* server will add the connection to manager, and delete it when remove.
*/
class SrsConnection : public virtual ISrsOneCycleThreadHandler, public virtual IKbpsDelta
{
private:
/**
* each connection start a green thread,
* when thread stop, the connection will be delete by server.
*/
SrsOneCycleThread* pthread;
/**
* the id of connection.
*/
int id;
protected:
/**
* the manager object to manage the connection.
*/
IConnectionManager* manager;
/**
* the underlayer st fd handler.
*/
st_netfd_t stfd;
/**
* the ip of client.
*/
std::string ip;
/**
* whether the connection is disposed,
* when disposed, connection should stop cycle and cleanup itself.
*/;
bool disposed;
public:
SrsConnection(IConnectionManager* cm, st_netfd_t c);
virtual ~SrsConnection();
public:
/**
* to dipose the connection.
*/
virtual void dispose();
/**
* start the client green thread.
* when server get a client from listener,
* 1. server will create an concrete connection(for instance, RTMP connection),
* 2. then add connection to its connection manager,
* 3. start the client thread by invoke this start()
* when client cycle thread stop, invoke the on_thread_stop(), which will use server
* to remove the client by server->remove(this).
*/
virtual int start();
// interface ISrsOneCycleThreadHandler
public:
/**
* the thread cycle function,
* when serve connection completed, terminate the loop which will terminate the thread,
* thread will invoke the on_thread_stop() when it terminated.
*/
virtual int cycle();
/**
* when the thread cycle finished, thread will invoke the on_thread_stop(),
* which will remove self from server, server will remove the connection from manager
* then delete the connection.
*/
virtual void on_thread_stop();
public:
/**
* get the srs id which identify the client.
*/
virtual int srs_id();
protected:
/**
* for concrete connection to do the cycle.
*/
virtual int do_cycle() = 0;
};
#endif
<commit_msg>fix typo of code.<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_APP_CONN_HPP
#define SRS_APP_CONN_HPP
/*
#include <srs_app_conn.hpp>
*/
#include <srs_core.hpp>
#include <string>
#include <srs_app_st.hpp>
#include <srs_app_thread.hpp>
#include <srs_protocol_kbps.hpp>
class SrsConnection;
/**
* the manager for connection.
*/
class IConnectionManager
{
public:
IConnectionManager();
virtual ~IConnectionManager();
public:
/**
* remove the specified connection.
*/
virtual void remove(SrsConnection* c) = 0;
};
/**
* the basic connection of SRS,
* all connections accept from listener must extends from this base class,
* server will add the connection to manager, and delete it when remove.
*/
class SrsConnection : public virtual ISrsOneCycleThreadHandler, public virtual IKbpsDelta
{
private:
/**
* each connection start a green thread,
* when thread stop, the connection will be delete by server.
*/
SrsOneCycleThread* pthread;
/**
* the id of connection.
*/
int id;
protected:
/**
* the manager object to manage the connection.
*/
IConnectionManager* manager;
/**
* the underlayer st fd handler.
*/
st_netfd_t stfd;
/**
* the ip of client.
*/
std::string ip;
/**
* whether the connection is disposed,
* when disposed, connection should stop cycle and cleanup itself.
*/
bool disposed;
public:
SrsConnection(IConnectionManager* cm, st_netfd_t c);
virtual ~SrsConnection();
public:
/**
* to dipose the connection.
*/
virtual void dispose();
/**
* start the client green thread.
* when server get a client from listener,
* 1. server will create an concrete connection(for instance, RTMP connection),
* 2. then add connection to its connection manager,
* 3. start the client thread by invoke this start()
* when client cycle thread stop, invoke the on_thread_stop(), which will use server
* to remove the client by server->remove(this).
*/
virtual int start();
// interface ISrsOneCycleThreadHandler
public:
/**
* the thread cycle function,
* when serve connection completed, terminate the loop which will terminate the thread,
* thread will invoke the on_thread_stop() when it terminated.
*/
virtual int cycle();
/**
* when the thread cycle finished, thread will invoke the on_thread_stop(),
* which will remove self from server, server will remove the connection from manager
* then delete the connection.
*/
virtual void on_thread_stop();
public:
/**
* get the srs id which identify the client.
*/
virtual int srs_id();
protected:
/**
* for concrete connection to do the cycle.
*/
virtual int do_cycle() = 0;
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#include <limits>
#include <cctype>
#include <cstdio>
#include <sstream>
#include "snphandler.h"
using namespace std;
using namespace hal;
SNPHandler::SNPHandler(SideGraph* sideGraph, bool caseSensitive)
: _caseSens(caseSensitive), _sg(sideGraph), _snpCount(0)
{
}
SNPHandler::~SNPHandler()
{
// simple way of making sure we don't delete same pointer twice:
// add to a set first.
set<SNPList*> snpSet;
for (SNPMap::iterator i = _snpMap.begin(); i != _snpMap.end(); ++i)
{
snpSet.insert(i->second);
}
for (set<SNPList*>::iterator i = snpSet.begin(); i != snpSet.end(); ++i)
{
delete *i;
}
}
pair<SGSide, SGSide> SNPHandler::createSNP(const string& srcDNA,
const string& tgtDNA,
size_t dnaOffset,
size_t dnaLength,
const Sequence* halSrcSequence,
const SGPosition& srcPos,
const SGPosition& tgtPos,
bool reverseMap,
SGLookup* srcLookup,
SequenceMapBack* seqMapBack)
{
cout << "\ncreateSNP " << srcDNA << " " << dnaOffset << "," << dnaLength
<< endl;
vector<SGPosition> sgPositions(dnaLength);
// note : should use hints / cache to speed up consecutive bases
// but start simple for baseline tests
// first we use the snp structure to find out if any of the SNPs we
// want to add already exist. If they do, we update sgPositions
SGPosition tgt(tgtPos);
for (sg_int_t i = 0; i < dnaLength; ++i)
{
char srcVal = srcDNA[i + dnaOffset];
char tgtVal = !reverseMap ? tgtDNA[i + dnaOffset] : reverseComplement(
tgtDNA[tgtDNA.length() - 1 - dnaOffset - i]);
if (reverseMap == false)
{
tgt.setPos(tgtPos.getPos() + i);
}
else
{
tgt.setPos(tgtPos.getPos() - i);
}
cout << "findSNP " << tgt << "," << srcVal
<< " = " << findSNP(tgt, srcVal)
<< " i=" << i << ", tgtPos=" << tgtPos << " rm " << reverseMap << endl;
sgPositions[i] = findSNP(tgt, srcVal);
// if empty slot, we add base from tgt but dont need to
// create / update any other structures.
if (sgPositions[i] == SideGraph::NullPos &&
findSNP(tgt, tgtVal) == SideGraph::NullPos)
{
assert(srcVal != tgtVal);
cout << "addtgtSNP " << SGPosition(tgtPos.getSeqID(), tgt.getPos())
<< " , " << tgtVal << " , "
<< SGPosition(tgtPos.getSeqID(), tgt.getPos()) << endl;
addSNP(SGPosition(tgtPos.getSeqID(), tgt.getPos()),
tgtVal,
SGPosition(tgtPos.getSeqID(), tgt.getPos()));
}
}
// now we have a position for all existing snps in the graph. any
// positions that are "null" means we need to add new sequences to
// cover them. We create the sequences and joins here and add them
// to the side graph. We also update sgPositions with these new
// coordinates.
SGSide prevHook;
string nameBuf;
for (sg_int_t i = 0; i < dnaLength; ++i)
{
if (sgPositions[i] == SideGraph::NullPos)
{
sg_int_t j = i + 1;
for (; j < dnaLength && sgPositions[j] == SideGraph::NullPos; ++j);
--j;
getSNPName(halSrcSequence, srcPos, i, j - i + 1, reverseMap, nameBuf);
const SGSequence* newSeq;
newSeq = _sg->addSequence(new SGSequence(-1, j - i + 1, nameBuf));
cout << "create snp seq " << *newSeq << endl;
_snpCount += newSeq->getLength();
if (i > 0)
{
SGJoin* inJoin = new SGJoin(prevHook,
SGSide(SGPosition(newSeq->getID(), 0),
false));
if (reverseMap == true)
{
inJoin->swap();
}
_sg->addJoin(inJoin);
}
if (j < dnaLength - 1)
{
SGSide tgtSide(sgPositions[j+1], false);
SGJoin* outJoin = new SGJoin(
SGSide(SGPosition(newSeq->getID(), newSeq->getLength() -1), true),
tgtSide);
if (reverseMap == true)
{
outJoin->swap();
}
_sg->addJoin(outJoin);
}
prevHook.setBase(SGPosition(newSeq->getID(), newSeq->getLength() - 1));
prevHook.setForward(true);
for (sg_int_t k = i; k <= j; ++k)
{
sgPositions[k].setSeqID(newSeq->getID());
sgPositions[k].setPos(k - i);
sg_int_t tgtCoord = tgtPos.getPos() + (!reverseMap ? k : -k);
cout << "addSNP " << SGPosition(tgtPos.getSeqID(), tgtCoord)
<< " , " << srcDNA[dnaOffset + k] << " , "
<< sgPositions[k] << endl;
addSNP(SGPosition(tgtPos.getSeqID(), tgtCoord),
srcDNA[dnaOffset + k],
sgPositions[k]);
}
i = j;
}
else
{
prevHook.setBase(sgPositions[i]);
prevHook.setForward(true);
}
}
// now the side graph is updated, and sgPositions
// finally we update the srcLookup for every snp, to make sure that
// we always map to the right base (ie when using the lookup structure
// to compute paths for the input
for (sg_int_t i = 0; i < dnaLength; ++i)
{
sg_int_t j = i + 1;
while (j < dnaLength && sgPositions[j].getSeqID() ==
sgPositions[j-1].getSeqID() &&
sgPositions[j].getPos() ==
sgPositions[j-1].getPos() + 1)
{
++j;
}
SGPosition pos = srcPos;
pos.setPos(srcPos.getPos() + i);
srcLookup->addInterval(pos, sgPositions[i], j - i, false);
// keep record of where it came from (ie to trace back from the side graph
// to hal
seqMapBack->insert(
pair<const SGSequence*, pair<const Sequence*, hal_index_t> >(
_sg->getSequence(sgPositions[i].getSeqID()),
pair<const Sequence*, hal_index_t>(halSrcSequence, pos.getPos())));
i = j - 1;
}
// return hooks at either end to be joined by calling code to rest of
// graph
pair<SGSide, SGSide> outHooks;
outHooks.first.setBase(sgPositions[0]);
outHooks.first.setForward(false);
outHooks.second.setBase(sgPositions[sgPositions.size() - 1]);
outHooks.second.setForward(true);
return outHooks;
}
const SGPosition& SNPHandler::findSNP(const SGPosition& pos, char nuc)
{
if (_caseSens == false)
{
nuc = toupper(nuc);
}
if (pos != _cachePos)
{
pair<SNPMap::iterator, bool> ins = _snpMap.insert(
pair<SGPosition, SNPList*>(pos, NULL));
_cacheIt = ins.first;
_cachePos = pos;
}
SNPList* snpList = _cacheIt->second;
if (snpList != NULL)
{
for (SNPList::iterator i = snpList->begin(); i != snpList->end(); ++i)
{
if (i->_nuc == nuc)
{
return i->_pos;
}
}
}
return SideGraph::NullPos;
}
void SNPHandler::addSNP(const SGPosition& pos, char nuc,
const SGPosition& snpPosition)
{
assert(findSNP(pos, nuc) == SideGraph::NullPos);
if (_caseSens == false)
{
nuc = toupper(nuc);
}
if (pos != _cachePos)
{
pair<SNPMap::iterator, bool> ins = _snpMap.insert(
pair<SGPosition, SNPList*>(pos, NULL));
_cacheIt = ins.first;
_cachePos = pos;
}
if (_cacheIt->second == NULL)
{
_cacheIt->second = new SNPList();
}
SNPList* snpList = _cacheIt->second;
snpList->push_back(SNP(snpPosition, nuc));
// add new position into the handler
if (pos != snpPosition)
{
assert(_snpMap.find(snpPosition) == _snpMap.end());
_snpMap.insert(pair<SGPosition, SNPList*>(snpPosition, snpList));
}
}
void SNPHandler::getSNPName(const Sequence* halSrcSequence,
const SGPosition& srcPos,
sg_int_t offset, sg_int_t length,
bool reverseMap, string& outName) const
{
stringstream ss;
if (halSrcSequence != NULL)
{
// unit tests sometimes dont bother with a hal sequence so we
// let it be optional here.
ss << halSrcSequence->getFullName();
}
ss << "_SNP_" << (srcPos.getPos() + offset) << "_" << length;
outName = ss.str();
}
<commit_msg>take SNP out of snp sequence name to make cactus camel output look consistent<commit_after>/*
* Copyright (C) 2015 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#include <limits>
#include <cctype>
#include <cstdio>
#include <sstream>
#include "snphandler.h"
using namespace std;
using namespace hal;
SNPHandler::SNPHandler(SideGraph* sideGraph, bool caseSensitive)
: _caseSens(caseSensitive), _sg(sideGraph), _snpCount(0)
{
}
SNPHandler::~SNPHandler()
{
// simple way of making sure we don't delete same pointer twice:
// add to a set first.
set<SNPList*> snpSet;
for (SNPMap::iterator i = _snpMap.begin(); i != _snpMap.end(); ++i)
{
snpSet.insert(i->second);
}
for (set<SNPList*>::iterator i = snpSet.begin(); i != snpSet.end(); ++i)
{
delete *i;
}
}
pair<SGSide, SGSide> SNPHandler::createSNP(const string& srcDNA,
const string& tgtDNA,
size_t dnaOffset,
size_t dnaLength,
const Sequence* halSrcSequence,
const SGPosition& srcPos,
const SGPosition& tgtPos,
bool reverseMap,
SGLookup* srcLookup,
SequenceMapBack* seqMapBack)
{
cout << "\ncreateSNP " << srcDNA << " " << dnaOffset << "," << dnaLength
<< endl;
vector<SGPosition> sgPositions(dnaLength);
// note : should use hints / cache to speed up consecutive bases
// but start simple for baseline tests
// first we use the snp structure to find out if any of the SNPs we
// want to add already exist. If they do, we update sgPositions
SGPosition tgt(tgtPos);
for (sg_int_t i = 0; i < dnaLength; ++i)
{
char srcVal = srcDNA[i + dnaOffset];
char tgtVal = !reverseMap ? tgtDNA[i + dnaOffset] : reverseComplement(
tgtDNA[tgtDNA.length() - 1 - dnaOffset - i]);
if (reverseMap == false)
{
tgt.setPos(tgtPos.getPos() + i);
}
else
{
tgt.setPos(tgtPos.getPos() - i);
}
cout << "findSNP " << tgt << "," << srcVal
<< " = " << findSNP(tgt, srcVal)
<< " i=" << i << ", tgtPos=" << tgtPos << " rm " << reverseMap << endl;
sgPositions[i] = findSNP(tgt, srcVal);
// if empty slot, we add base from tgt but dont need to
// create / update any other structures.
if (sgPositions[i] == SideGraph::NullPos &&
findSNP(tgt, tgtVal) == SideGraph::NullPos)
{
assert(srcVal != tgtVal);
cout << "addtgtSNP " << SGPosition(tgtPos.getSeqID(), tgt.getPos())
<< " , " << tgtVal << " , "
<< SGPosition(tgtPos.getSeqID(), tgt.getPos()) << endl;
addSNP(SGPosition(tgtPos.getSeqID(), tgt.getPos()),
tgtVal,
SGPosition(tgtPos.getSeqID(), tgt.getPos()));
}
}
// now we have a position for all existing snps in the graph. any
// positions that are "null" means we need to add new sequences to
// cover them. We create the sequences and joins here and add them
// to the side graph. We also update sgPositions with these new
// coordinates.
SGSide prevHook;
string nameBuf;
for (sg_int_t i = 0; i < dnaLength; ++i)
{
if (sgPositions[i] == SideGraph::NullPos)
{
sg_int_t j = i + 1;
for (; j < dnaLength && sgPositions[j] == SideGraph::NullPos; ++j);
--j;
getSNPName(halSrcSequence, srcPos, i, j - i + 1, reverseMap, nameBuf);
const SGSequence* newSeq;
newSeq = _sg->addSequence(new SGSequence(-1, j - i + 1, nameBuf));
cout << "create snp seq " << *newSeq << endl;
_snpCount += newSeq->getLength();
if (i > 0)
{
SGJoin* inJoin = new SGJoin(prevHook,
SGSide(SGPosition(newSeq->getID(), 0),
false));
if (reverseMap == true)
{
inJoin->swap();
}
_sg->addJoin(inJoin);
}
if (j < dnaLength - 1)
{
SGSide tgtSide(sgPositions[j+1], false);
SGJoin* outJoin = new SGJoin(
SGSide(SGPosition(newSeq->getID(), newSeq->getLength() -1), true),
tgtSide);
if (reverseMap == true)
{
outJoin->swap();
}
_sg->addJoin(outJoin);
}
prevHook.setBase(SGPosition(newSeq->getID(), newSeq->getLength() - 1));
prevHook.setForward(true);
for (sg_int_t k = i; k <= j; ++k)
{
sgPositions[k].setSeqID(newSeq->getID());
sgPositions[k].setPos(k - i);
sg_int_t tgtCoord = tgtPos.getPos() + (!reverseMap ? k : -k);
cout << "addSNP " << SGPosition(tgtPos.getSeqID(), tgtCoord)
<< " , " << srcDNA[dnaOffset + k] << " , "
<< sgPositions[k] << endl;
addSNP(SGPosition(tgtPos.getSeqID(), tgtCoord),
srcDNA[dnaOffset + k],
sgPositions[k]);
}
i = j;
}
else
{
prevHook.setBase(sgPositions[i]);
prevHook.setForward(true);
}
}
// now the side graph is updated, and sgPositions
// finally we update the srcLookup for every snp, to make sure that
// we always map to the right base (ie when using the lookup structure
// to compute paths for the input
for (sg_int_t i = 0; i < dnaLength; ++i)
{
sg_int_t j = i + 1;
while (j < dnaLength && sgPositions[j].getSeqID() ==
sgPositions[j-1].getSeqID() &&
sgPositions[j].getPos() ==
sgPositions[j-1].getPos() + 1)
{
++j;
}
SGPosition pos = srcPos;
pos.setPos(srcPos.getPos() + i);
srcLookup->addInterval(pos, sgPositions[i], j - i, false);
// keep record of where it came from (ie to trace back from the side graph
// to hal
seqMapBack->insert(
pair<const SGSequence*, pair<const Sequence*, hal_index_t> >(
_sg->getSequence(sgPositions[i].getSeqID()),
pair<const Sequence*, hal_index_t>(halSrcSequence, pos.getPos())));
i = j - 1;
}
// return hooks at either end to be joined by calling code to rest of
// graph
pair<SGSide, SGSide> outHooks;
outHooks.first.setBase(sgPositions[0]);
outHooks.first.setForward(false);
outHooks.second.setBase(sgPositions[sgPositions.size() - 1]);
outHooks.second.setForward(true);
return outHooks;
}
const SGPosition& SNPHandler::findSNP(const SGPosition& pos, char nuc)
{
if (_caseSens == false)
{
nuc = toupper(nuc);
}
if (pos != _cachePos)
{
pair<SNPMap::iterator, bool> ins = _snpMap.insert(
pair<SGPosition, SNPList*>(pos, NULL));
_cacheIt = ins.first;
_cachePos = pos;
}
SNPList* snpList = _cacheIt->second;
if (snpList != NULL)
{
for (SNPList::iterator i = snpList->begin(); i != snpList->end(); ++i)
{
if (i->_nuc == nuc)
{
return i->_pos;
}
}
}
return SideGraph::NullPos;
}
void SNPHandler::addSNP(const SGPosition& pos, char nuc,
const SGPosition& snpPosition)
{
assert(findSNP(pos, nuc) == SideGraph::NullPos);
if (_caseSens == false)
{
nuc = toupper(nuc);
}
if (pos != _cachePos)
{
pair<SNPMap::iterator, bool> ins = _snpMap.insert(
pair<SGPosition, SNPList*>(pos, NULL));
_cacheIt = ins.first;
_cachePos = pos;
}
if (_cacheIt->second == NULL)
{
_cacheIt->second = new SNPList();
}
SNPList* snpList = _cacheIt->second;
snpList->push_back(SNP(snpPosition, nuc));
// add new position into the handler
if (pos != snpPosition)
{
assert(_snpMap.find(snpPosition) == _snpMap.end());
_snpMap.insert(pair<SGPosition, SNPList*>(snpPosition, snpList));
}
}
void SNPHandler::getSNPName(const Sequence* halSrcSequence,
const SGPosition& srcPos,
sg_int_t offset, sg_int_t length,
bool reverseMap, string& outName) const
{
stringstream ss;
if (halSrcSequence != NULL)
{
// unit tests sometimes dont bother with a hal sequence so we
// let it be optional here.
ss << halSrcSequence->getFullName();
}
ss << "_" << (srcPos.getPos() + offset) << "_" << length;
outName = ss.str();
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
#include "grins/inc_navier_stokes_bc_handling.h"
namespace GRINS
{
IncompressibleNavierStokesBCHandling::IncompressibleNavierStokesBCHandling(const std::string& physics_name,
const GetPot& input)
: BCHandlingBase(physics_name)
{
_u_var_name = input("Physics/VariableNames/u_velocity", u_var_name_default );
_v_var_name = input("Physics/VariableNames/v_velocity", v_var_name_default );
_w_var_name = input("Physics/VariableNames/w_velocity", w_var_name_default );
std::string id_str = "Physics/"+_physics_name+"/bc_ids";
std::string bc_str = "Physics/"+_physics_name+"/bc_types";
this->read_bc_data( input, id_str, bc_str );
return;
}
IncompressibleNavierStokesBCHandling::~IncompressibleNavierStokesBCHandling()
{
return;
}
int IncompressibleNavierStokesBCHandling::string_to_int( const std::string& bc_type ) const
{
int bc_type_out;
if( bc_type == "no_slip" )
bc_type_out = NO_SLIP;
else if( bc_type == "prescribed_vel" )
bc_type_out = PRESCRIBED_VELOCITY;
else if( bc_type == "parabolic_profile" )
bc_type_out = PARABOLIC_PROFILE;
else if( bc_type == "general_velocity" )
bc_type_out = GENERAL_VELOCITY;
else
{
// Call base class to detect any physics-common boundary conditions
bc_type_out = BCHandlingBase::string_to_int( bc_type );
}
return bc_type_out;
}
void IncompressibleNavierStokesBCHandling::init_bc_data( const BoundaryID bc_id,
const std::string& bc_id_string,
const int bc_type,
const GetPot& input )
{
switch(bc_type)
{
case(NO_SLIP):
{
this->set_dirichlet_bc_type( bc_id, bc_type );
}
break;
case(PRESCRIBED_VELOCITY):
{
this->set_dirichlet_bc_type( bc_id, bc_type );
/* Force the user to specify 3 velocity components regardless of dimension.
This should make it easier to keep things correct if we want to have
2D flow not be in the x-y plane. */
int n_vel_comps = input.vector_variable_size("Physics/"+_physics_name+"/bound_vel_"+bc_id_string);
if( n_vel_comps != 3 )
{
std::cerr << "Error: Must specify 3 velocity components when inputting"
<< std::endl
<< " prescribed velocities. Found " << n_vel_comps
<< " velocity components."
<< std::endl;
libmesh_error();
}
this->set_dirichlet_bc_value( bc_id,
input("Physics/"+_physics_name+"/bound_vel_"+bc_id_string, 0.0, 0 ),
0 );
this->set_dirichlet_bc_value( bc_id,
input("Physics/"+_physics_name+"/bound_vel_"+bc_id_string, 0.0, 1 ),
1 );
this->set_dirichlet_bc_value( bc_id,
input("Physics/"+_physics_name+"/bound_vel_"+bc_id_string, 0.0, 2 ),
2 );
}
break;
case(PARABOLIC_PROFILE):
{
this->set_dirichlet_bc_type( bc_id, bc_type );
// Make sure all 6 components are there
if( input.vector_variable_size("Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string) != 6 )
{
std::cerr << "Error: Must specify 6 components when inputting"
<< std::endl
<< " coefficients for a parabolic profile. Found "
<< input.vector_variable_size("Physics/"+_physics_name+"/parabolic_profile_"+bc_id_string)
<< " components."
<< std::endl;
libmesh_error();
}
Real a = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 0 );
Real b = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 1 );
Real c = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 2 );
Real d = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 3 );
Real e = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 4 );
Real f = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 5 );
std::string var = input( "Physics/"+_physics_name+"/parabolic_profile_var_"+bc_id_string, "DIE!" );
DBCContainer cont;
cont.add_var_name( var );
cont.add_bc_id( bc_id );
std::tr1::shared_ptr<libMesh::FunctionBase<Number> > func( new ParabolicProfile(a,b,c,d,e,f) );
cont.set_func( func );
this->attach_dirichlet_bound_func( cont );
// Set specified components of Dirichlet data to zero
std::string fix_var = input( "Physics/"+_physics_name+"/parabolic_profile_fix_"+bc_id_string, "DIE!" );
DBCContainer cont_fix;
cont_fix.add_var_name( fix_var );
cont_fix.add_bc_id( bc_id );
std::tr1::shared_ptr<libMesh::FunctionBase<Number> > func_fix( new ZeroFunction<Number>() );
cont_fix.set_func( func_fix );
this->attach_dirichlet_bound_func( cont_fix );
}
break;
case(GENERAL_VELOCITY):
{
this->set_dirichlet_bc_type( bc_id, bc_type );
}
break;
default:
{
// Call base class to detect any physics-common boundary conditions
BCHandlingBase::init_bc_data( bc_id, bc_id_string, bc_type, input );
}
} // End switch(bc_type)
return;
}
void IncompressibleNavierStokesBCHandling::user_init_dirichlet_bcs( libMesh::FEMSystem* system,
libMesh::DofMap& dof_map,
BoundaryID bc_id,
BCType bc_type ) const
{
int dim = system->get_mesh().mesh_dimension();
VariableIndex u_var = system->variable_number( _u_var_name );
VariableIndex v_var = system->variable_number( _v_var_name );
VariableIndex w_var;
if( dim == 3 )
w_var = system->variable_number( _w_var_name );
switch( bc_type )
{
case(NO_SLIP):
{
std::set<BoundaryID> dbc_ids;
dbc_ids.insert(bc_id);
std::vector<VariableIndex> dbc_vars;
dbc_vars.push_back(u_var);
dbc_vars.push_back(v_var);
if(dim == 3)
dbc_vars.push_back(w_var);
ZeroFunction<Number> zero;
libMesh::DirichletBoundary no_slip_dbc(dbc_ids,
dbc_vars,
&zero );
dof_map.add_dirichlet_boundary( no_slip_dbc );
}
break;
case(PRESCRIBED_VELOCITY):
{
std::set<BoundaryID> dbc_ids;
dbc_ids.insert(bc_id);
std::vector<VariableIndex> dbc_vars;
// This is inefficient, but it shouldn't matter because
// everything gets cached on the libMesh side so it should
// only affect performance at startup.
{
dbc_vars.push_back(u_var);
ConstFunction<Number> vel_func( this->get_dirichlet_bc_value(bc_id,0) );
libMesh::DirichletBoundary vel_dbc(dbc_ids,
dbc_vars,
&vel_func );
dof_map.add_dirichlet_boundary( vel_dbc );
dbc_vars.clear();
}
{
dbc_vars.push_back(v_var);
ConstFunction<Number> vel_func( this->get_dirichlet_bc_value(bc_id,1) );
libMesh::DirichletBoundary vel_dbc(dbc_ids,
dbc_vars,
&vel_func );
dof_map.add_dirichlet_boundary( vel_dbc );
dbc_vars.clear();
}
if( dim == 3 )
{
dbc_vars.push_back(w_var);
ConstFunction<Number> vel_func( this->get_dirichlet_bc_value(bc_id,2) );
libMesh::DirichletBoundary vel_dbc(dbc_ids,
dbc_vars,
&vel_func );
dof_map.add_dirichlet_boundary( vel_dbc );
}
}
break;
case(PARABOLIC_PROFILE):
// This case is handled init_dirichlet_bc_func_objs
break;
case(GENERAL_VELOCITY):
// This case is handled in the init_dirichlet_bc_func_objs
break;
default:
{
std::cerr << "Invalid BCType " << bc_type << std::endl;
libmesh_error();
}
}// end switch
return;
}
} // namespace GRINS
<commit_msg>[GRINS]: Some helpful error messages.<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
#include "grins/inc_navier_stokes_bc_handling.h"
namespace GRINS
{
IncompressibleNavierStokesBCHandling::IncompressibleNavierStokesBCHandling(const std::string& physics_name,
const GetPot& input)
: BCHandlingBase(physics_name)
{
_u_var_name = input("Physics/VariableNames/u_velocity", u_var_name_default );
_v_var_name = input("Physics/VariableNames/v_velocity", v_var_name_default );
_w_var_name = input("Physics/VariableNames/w_velocity", w_var_name_default );
std::string id_str = "Physics/"+_physics_name+"/bc_ids";
std::string bc_str = "Physics/"+_physics_name+"/bc_types";
this->read_bc_data( input, id_str, bc_str );
return;
}
IncompressibleNavierStokesBCHandling::~IncompressibleNavierStokesBCHandling()
{
return;
}
int IncompressibleNavierStokesBCHandling::string_to_int( const std::string& bc_type ) const
{
int bc_type_out;
if( bc_type == "no_slip" )
bc_type_out = NO_SLIP;
else if( bc_type == "prescribed_vel" )
bc_type_out = PRESCRIBED_VELOCITY;
else if( bc_type == "parabolic_profile" )
bc_type_out = PARABOLIC_PROFILE;
else if( bc_type == "general_velocity" )
bc_type_out = GENERAL_VELOCITY;
else
{
// Call base class to detect any physics-common boundary conditions
bc_type_out = BCHandlingBase::string_to_int( bc_type );
}
return bc_type_out;
}
void IncompressibleNavierStokesBCHandling::init_bc_data( const BoundaryID bc_id,
const std::string& bc_id_string,
const int bc_type,
const GetPot& input )
{
switch(bc_type)
{
case(NO_SLIP):
{
this->set_dirichlet_bc_type( bc_id, bc_type );
}
break;
case(PRESCRIBED_VELOCITY):
{
this->set_dirichlet_bc_type( bc_id, bc_type );
/* Force the user to specify 3 velocity components regardless of dimension.
This should make it easier to keep things correct if we want to have
2D flow not be in the x-y plane. */
int n_vel_comps = input.vector_variable_size("Physics/"+_physics_name+"/bound_vel_"+bc_id_string);
if( n_vel_comps != 3 )
{
std::cerr << "Error: Must specify 3 velocity components when inputting"
<< std::endl
<< " prescribed velocities. Found " << n_vel_comps
<< " velocity components."
<< std::endl;
libmesh_error();
}
this->set_dirichlet_bc_value( bc_id,
input("Physics/"+_physics_name+"/bound_vel_"+bc_id_string, 0.0, 0 ),
0 );
this->set_dirichlet_bc_value( bc_id,
input("Physics/"+_physics_name+"/bound_vel_"+bc_id_string, 0.0, 1 ),
1 );
this->set_dirichlet_bc_value( bc_id,
input("Physics/"+_physics_name+"/bound_vel_"+bc_id_string, 0.0, 2 ),
2 );
}
break;
case(PARABOLIC_PROFILE):
{
this->set_dirichlet_bc_type( bc_id, bc_type );
// Make sure all 6 components are there
if( input.vector_variable_size("Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string) != 6 )
{
std::cerr << "Error: Must specify 6 components when inputting"
<< std::endl
<< " coefficients for a parabolic profile. Found "
<< input.vector_variable_size("Physics/"+_physics_name+"/parabolic_profile_"+bc_id_string)
<< " components."
<< std::endl;
libmesh_error();
}
Real a = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 0 );
Real b = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 1 );
Real c = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 2 );
Real d = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 3 );
Real e = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 4 );
Real f = input( "Physics/"+_physics_name+"/parabolic_profile_coeffs_"+bc_id_string, 0.0, 5 );
std::string var = input( "Physics/"+_physics_name+"/parabolic_profile_var_"+bc_id_string, "DIE!" );
if( var == "DIE!" )
{
std::cerr << "Error: Mush specify a variable name to which apply parabolic profile through parabolic_profile_var input option." << std::endl;
libmesh_error();
}
DBCContainer cont;
cont.add_var_name( var );
cont.add_bc_id( bc_id );
std::tr1::shared_ptr<libMesh::FunctionBase<Number> > func( new ParabolicProfile(a,b,c,d,e,f) );
cont.set_func( func );
this->attach_dirichlet_bound_func( cont );
// Set specified components of Dirichlet data to zero
std::string fix_var = input( "Physics/"+_physics_name+"/parabolic_profile_fix_"+bc_id_string, "DIE!" );
if( fix_var == "DIE!" )
{
std::cerr << "Error: Mush specify a variable name to fix for parabolic profile through parabolic_profile_fix input option." << std::endl;
libmesh_error();
}
DBCContainer cont_fix;
cont_fix.add_var_name( fix_var );
cont_fix.add_bc_id( bc_id );
std::tr1::shared_ptr<libMesh::FunctionBase<Number> > func_fix( new ZeroFunction<Number>() );
cont_fix.set_func( func_fix );
this->attach_dirichlet_bound_func( cont_fix );
}
break;
case(GENERAL_VELOCITY):
{
this->set_dirichlet_bc_type( bc_id, bc_type );
}
break;
default:
{
// Call base class to detect any physics-common boundary conditions
BCHandlingBase::init_bc_data( bc_id, bc_id_string, bc_type, input );
}
} // End switch(bc_type)
return;
}
void IncompressibleNavierStokesBCHandling::user_init_dirichlet_bcs( libMesh::FEMSystem* system,
libMesh::DofMap& dof_map,
BoundaryID bc_id,
BCType bc_type ) const
{
int dim = system->get_mesh().mesh_dimension();
VariableIndex u_var = system->variable_number( _u_var_name );
VariableIndex v_var = system->variable_number( _v_var_name );
VariableIndex w_var;
if( dim == 3 )
w_var = system->variable_number( _w_var_name );
switch( bc_type )
{
case(NO_SLIP):
{
std::set<BoundaryID> dbc_ids;
dbc_ids.insert(bc_id);
std::vector<VariableIndex> dbc_vars;
dbc_vars.push_back(u_var);
dbc_vars.push_back(v_var);
if(dim == 3)
dbc_vars.push_back(w_var);
ZeroFunction<Number> zero;
libMesh::DirichletBoundary no_slip_dbc(dbc_ids,
dbc_vars,
&zero );
dof_map.add_dirichlet_boundary( no_slip_dbc );
}
break;
case(PRESCRIBED_VELOCITY):
{
std::set<BoundaryID> dbc_ids;
dbc_ids.insert(bc_id);
std::vector<VariableIndex> dbc_vars;
// This is inefficient, but it shouldn't matter because
// everything gets cached on the libMesh side so it should
// only affect performance at startup.
{
dbc_vars.push_back(u_var);
ConstFunction<Number> vel_func( this->get_dirichlet_bc_value(bc_id,0) );
libMesh::DirichletBoundary vel_dbc(dbc_ids,
dbc_vars,
&vel_func );
dof_map.add_dirichlet_boundary( vel_dbc );
dbc_vars.clear();
}
{
dbc_vars.push_back(v_var);
ConstFunction<Number> vel_func( this->get_dirichlet_bc_value(bc_id,1) );
libMesh::DirichletBoundary vel_dbc(dbc_ids,
dbc_vars,
&vel_func );
dof_map.add_dirichlet_boundary( vel_dbc );
dbc_vars.clear();
}
if( dim == 3 )
{
dbc_vars.push_back(w_var);
ConstFunction<Number> vel_func( this->get_dirichlet_bc_value(bc_id,2) );
libMesh::DirichletBoundary vel_dbc(dbc_ids,
dbc_vars,
&vel_func );
dof_map.add_dirichlet_boundary( vel_dbc );
}
}
break;
case(PARABOLIC_PROFILE):
// This case is handled init_dirichlet_bc_func_objs
break;
case(GENERAL_VELOCITY):
// This case is handled in the init_dirichlet_bc_func_objs
break;
default:
{
std::cerr << "Invalid BCType " << bc_type << std::endl;
libmesh_error();
}
}// end switch
return;
}
} // namespace GRINS
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2016-2019 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "pico_bench/pico_bench.h"
#include "ospapp/OSPApp.h"
#include "common/sg/SceneGraph.h"
#include "ospcommon/utility/SaveImage.h"
#include "sg/Renderer.h"
#include "sg/common/FrameBuffer.h"
namespace ospray {
namespace app {
struct OSPBenchmark : public OSPApp
{
OSPBenchmark();
private:
void render(const std::shared_ptr<sg::Frame> &) override;
int parseCommandLine(int &ac, const char **&av) override;
template <typename T>
void outputStats(const T &stats);
size_t numWarmupFrames = 10;
size_t numBenchFrames = 100;
std::string imageOutputFile = "";
};
OSPBenchmark::OSPBenchmark()
{
addPlane = false; // NOTE(jda) - override default behavior, can still
// force on/off via standard command-line
// options
}
void OSPBenchmark::render(const std::shared_ptr<sg::Frame> &root)
{
for (size_t i = 0; i < numWarmupFrames; ++i)
root->renderFrame();
// NOTE(jda) - allow 0 bench frames to enable testing only data load times
if (numBenchFrames <= 0)
return;
auto benchmarker =
pico_bench::Benchmarker<std::chrono::milliseconds>{ numBenchFrames };
auto stats = benchmarker([&]() {
root->renderFrame();
// TODO: measure just ospRenderFrame() time from within ospray_sg
// return std::chrono::milliseconds{500};
});
if (!imageOutputFile.empty()) {
auto fb = root->child("frameBuffer").nodeAs<sg::FrameBuffer>();
auto *srcPB = (const uint32_t *)fb->map();
utility::writePPM(imageOutputFile + ".ppm", width, height, srcPB);
fb->unmap(srcPB);
}
outputStats(stats);
}
int OSPBenchmark::parseCommandLine(int &ac, const char **&av)
{
for (int i = 1; i < ac; i++) {
const std::string arg = av[i];
if (arg == "-i" || arg == "--image") {
imageOutputFile = av[i + 1];
removeArgs(ac, av, i, 2);
--i;
} else if (arg == "-wf" || arg == "--warmup") {
numWarmupFrames = atoi(av[i + 1]);
removeArgs(ac, av, i, 2);
--i;
} else if (arg == "-bf" || arg == "--bench") {
numBenchFrames = atoi(av[i + 1]);
removeArgs(ac, av, i, 2);
--i;
}
}
return 0;
}
// NOTE(jda) - Issues with template type deduction w/ GCC 7.1 and Clang 4.0,
// thus defining the use of operator<<() from pico_bench here
// before OSPCommon.h (offending file) gets eventually included
// through ospray_sg headers. [blech]
template <typename T>
void OSPBenchmark::outputStats(const T &stats)
{
std::cout << stats << std::endl;
}
} // ::ospray::app
} // ::ospray
int main(int ac, const char **av)
{
ospray::app::OSPBenchmark ospApp;
return ospApp.main(ac, av);
}
<commit_msg>Generate pfm image file when framebuffer is in float format.<commit_after>// ======================================================================== //
// Copyright 2016-2019 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "pico_bench/pico_bench.h"
#include "ospapp/OSPApp.h"
#include "common/sg/SceneGraph.h"
#include "ospcommon/utility/SaveImage.h"
#include "sg/Renderer.h"
#include "sg/common/FrameBuffer.h"
namespace ospray {
namespace app {
struct OSPBenchmark : public OSPApp
{
OSPBenchmark();
private:
void render(const std::shared_ptr<sg::Frame> &) override;
int parseCommandLine(int &ac, const char **&av) override;
template <typename T>
void outputStats(const T &stats);
size_t numWarmupFrames = 10;
size_t numBenchFrames = 100;
std::string imageOutputFile = "";
};
OSPBenchmark::OSPBenchmark()
{
addPlane = false; // NOTE(jda) - override default behavior, can still
// force on/off via standard command-line
// options
}
void OSPBenchmark::render(const std::shared_ptr<sg::Frame> &root)
{
for (size_t i = 0; i < numWarmupFrames; ++i)
root->renderFrame();
// NOTE(jda) - allow 0 bench frames to enable testing only data load times
if (numBenchFrames <= 0)
return;
auto benchmarker =
pico_bench::Benchmarker<std::chrono::milliseconds>{ numBenchFrames };
auto stats = benchmarker([&]() {
root->renderFrame();
// TODO: measure just ospRenderFrame() time from within ospray_sg
// return std::chrono::milliseconds{500};
});
if (!imageOutputFile.empty()) {
auto fb = root->child("frameBuffer").nodeAs<sg::FrameBuffer>();
auto *srcPB = (const uint32_t *)fb->map();
if (fb->format() == OSP_FB_RGBA32F)
utility::writePFM(imageOutputFile + ".pfm", width, height, (vec4f*)srcPB);
else
utility::writePPM(imageOutputFile + ".ppm", width, height, srcPB);
fb->unmap(srcPB);
}
outputStats(stats);
}
int OSPBenchmark::parseCommandLine(int &ac, const char **&av)
{
for (int i = 1; i < ac; i++) {
const std::string arg = av[i];
if (arg == "-i" || arg == "--image") {
imageOutputFile = av[i + 1];
removeArgs(ac, av, i, 2);
--i;
} else if (arg == "-wf" || arg == "--warmup") {
numWarmupFrames = atoi(av[i + 1]);
removeArgs(ac, av, i, 2);
--i;
} else if (arg == "-bf" || arg == "--bench") {
numBenchFrames = atoi(av[i + 1]);
removeArgs(ac, av, i, 2);
--i;
}
}
return 0;
}
// NOTE(jda) - Issues with template type deduction w/ GCC 7.1 and Clang 4.0,
// thus defining the use of operator<<() from pico_bench here
// before OSPCommon.h (offending file) gets eventually included
// through ospray_sg headers. [blech]
template <typename T>
void OSPBenchmark::outputStats(const T &stats)
{
std::cout << stats << std::endl;
}
} // ::ospray::app
} // ::ospray
int main(int ac, const char **av)
{
ospray::app::OSPBenchmark ospApp;
return ospApp.main(ac, av);
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "c11log/formatters/formatters.h"
#include "c11log/level.h"
void c11log::formatters::format_time(const c11log::formatters::timepoint& tp, std::ostream &dest)
{
std::tm tm = details::os::localtime(std::chrono::system_clock::to_time_t(tp));
//get ms
//auto duration = tp.time_since_epoch();
//int millis = static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() % 1000);
char buf[64];
auto size = sprintf(buf, "[%d-%02d-%02d %02d:%02d:%02d]",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
dest.write(buf, size);
}
void c11log::formatters::format_time(std::ostream& dest)
{
return format_time(std::chrono::system_clock::now(), dest);
}
static const char _hex_chars[17] = "0123456789ABCDEF";
std::string c11log::formatters::to_hex(const unsigned char* buf, std::size_t size)
{
std::ostringstream oss;
for (std::size_t i = 0; i < size; i++) {
oss << _hex_chars[buf[i] >> 4];
oss << _hex_chars[buf[i] & 0x0F];
}
return oss.str();
}
<commit_msg>timestamp caching of last second<commit_after>#include "stdafx.h"
#include <memory.h>
#include "c11log/formatters/formatters.h"
#include "c11log/level.h"
static thread_local std::tm last_tm;
static thread_local char timestamp_cache[64];
void c11log::formatters::format_time(const c11log::formatters::timepoint& tp, std::ostream &dest)
{
auto tm = details::os::localtime(std::chrono::system_clock::to_time_t(tp));
// Cache timestamp string of last second
if(memcmp(&tm, &last_tm, sizeof(tm)))
{
sprintf(timestamp_cache, "[%d-%02d-%02d %02d:%02d:%02d]", tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec);
last_tm = tm;
}
dest << timestamp_cache;
}
void c11log::formatters::format_time(std::ostream& dest)
{
return format_time(std::chrono::system_clock::now(), dest);
}
static const char _hex_chars[17] = "0123456789ABCDEF";
std::string c11log::formatters::to_hex(const unsigned char* buf, std::size_t size)
{
std::ostringstream oss;
for (std::size_t i = 0; i < size; i++) {
oss << _hex_chars[buf[i] >> 4];
oss << _hex_chars[buf[i] & 0x0F];
}
return oss.str();
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file brw_wm_vector_splitting.cpp
*
* If a vector is only ever referenced by its components, then
* split those components out to individual variables so they can be
* handled normally by other optimization passes.
*
* This skips vectors in uniforms and varyings, which need to be
* accessible as vectors for their access by the GL. Also, vector
* results of non-variable-derefs in assignments aren't handled
* because to do so we would have to store the vector result to a
* temporary in order to unload each channel, and to do so would just
* loop us back to where we started. For the 965, this is exactly the
* behavior we want for the results of texture lookups, but probably not for
*/
extern "C" {
#include "main/core.h"
#include "intel_context.h"
}
#include "../glsl/ir.h"
#include "../glsl/ir_visitor.h"
#include "../glsl/ir_print_visitor.h"
#include "../glsl/ir_rvalue_visitor.h"
#include "../glsl/glsl_types.h"
static bool debug = false;
class variable_entry : public exec_node
{
public:
variable_entry(ir_variable *var)
{
this->var = var;
this->whole_vector_access = 0;
this->declaration = false;
this->mem_ctx = NULL;
}
ir_variable *var; /* The key: the variable's pointer. */
/** Number of times the variable is referenced, including assignments. */
unsigned whole_vector_access;
bool declaration; /* If the variable had a decl in the instruction stream */
ir_variable *components[4];
/** talloc_parent(this->var) -- the shader's talloc context. */
void *mem_ctx;
};
class ir_vector_reference_visitor : public ir_hierarchical_visitor {
public:
ir_vector_reference_visitor(void)
{
this->mem_ctx = talloc_new(NULL);
this->variable_list.make_empty();
}
~ir_vector_reference_visitor(void)
{
talloc_free(mem_ctx);
}
virtual ir_visitor_status visit(ir_variable *);
virtual ir_visitor_status visit(ir_dereference_variable *);
virtual ir_visitor_status visit_enter(ir_swizzle *);
virtual ir_visitor_status visit_enter(ir_assignment *);
virtual ir_visitor_status visit_enter(ir_function_signature *);
variable_entry *get_variable_entry(ir_variable *var);
/* List of variable_entry */
exec_list variable_list;
void *mem_ctx;
};
variable_entry *
ir_vector_reference_visitor::get_variable_entry(ir_variable *var)
{
assert(var);
if (!var->type->is_vector())
return NULL;
switch (var->mode) {
case ir_var_uniform:
case ir_var_in:
case ir_var_out:
case ir_var_inout:
/* Can't split varyings or uniforms. Function in/outs won't get split
* either, so don't care about the ambiguity.
*/
return NULL;
case ir_var_auto:
case ir_var_temporary:
break;
}
foreach_iter(exec_list_iterator, iter, this->variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (entry->var == var)
return entry;
}
variable_entry *entry = new(mem_ctx) variable_entry(var);
this->variable_list.push_tail(entry);
return entry;
}
ir_visitor_status
ir_vector_reference_visitor::visit(ir_variable *ir)
{
variable_entry *entry = this->get_variable_entry(ir);
if (entry)
entry->declaration = true;
return visit_continue;
}
ir_visitor_status
ir_vector_reference_visitor::visit(ir_dereference_variable *ir)
{
ir_variable *const var = ir->var;
variable_entry *entry = this->get_variable_entry(var);
if (entry)
entry->whole_vector_access++;
return visit_continue;
}
ir_visitor_status
ir_vector_reference_visitor::visit_enter(ir_swizzle *ir)
{
/* Don't descend into a vector ir_dereference_variable below. */
if (ir->val->as_dereference_variable() && ir->type->is_scalar())
return visit_continue_with_parent;
return visit_continue;
}
ir_visitor_status
ir_vector_reference_visitor::visit_enter(ir_assignment *ir)
{
if (ir->lhs->as_dereference_variable() &&
ir->rhs->as_dereference_variable() &&
!ir->condition) {
/* We'll split copies of a vector to copies of channels, so don't
* descend to the ir_dereference_variables.
*/
return visit_continue_with_parent;
}
if (ir->lhs->as_dereference_variable() &&
is_power_of_two(ir->write_mask) &&
!ir->condition) {
/* If we're writing just a channel, then channel-splitting the LHS is OK.
*/
ir->rhs->accept(this);
return visit_continue_with_parent;
}
return visit_continue;
}
ir_visitor_status
ir_vector_reference_visitor::visit_enter(ir_function_signature *ir)
{
/* We don't want to descend into the function parameters and
* split them, so just accept the body here.
*/
visit_list_elements(this, &ir->body);
return visit_continue_with_parent;
}
class ir_vector_splitting_visitor : public ir_rvalue_visitor {
public:
ir_vector_splitting_visitor(exec_list *vars)
{
this->variable_list = vars;
}
virtual ir_visitor_status visit_leave(ir_assignment *);
void handle_rvalue(ir_rvalue **rvalue);
struct variable_entry *get_splitting_entry(ir_variable *var);
exec_list *variable_list;
void *mem_ctx;
};
struct variable_entry *
ir_vector_splitting_visitor::get_splitting_entry(ir_variable *var)
{
assert(var);
if (!var->type->is_vector())
return NULL;
foreach_iter(exec_list_iterator, iter, *this->variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (entry->var == var) {
return entry;
}
}
return NULL;
}
void
ir_vector_splitting_visitor::handle_rvalue(ir_rvalue **rvalue)
{
if (!*rvalue)
return;
ir_swizzle *swiz = (*rvalue)->as_swizzle();
if (!swiz || !swiz->type->is_scalar())
return;
ir_dereference_variable *deref_var = swiz->val->as_dereference_variable();
if (!deref_var)
return;
variable_entry *entry = get_splitting_entry(deref_var->var);
if (!entry)
return;
ir_variable *var = entry->components[swiz->mask.x];
*rvalue = new(entry->mem_ctx) ir_dereference_variable(var);
}
ir_visitor_status
ir_vector_splitting_visitor::visit_leave(ir_assignment *ir)
{
ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();
ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();
variable_entry *lhs = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;
variable_entry *rhs = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;
if (lhs_deref && rhs_deref && (lhs || rhs) && !ir->condition) {
/* Straight assignment of vector variables. */
for (unsigned int i = 0; i < ir->rhs->type->vector_elements; i++) {
ir_dereference *new_lhs;
ir_rvalue *new_rhs;
void *mem_ctx = lhs ? lhs->mem_ctx : rhs->mem_ctx;
unsigned int writemask;
if (!(ir->write_mask & (1 << i)))
continue;
if (lhs) {
new_lhs = new(mem_ctx) ir_dereference_variable(lhs->components[i]);
writemask = 1;
} else {
new_lhs = ir->lhs->clone(mem_ctx, NULL);
writemask = 1 << i;
}
if (rhs) {
new_rhs = new(mem_ctx) ir_dereference_variable(rhs->components[i]);
} else {
new_rhs = new(mem_ctx) ir_swizzle(ir->rhs->clone(mem_ctx, NULL),
i, i, i, i, 1);
}
ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,
new_rhs,
NULL, writemask));
}
ir->remove();
} else if (lhs) {
int elem = -1;
switch (ir->write_mask) {
case (1 << 0):
elem = 0;
break;
case (1 << 1):
elem = 1;
break;
case (1 << 2):
elem = 2;
break;
case (1 << 3):
elem = 3;
break;
default:
ir->print();
assert(!"not reached: non-channelwise dereference of LHS.");
}
ir->lhs = new(mem_ctx) ir_dereference_variable(lhs->components[elem]);
ir->write_mask = (1 << 0);
handle_rvalue(&ir->rhs);
ir->rhs = new(mem_ctx) ir_swizzle(ir->rhs,
elem, elem, elem, elem, 1);
} else {
handle_rvalue(&ir->rhs);
}
handle_rvalue(&ir->condition);
return visit_continue;
}
extern "C" {
bool
brw_do_vector_splitting(exec_list *instructions)
{
ir_vector_reference_visitor refs;
visit_list_elements(&refs, instructions);
/* Trim out variables we can't split. */
foreach_iter(exec_list_iterator, iter, refs.variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (debug) {
printf("vector %s@%p: decl %d, whole_access %d\n",
entry->var->name, (void *) entry->var, entry->declaration,
entry->whole_vector_access);
}
if (!entry->declaration || entry->whole_vector_access) {
entry->remove();
}
}
if (refs.variable_list.is_empty())
return false;
void *mem_ctx = talloc_new(NULL);
/* Replace the decls of the vectors to be split with their split
* components.
*/
foreach_iter(exec_list_iterator, iter, refs.variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
const struct glsl_type *type;
type = glsl_type::get_instance(entry->var->type->base_type, 1, 1);
entry->mem_ctx = talloc_parent(entry->var);
for (unsigned int i = 0; i < entry->var->type->vector_elements; i++) {
const char *name = talloc_asprintf(mem_ctx, "%s_%c",
entry->var->name,
"xyzw"[i]);
entry->components[i] = new(entry->mem_ctx) ir_variable(type, name,
ir_var_temporary);
entry->var->insert_before(entry->components[i]);
}
entry->var->remove();
}
ir_vector_splitting_visitor split(&refs.variable_list);
visit_list_elements(&split, instructions);
talloc_free(mem_ctx);
return true;
}
}
<commit_msg>i965: Remove swizzling of assignment to vector-splitting single-channel LHS.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file brw_wm_vector_splitting.cpp
*
* If a vector is only ever referenced by its components, then
* split those components out to individual variables so they can be
* handled normally by other optimization passes.
*
* This skips vectors in uniforms and varyings, which need to be
* accessible as vectors for their access by the GL. Also, vector
* results of non-variable-derefs in assignments aren't handled
* because to do so we would have to store the vector result to a
* temporary in order to unload each channel, and to do so would just
* loop us back to where we started. For the 965, this is exactly the
* behavior we want for the results of texture lookups, but probably not for
*/
extern "C" {
#include "main/core.h"
#include "intel_context.h"
}
#include "../glsl/ir.h"
#include "../glsl/ir_visitor.h"
#include "../glsl/ir_print_visitor.h"
#include "../glsl/ir_rvalue_visitor.h"
#include "../glsl/glsl_types.h"
static bool debug = false;
class variable_entry : public exec_node
{
public:
variable_entry(ir_variable *var)
{
this->var = var;
this->whole_vector_access = 0;
this->declaration = false;
this->mem_ctx = NULL;
}
ir_variable *var; /* The key: the variable's pointer. */
/** Number of times the variable is referenced, including assignments. */
unsigned whole_vector_access;
bool declaration; /* If the variable had a decl in the instruction stream */
ir_variable *components[4];
/** talloc_parent(this->var) -- the shader's talloc context. */
void *mem_ctx;
};
class ir_vector_reference_visitor : public ir_hierarchical_visitor {
public:
ir_vector_reference_visitor(void)
{
this->mem_ctx = talloc_new(NULL);
this->variable_list.make_empty();
}
~ir_vector_reference_visitor(void)
{
talloc_free(mem_ctx);
}
virtual ir_visitor_status visit(ir_variable *);
virtual ir_visitor_status visit(ir_dereference_variable *);
virtual ir_visitor_status visit_enter(ir_swizzle *);
virtual ir_visitor_status visit_enter(ir_assignment *);
virtual ir_visitor_status visit_enter(ir_function_signature *);
variable_entry *get_variable_entry(ir_variable *var);
/* List of variable_entry */
exec_list variable_list;
void *mem_ctx;
};
variable_entry *
ir_vector_reference_visitor::get_variable_entry(ir_variable *var)
{
assert(var);
if (!var->type->is_vector())
return NULL;
switch (var->mode) {
case ir_var_uniform:
case ir_var_in:
case ir_var_out:
case ir_var_inout:
/* Can't split varyings or uniforms. Function in/outs won't get split
* either, so don't care about the ambiguity.
*/
return NULL;
case ir_var_auto:
case ir_var_temporary:
break;
}
foreach_iter(exec_list_iterator, iter, this->variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (entry->var == var)
return entry;
}
variable_entry *entry = new(mem_ctx) variable_entry(var);
this->variable_list.push_tail(entry);
return entry;
}
ir_visitor_status
ir_vector_reference_visitor::visit(ir_variable *ir)
{
variable_entry *entry = this->get_variable_entry(ir);
if (entry)
entry->declaration = true;
return visit_continue;
}
ir_visitor_status
ir_vector_reference_visitor::visit(ir_dereference_variable *ir)
{
ir_variable *const var = ir->var;
variable_entry *entry = this->get_variable_entry(var);
if (entry)
entry->whole_vector_access++;
return visit_continue;
}
ir_visitor_status
ir_vector_reference_visitor::visit_enter(ir_swizzle *ir)
{
/* Don't descend into a vector ir_dereference_variable below. */
if (ir->val->as_dereference_variable() && ir->type->is_scalar())
return visit_continue_with_parent;
return visit_continue;
}
ir_visitor_status
ir_vector_reference_visitor::visit_enter(ir_assignment *ir)
{
if (ir->lhs->as_dereference_variable() &&
ir->rhs->as_dereference_variable() &&
!ir->condition) {
/* We'll split copies of a vector to copies of channels, so don't
* descend to the ir_dereference_variables.
*/
return visit_continue_with_parent;
}
if (ir->lhs->as_dereference_variable() &&
is_power_of_two(ir->write_mask) &&
!ir->condition) {
/* If we're writing just a channel, then channel-splitting the LHS is OK.
*/
ir->rhs->accept(this);
return visit_continue_with_parent;
}
return visit_continue;
}
ir_visitor_status
ir_vector_reference_visitor::visit_enter(ir_function_signature *ir)
{
/* We don't want to descend into the function parameters and
* split them, so just accept the body here.
*/
visit_list_elements(this, &ir->body);
return visit_continue_with_parent;
}
class ir_vector_splitting_visitor : public ir_rvalue_visitor {
public:
ir_vector_splitting_visitor(exec_list *vars)
{
this->variable_list = vars;
}
virtual ir_visitor_status visit_leave(ir_assignment *);
void handle_rvalue(ir_rvalue **rvalue);
struct variable_entry *get_splitting_entry(ir_variable *var);
exec_list *variable_list;
void *mem_ctx;
};
struct variable_entry *
ir_vector_splitting_visitor::get_splitting_entry(ir_variable *var)
{
assert(var);
if (!var->type->is_vector())
return NULL;
foreach_iter(exec_list_iterator, iter, *this->variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (entry->var == var) {
return entry;
}
}
return NULL;
}
void
ir_vector_splitting_visitor::handle_rvalue(ir_rvalue **rvalue)
{
if (!*rvalue)
return;
ir_swizzle *swiz = (*rvalue)->as_swizzle();
if (!swiz || !swiz->type->is_scalar())
return;
ir_dereference_variable *deref_var = swiz->val->as_dereference_variable();
if (!deref_var)
return;
variable_entry *entry = get_splitting_entry(deref_var->var);
if (!entry)
return;
ir_variable *var = entry->components[swiz->mask.x];
*rvalue = new(entry->mem_ctx) ir_dereference_variable(var);
}
ir_visitor_status
ir_vector_splitting_visitor::visit_leave(ir_assignment *ir)
{
ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();
ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();
variable_entry *lhs = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;
variable_entry *rhs = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;
if (lhs_deref && rhs_deref && (lhs || rhs) && !ir->condition) {
/* Straight assignment of vector variables. */
for (unsigned int i = 0; i < ir->rhs->type->vector_elements; i++) {
ir_dereference *new_lhs;
ir_rvalue *new_rhs;
void *mem_ctx = lhs ? lhs->mem_ctx : rhs->mem_ctx;
unsigned int writemask;
if (!(ir->write_mask & (1 << i)))
continue;
if (lhs) {
new_lhs = new(mem_ctx) ir_dereference_variable(lhs->components[i]);
writemask = 1;
} else {
new_lhs = ir->lhs->clone(mem_ctx, NULL);
writemask = 1 << i;
}
if (rhs) {
new_rhs = new(mem_ctx) ir_dereference_variable(rhs->components[i]);
} else {
new_rhs = new(mem_ctx) ir_swizzle(ir->rhs->clone(mem_ctx, NULL),
i, i, i, i, 1);
}
ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,
new_rhs,
NULL, writemask));
}
ir->remove();
} else if (lhs) {
int elem = -1;
switch (ir->write_mask) {
case (1 << 0):
elem = 0;
break;
case (1 << 1):
elem = 1;
break;
case (1 << 2):
elem = 2;
break;
case (1 << 3):
elem = 3;
break;
default:
ir->print();
assert(!"not reached: non-channelwise dereference of LHS.");
}
ir->lhs = new(mem_ctx) ir_dereference_variable(lhs->components[elem]);
ir->write_mask = (1 << 0);
handle_rvalue(&ir->rhs);
} else {
handle_rvalue(&ir->rhs);
}
handle_rvalue(&ir->condition);
return visit_continue;
}
extern "C" {
bool
brw_do_vector_splitting(exec_list *instructions)
{
ir_vector_reference_visitor refs;
visit_list_elements(&refs, instructions);
/* Trim out variables we can't split. */
foreach_iter(exec_list_iterator, iter, refs.variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
if (debug) {
printf("vector %s@%p: decl %d, whole_access %d\n",
entry->var->name, (void *) entry->var, entry->declaration,
entry->whole_vector_access);
}
if (!entry->declaration || entry->whole_vector_access) {
entry->remove();
}
}
if (refs.variable_list.is_empty())
return false;
void *mem_ctx = talloc_new(NULL);
/* Replace the decls of the vectors to be split with their split
* components.
*/
foreach_iter(exec_list_iterator, iter, refs.variable_list) {
variable_entry *entry = (variable_entry *)iter.get();
const struct glsl_type *type;
type = glsl_type::get_instance(entry->var->type->base_type, 1, 1);
entry->mem_ctx = talloc_parent(entry->var);
for (unsigned int i = 0; i < entry->var->type->vector_elements; i++) {
const char *name = talloc_asprintf(mem_ctx, "%s_%c",
entry->var->name,
"xyzw"[i]);
entry->components[i] = new(entry->mem_ctx) ir_variable(type, name,
ir_var_temporary);
entry->var->insert_before(entry->components[i]);
}
entry->var->remove();
}
ir_vector_splitting_visitor split(&refs.variable_list);
visit_list_elements(&split, instructions);
talloc_free(mem_ctx);
return true;
}
}
<|endoftext|> |
<commit_before>#include "xchainer/python/array.h"
#include <algorithm>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
namespace xchainer {
namespace py = pybind11;
Dtype NumpyDtypeToDtype(py::dtype npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
Array MakeArray(const Shape& shape, Dtype dtype, py::list list) {
auto total_size = shape.total_size();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
auto func = [&](auto dummy) {
using T = decltype(dummy);
std::transform(list.begin(), list.end(), reinterpret_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
};
switch (dtype) {
case Dtype::kBool:
func(static_cast<bool>(0));
break;
case Dtype::kInt8:
func(static_cast<int8_t>(0));
break;
case Dtype::kInt16:
func(static_cast<int16_t>(0));
break;
case Dtype::kInt32:
func(static_cast<int32_t>(0));
break;
case Dtype::kInt64:
func(static_cast<int64_t>(0));
break;
case Dtype::kUInt8:
func(static_cast<uint8_t>(0));
break;
case Dtype::kFloat32:
func(static_cast<float>(0));
break;
case Dtype::kFloat64:
func(static_cast<double>(0));
break;
default:
assert(0);
}
return Array{shape, dtype, ptr};
}
std::unique_ptr<Array> MakeArray(py::array array) {
if (!(array.flags() & py::array::c_style)) {
throw DimensionError("cannot convert non-contiguous NumPy array to Array");
}
// TODO(hvy): When Unified Memory Array creation and its Python binding is in-place, create the Array on the correct device
Dtype dtype = NumpyDtypeToDtype(array.dtype());
py::buffer_info info = array.request();
Shape shape(info.shape);
// data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());
return std::make_unique<Array>(shape, dtype, data);
}
py::buffer_info MakeNumpyArrayFromArray(Array& self) {
if (!self.is_contiguous()) {
throw DimensionError("cannot convert non-contiguous Array to NumPy array");
}
size_t itemsize{GetElementSize(self.dtype())};
const Shape& shape = self.shape();
// compute C-contiguous strides
size_t ndim = self.ndim();
std::vector<size_t> strides(ndim);
if (ndim > 0) {
std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>());
strides.back() = 1;
std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; });
}
return py::buffer_info(self.data().get(), itemsize, std::string(1, GetCharCode(self.dtype())), ndim, shape, strides);
}
void InitXchainerArray(pybind11::module& m) {
py::class_<Array>{m, "Array", py::buffer_protocol()}
.def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray)))
.def(py::init(py::overload_cast<py::array>(&MakeArray)))
.def_buffer(&MakeNumpyArrayFromArray)
.def(py::self + py::self)
.def(py::self += py::self)
.def(py::self * py::self)
.def(py::self *= py::self)
.def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
.def_property_readonly("dtype", &Array::dtype)
.def_property_readonly("element_bytes", &Array::element_bytes)
.def_property_readonly("is_contiguous", &Array::is_contiguous)
.def_property_readonly("ndim", &Array::ndim)
.def_property_readonly("offset", &Array::offset)
.def_property_readonly("shape", &Array::shape)
.def_property_readonly("total_bytes", &Array::total_bytes)
.def_property_readonly("total_size", &Array::total_size)
.def_property_readonly("debug_flat_data",
[](const Array& self) { // This method is a stub for testing
py::list list;
auto size = self.total_size();
auto func = [&](auto dummy) {
using T = decltype(dummy);
const T& data = *std::static_pointer_cast<const T>(self.data());
for (int64_t i = 0; i < size; ++i) {
list.append((&data)[i]);
}
};
switch (self.dtype()) {
case Dtype::kBool:
func(static_cast<bool>(0));
break;
case Dtype::kInt8:
func(static_cast<int8_t>(0));
break;
case Dtype::kInt16:
func(static_cast<int16_t>(0));
break;
case Dtype::kInt32:
func(static_cast<int32_t>(0));
break;
case Dtype::kInt64:
func(static_cast<int64_t>(0));
break;
case Dtype::kUInt8:
func(static_cast<uint8_t>(0));
break;
case Dtype::kFloat32:
func(static_cast<float>(0));
break;
case Dtype::kFloat64:
func(static_cast<double>(0));
break;
default:
assert(0);
}
return list;
});
}
} // namespace xchainer
<commit_msg>Change order or bindings<commit_after>#include "xchainer/python/array.h"
#include <algorithm>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
namespace xchainer {
namespace py = pybind11;
Dtype NumpyDtypeToDtype(py::dtype npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
Array MakeArray(const Shape& shape, Dtype dtype, py::list list) {
auto total_size = shape.total_size();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
auto func = [&](auto dummy) {
using T = decltype(dummy);
std::transform(list.begin(), list.end(), reinterpret_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
};
switch (dtype) {
case Dtype::kBool:
func(static_cast<bool>(0));
break;
case Dtype::kInt8:
func(static_cast<int8_t>(0));
break;
case Dtype::kInt16:
func(static_cast<int16_t>(0));
break;
case Dtype::kInt32:
func(static_cast<int32_t>(0));
break;
case Dtype::kInt64:
func(static_cast<int64_t>(0));
break;
case Dtype::kUInt8:
func(static_cast<uint8_t>(0));
break;
case Dtype::kFloat32:
func(static_cast<float>(0));
break;
case Dtype::kFloat64:
func(static_cast<double>(0));
break;
default:
assert(0);
}
return Array{shape, dtype, ptr};
}
std::unique_ptr<Array> MakeArray(py::array array) {
if (!(array.flags() & py::array::c_style)) {
throw DimensionError("cannot convert non-contiguous NumPy array to Array");
}
// TODO(hvy): When Unified Memory Array creation and its Python binding is in-place, create the Array on the correct device
Dtype dtype = NumpyDtypeToDtype(array.dtype());
py::buffer_info info = array.request();
Shape shape(info.shape);
// data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());
return std::make_unique<Array>(shape, dtype, data);
}
py::buffer_info MakeNumpyArrayFromArray(Array& self) {
if (!self.is_contiguous()) {
throw DimensionError("cannot convert non-contiguous Array to NumPy array");
}
size_t itemsize{GetElementSize(self.dtype())};
const Shape& shape = self.shape();
// compute C-contiguous strides
size_t ndim = self.ndim();
std::vector<size_t> strides(ndim);
if (ndim > 0) {
std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>());
strides.back() = 1;
std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; });
}
return py::buffer_info(self.data().get(), itemsize, std::string(1, GetCharCode(self.dtype())), ndim, shape, strides);
}
void InitXchainerArray(pybind11::module& m) {
py::class_<Array>{m, "Array", py::buffer_protocol()}
.def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray)))
.def(py::init(py::overload_cast<py::array>(&MakeArray)))
.def_buffer(&MakeNumpyArrayFromArray)
.def(py::self += py::self)
.def(py::self *= py::self)
.def(py::self + py::self)
.def(py::self * py::self)
.def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
.def_property_readonly("dtype", &Array::dtype)
.def_property_readonly("element_bytes", &Array::element_bytes)
.def_property_readonly("is_contiguous", &Array::is_contiguous)
.def_property_readonly("ndim", &Array::ndim)
.def_property_readonly("offset", &Array::offset)
.def_property_readonly("shape", &Array::shape)
.def_property_readonly("total_bytes", &Array::total_bytes)
.def_property_readonly("total_size", &Array::total_size)
.def_property_readonly("debug_flat_data",
[](const Array& self) { // This method is a stub for testing
py::list list;
auto size = self.total_size();
auto func = [&](auto dummy) {
using T = decltype(dummy);
const T& data = *std::static_pointer_cast<const T>(self.data());
for (int64_t i = 0; i < size; ++i) {
list.append((&data)[i]);
}
};
switch (self.dtype()) {
case Dtype::kBool:
func(static_cast<bool>(0));
break;
case Dtype::kInt8:
func(static_cast<int8_t>(0));
break;
case Dtype::kInt16:
func(static_cast<int16_t>(0));
break;
case Dtype::kInt32:
func(static_cast<int32_t>(0));
break;
case Dtype::kInt64:
func(static_cast<int64_t>(0));
break;
case Dtype::kUInt8:
func(static_cast<uint8_t>(0));
break;
case Dtype::kFloat32:
func(static_cast<float>(0));
break;
case Dtype::kFloat64:
func(static_cast<double>(0));
break;
default:
assert(0);
}
return list;
});
}
} // namespace xchainer
<|endoftext|> |
<commit_before>// Copyright (c) 2011 Zeex
//
// 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 "amxprofiler.h"
platformstl::int64_t AMXFunPerfCounter::GetExecutionTime() const {
return time_;
}
platformstl::int64_t AMXFunPerfCounter::GetNumberOfCalls() const {
return calls_;
}
void AMXFunPerfCounter::StartCounter() {
counter_.start();
}
void AMXFunPerfCounter::StopCounter() {
counter_.stop();
time_ += counter_.get_microseconds();
}
void AMXFunPerfCounter::IncreaseCalls() {
calls_++;
}
AMXProfiler::AMXProfiler(AMX *amx)
: amx_(amx),
running_(false),
debugHook_(amx->debug),
callback_(amx->callback),
currentStackFrame_(0)
{
amx_SetUserData(amx_, AMX_USERTAG('p', 'r', 'o', 'f'), this);
}
AMXProfiler::~AMXProfiler() {
amx_SetUserData(amx_, AMX_USERTAG('p', 'r', 'o', 'f'), 0);
}
static int AMXAPI DebugHook(AMX *amx) {
void *prof;
amx_GetUserData(amx, AMX_USERTAG('p', 'r', 'o', 'f'), &prof);
return static_cast<AMXProfiler*>(prof)->DebugHook();
}
static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {
void *prof;
amx_GetUserData(amx, AMX_USERTAG('p', 'r', 'o', 'f'), &prof);
return static_cast<AMXProfiler*>(prof)->Callback(index, result, params);
}
void AMXProfiler::Run() {
functions_.clear();
amx_SetDebugHook(amx_, ::DebugHook);
amx_SetCallback(amx_, ::Callback);
}
bool AMXProfiler::IsRunning() const {
return running_;
}
void AMXProfiler::Terminate() {
amx_SetDebugHook(amx_, debugHook_);
amx_SetCallback(amx_, callback_);
}
// Get address of a CALL by frame
static cell GetCallAddress(AMX *amx, cell frame) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
cell data = reinterpret_cast<cell>(amx->base + hdr->dat);
return *(reinterpret_cast<cell*>(data + frame) + 1) - 2*sizeof(cell);
}
// Get address of callee
static cell GetCallTarget(AMX *amx, cell callAddr) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
cell code = reinterpret_cast<cell>(amx->base) + hdr->cod;
return *reinterpret_cast<cell*>(callAddr + sizeof(cell) + code) - code;
}
int AMXProfiler::DebugHook() {
if (amx_->frm != currentStackFrame_) {
if (amx_->frm < currentStackFrame_ || currentStackFrame_ == 0) {
// Entered a function
cell callAddr = GetCallAddress(amx_, amx_->frm);
if (callAddr > 0) {
cell funcAddr = GetCallTarget(amx_, callAddr);
functions_[funcAddr].IncreaseCalls();
functions_[funcAddr].StartCounter();
}
} else if (amx_->frm > currentStackFrame_) {
// Left a function
cell callAddr = GetCallAddress(amx_, currentStackFrame_);
if (callAddr > 0) {
cell funcAddr = GetCallTarget(amx_, callAddr);
functions_[funcAddr].StopCounter();
}
}
currentStackFrame_ = amx_->frm;
}
if (debugHook_ != 0) {
// Others could set their own debug hooks
return debugHook_(amx_);
}
return AMX_ERR_NONE;
}
int AMXProfiler::Callback(cell index, cell *result, cell *params) {
AMXFunPerfCounter &fun = functions_[-index]; // Note negative index
fun.StartCounter();
// Disable SYSREQ.D opcodes
amx_->sysreq_d = 0;
// Call any previously set AMX callback (must not be null
// so we don't bother checking it)
int error = callback_(amx_, index, result, params);
fun.StopCounter();
fun.IncreaseCalls();
return error;
}
std::vector<AMXFunPerfStats> AMXProfiler::GetStats() const {
std::vector<AMXFunPerfStats> stats;
for (std::map<cell, AMXFunPerfCounter>::const_iterator it = functions_.begin();
it != functions_.end(); ++it)
{
AMXFunPerfStats st;
cell address = it->first;
st.native = address <= 0;
st.address = address < 0 ? -address : address;
st.numberOfCalls = it->second.GetNumberOfCalls();
st.executionTime = it->second.GetExecutionTime();
stats.push_back(st);
}
return stats;
}
<commit_msg>Fix running_ flag is never set!!<commit_after>// Copyright (c) 2011 Zeex
//
// 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 "amxprofiler.h"
platformstl::int64_t AMXFunPerfCounter::GetExecutionTime() const {
return time_;
}
platformstl::int64_t AMXFunPerfCounter::GetNumberOfCalls() const {
return calls_;
}
void AMXFunPerfCounter::StartCounter() {
counter_.start();
}
void AMXFunPerfCounter::StopCounter() {
counter_.stop();
time_ += counter_.get_microseconds();
}
void AMXFunPerfCounter::IncreaseCalls() {
calls_++;
}
AMXProfiler::AMXProfiler(AMX *amx)
: amx_(amx),
running_(false),
debugHook_(amx->debug),
callback_(amx->callback),
currentStackFrame_(0)
{
amx_SetUserData(amx_, AMX_USERTAG('p', 'r', 'o', 'f'), this);
}
AMXProfiler::~AMXProfiler() {
amx_SetUserData(amx_, AMX_USERTAG('p', 'r', 'o', 'f'), 0);
}
static int AMXAPI DebugHook(AMX *amx) {
void *prof;
amx_GetUserData(amx, AMX_USERTAG('p', 'r', 'o', 'f'), &prof);
return static_cast<AMXProfiler*>(prof)->DebugHook();
}
static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {
void *prof;
amx_GetUserData(amx, AMX_USERTAG('p', 'r', 'o', 'f'), &prof);
return static_cast<AMXProfiler*>(prof)->Callback(index, result, params);
}
void AMXProfiler::Run() {
running_ = true;
functions_.clear();
amx_SetDebugHook(amx_, ::DebugHook);
amx_SetCallback(amx_, ::Callback);
}
bool AMXProfiler::IsRunning() const {
return running_;
}
void AMXProfiler::Terminate() {
running_ = false;
amx_SetDebugHook(amx_, debugHook_);
amx_SetCallback(amx_, callback_);
}
// Get address of a CALL by frame
static cell GetCallAddress(AMX *amx, cell frame) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
cell data = reinterpret_cast<cell>(amx->base + hdr->dat);
return *(reinterpret_cast<cell*>(data + frame) + 1) - 2*sizeof(cell);
}
// Get address of callee
static cell GetCallTarget(AMX *amx, cell callAddr) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
cell code = reinterpret_cast<cell>(amx->base) + hdr->cod;
return *reinterpret_cast<cell*>(callAddr + sizeof(cell) + code) - code;
}
int AMXProfiler::DebugHook() {
if (amx_->frm != currentStackFrame_) {
if (amx_->frm < currentStackFrame_ || currentStackFrame_ == 0) {
// Entered a function
cell callAddr = GetCallAddress(amx_, amx_->frm);
if (callAddr > 0) {
cell funcAddr = GetCallTarget(amx_, callAddr);
functions_[funcAddr].IncreaseCalls();
functions_[funcAddr].StartCounter();
}
} else if (amx_->frm > currentStackFrame_) {
// Left a function
cell callAddr = GetCallAddress(amx_, currentStackFrame_);
if (callAddr > 0) {
cell funcAddr = GetCallTarget(amx_, callAddr);
functions_[funcAddr].StopCounter();
}
}
currentStackFrame_ = amx_->frm;
}
if (debugHook_ != 0) {
// Others could set their own debug hooks
return debugHook_(amx_);
}
return AMX_ERR_NONE;
}
int AMXProfiler::Callback(cell index, cell *result, cell *params) {
AMXFunPerfCounter &fun = functions_[-index]; // Note negative index
fun.StartCounter();
// Disable SYSREQ.D opcodes
amx_->sysreq_d = 0;
// Call any previously set AMX callback (must not be null
// so we don't bother checking it)
int error = callback_(amx_, index, result, params);
fun.StopCounter();
fun.IncreaseCalls();
return error;
}
std::vector<AMXFunPerfStats> AMXProfiler::GetStats() const {
std::vector<AMXFunPerfStats> stats;
for (std::map<cell, AMXFunPerfCounter>::const_iterator it = functions_.begin();
it != functions_.end(); ++it)
{
AMXFunPerfStats st;
cell address = it->first;
st.native = address <= 0;
st.address = address < 0 ? -address : address;
st.numberOfCalls = it->second.GetNumberOfCalls();
st.executionTime = it->second.GetExecutionTime();
stats.push_back(st);
}
return stats;
}
<|endoftext|> |
<commit_before>#include <boost/filesystem/operations.hpp>
#include <iostream>
#include <algorithm>
#include "../include/fs_helpers.hpp"
#include "../include/debug.hpp"
namespace llscm {
using namespace std;
using namespace boost::filesystem;
static string exec_path;
static deque<string> search_path = {
"/usr/local/lib",
"/lib",
"/usr/lib"
};
void initExecPath(char *argv0) {
path full_path(initial_path<path>());
full_path = canonical(system_complete(path(argv0)));
exec_path = full_path.parent_path().generic_string();
search_path.push_front(exec_path);
D(cerr << "Exec path: " << exec_path << endl);
}
pair<string, bool> getLibraryPath(const string & name) {
for(auto & p: search_path) {
auto res = findFileInDirectory(name, p);
if (res.second) {
return res;
}
}
return {"", false};
}
pair<string, bool> findFileInDirectory(const string & fname, const string & dir) {
path file = fname;
directory_iterator dir_it(dir);
directory_iterator end;
auto file_it = find_if(dir_it, end, [&file] (const directory_entry & e) {
return e.path().filename() == file;
});
if (file_it == end) {
return {"", false};
}
return {file_it->path().generic_string(), true};
}
}
<commit_msg>findFileInDirectory: Must check if directory exists.<commit_after>#include <boost/filesystem/operations.hpp>
#include <iostream>
#include <algorithm>
#include "../include/fs_helpers.hpp"
#include "../include/debug.hpp"
namespace llscm {
using namespace std;
using namespace boost::filesystem;
static string exec_path;
static deque<string> search_path = {
"/usr/local/lib",
"/lib",
"/usr/lib"
};
void initExecPath(char *argv0) {
path full_path(initial_path<path>());
full_path = canonical(system_complete(path(argv0)));
exec_path = full_path.parent_path().generic_string();
search_path.push_front(exec_path);
D(cerr << "Exec path: " << exec_path << endl);
}
pair<string, bool> getLibraryPath(const string & name) {
for(auto & p: search_path) {
auto res = findFileInDirectory(name, p);
if (res.second) {
return res;
}
}
return {"", false};
}
pair<string, bool> findFileInDirectory(const string & fname, const string & dir) {
if (!exists(dir)) {
return {"", false};
}
path file = fname;
directory_iterator dir_it(dir);
directory_iterator end;
auto file_it = find_if(dir_it, end, [&file] (const directory_entry & e) {
return e.path().filename() == file;
});
if (file_it == end) {
return {"", false};
}
return {file_it->path().generic_string(), true};
}
}
<|endoftext|> |
<commit_before><commit_msg>related tdf#89004 improve performance of document data collection<commit_after><|endoftext|> |
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2015
*/
/*
Routines for sleeping for various times with particular trade-offs.
Uses a combination of sleep modes, watchdog timer (WDT), and other techniques.
*/
#include "OTV0P2BASE_Sleep.h"
namespace OTV0P2BASE
{
// Define macro to disable BOD during sleep here if not included in Arduino AVR toolset...
// This is only for "pico-power" variants, eg the "P" in ATmega328P.
#ifndef sleep_bod_disable
#define sleep_bod_disable() \
do { \
uint8_t tempreg; \
__asm__ __volatile__("in %[tempreg], %[mcucr]" "\n\t" \
"ori %[tempreg], %[bods_bodse]" "\n\t" \
"out %[mcucr], %[tempreg]" "\n\t" \
"andi %[tempreg], %[not_bodse]" "\n\t" \
"out %[mcucr], %[tempreg]" \
: [tempreg] "=&d" (tempreg) \
: [mcucr] "I" _SFR_IO_ADDR(MCUCR), \
[bods_bodse] "i" (_BV(BODS) | _BV(BODSE)), \
[not_bodse] "i" (~_BV(BODSE))); \
} while (0)
#endif
// Sleep with BOD disabled in power-save mode; will wake on any interrupt.
void sleepPwrSaveWithBODDisabled()
{
set_sleep_mode(SLEEP_MODE_PWR_SAVE); // Stop all but timer 2 and watchdog when sleeping.
cli();
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();
sleep_disable();
sei();
}
// Set non-zero when the watchdog ISR is invoked, ie the watchdog timer has gone off.
// Cleared at the start of the watchdog sleep routine.
// May contain a little entropy concentrated in the least-significant bits, in part from WDT-vs-CPU-clock jitter, especially if not sleeping.
static volatile uint8_t _watchdogFired;
// Catch watchdog timer interrupt to automatically clear WDIE and WDIF.
// This allows use of watchdog for low-power timed sleep.
ISR(WDT_vect)
{
// WDIE and WDIF are cleared in hardware upon entering this ISR.
wdt_disable();
// Note: be careful of what is accessed from this ISR.
// Capture some marginal entropy from the stack position.
uint8_t x;
_watchdogFired = ((uint8_t) 0x80) | ((uint8_t) (int) &x); // Ensure non-zero, retaining any entropy in ls bits.
}
// Idle the CPU for specified time but leave everything else running (eg UART), returning on any interrupt or the watchdog timer.
// * watchdogSleep is one of the WDTO_XX values from <avr/wdt.h>
// Should reduce power consumption vs spinning the CPU more than 3x, though not nearly as much as nap().
// True iff watchdog timer expired; false if something else woke the CPU.
// Only use this if not disallowed for board type, eg with ENABLE_USE_OF_AVR_IDLE_MODE.
bool idleCPU(const int_fast8_t watchdogSleep, const bool allowPrematureWakeup)
{
// Watchdog should (already) be disabled on entry.
_watchdogFired = 0;
wdt_enable(watchdogSleep);
WDTCSR |= (1 << WDIE);
// Keep sleeping until watchdog actually fires, unless premature return is permitted.
for( ; ; )
{
set_sleep_mode(SLEEP_MODE_IDLE); // Leave everything running but the CPU...
sleep_mode();
const bool fired = (0 != _watchdogFired);
if(fired || allowPrematureWakeup)
{
wdt_disable(); // Avoid spurious wakeup later.
return(fired);
}
}
}
// Sleep briefly in as lower-power mode as possible until the specified (watchdog) time expires.
// * watchdogSleep is one of the WDTO_XX values from <avr/wdt.h>
// May be useful to call minimsePowerWithoutSleep() first, when not needing any modules left on.
// NOTE: will stop clocks for UART, etc.
void nap(const int_fast8_t watchdogSleep)
{
// Watchdog should (already) be disabled on entry.
_watchdogFired = 0;
wdt_enable(watchdogSleep);
WDTCSR |= (1 << WDIE);
// Keep sleeping until watchdog actually fires.
for( ; ; )
{
sleepPwrSaveWithBODDisabled();
if(0 != _watchdogFired)
{
wdt_disable(); // Avoid spurious wakeup later.
return; // All done!
}
}
}
// Sleep briefly in as lower-power mode as possible until the specified (watchdog) time expires, or another interrupt.
// * watchdogSleep is one of the WDTO_XX values from <avr/wdt.h>
// * allowPrematureWakeup if true then if woken before watchdog fires return false; default false
// Returns false if the watchdog timer did not go off, true if it did.
// May be useful to call minimsePowerWithoutSleep() first, when not needing any modules left on.
// NOTE: will stop clocks for UART, etc.
bool nap(const int_fast8_t watchdogSleep, const bool allowPrematureWakeup)
{
// Watchdog should (already) be disabled on entry.
_watchdogFired = 0;
wdt_enable(watchdogSleep);
WDTCSR |= (1 << WDIE);
// Keep sleeping until watchdog actually fires, unless premature return is permitted.
for( ; ; )
{
sleepPwrSaveWithBODDisabled();
const bool fired = (0 != _watchdogFired);
if(fired || allowPrematureWakeup)
{
wdt_disable(); // Avoid spurious wakeup later.
return(fired);
}
}
}
// Sleep for specified number of _delay_loop2() loops at minimum available CPU speed.
// Each loop takes 4 cycles at that minimum speed, but entry and exit overheads may take the equivalent of a loop or two.
// Note: inlining is prevented so as to avoid migrating anything into the section where the CPU is running slowly.
//
// Note: may be dubious to run CPU clock less than 4x 32768Hz crystal speed,
// eg at 31250Hz for 8MHz RC clock and max prescale.
// Don't access timer 2 registers at low CPU speed, eg in ISRs.
//
// This may only be safe to use in practice with interrupts disabled.
__attribute__ ((noinline)) void _sleepLowPowerLoopsMinCPUSpeed(uint16_t loops)
{
const clock_div_t prescale = clock_prescale_get(); // Capture current prescale value.
clock_prescale_set(MAX_CPU_PRESCALE); // Reduce clock speed (increase prescale) as far as possible.
_delay_loop_2(loops); // Burn cycles...
clock_prescale_set(prescale); // Restore clock prescale.
}
#include <util/crc16.h>
// Extract and return a little entropy from clock jitter between CPU and WDT clocks; possibly one bit of entropy captured.
// Expensive in terms of CPU time and thus energy.
// TODO: may be able to reduce clock speed to lower energy cost while still detecting useful jitter.
// NOTE: in this file to have direct access to WDT.
uint_fast8_t clockJitterWDT()
{
// Watchdog should be (already) be disabled on entry.
_watchdogFired = false;
wdt_enable(WDTO_15MS); // Set watchdog for minimum time.
WDTCSR |= (1 << WDIE);
uint_fast8_t count = 0;
while(!_watchdogFired) { ++count; } // Effectively count CPU cycles until WDT fires.
return(count);
}
// Combined clock jitter techniques to return approximately 8 bits (the entire result byte) of entropy efficiently on demand.
// Expensive in terms of CPU time and thus energy, though possibly more efficient than basic clockJitterXXX() routines.
// Internally this uses a CRC as a relatively fast and hopefully effective hash over intermediate values.
// Note the that rejection of repeat values will be less effective with two interleaved gathering mechanisms
// as the interaction while not necessarily adding genuine entropy, will make counts differ between runs.
// DHD20130519: measured as taking ~63ms to run, ie ~8ms per bit gathered.
// NOTE: in this file to have direct access to WDT.
uint_fast8_t clockJitterEntropyByte()
{
uint16_t hash = 0;
uint_fast8_t result = 0;
uint_fast8_t countR = 0, lastCountR = 0;
uint_fast8_t countW = 0, lastCountW = 0;
const uint8_t t0 = TCNT2; // Wait for sub-cycle timer to roll.
while(t0 == TCNT2) { ++hash; } // Possibly capture some entropy from recent program activity/timing.
uint8_t t1 = TCNT2;
_watchdogFired = 0;
wdt_enable(WDTO_15MS); // Start watchdog, with minimum timeout.
WDTCSR |= (1 << WDIE);
int_fast8_t bitsLeft = 8; // Decrement when a bit is harvested...
for( ; ; )
{
// Extract watchdog jitter vs CPU.
if(!_watchdogFired) { ++countW; }
else // Watchdog fired.
{
if(countW != lastCountW) // Got a different value from last; assume one bit of entropy.
{
hash = _crc_ccitt_update(hash, countW);
result = (result << 1) ^ ((uint_fast8_t)hash); // Nominally capturing (at least) lsb of hash.
if(--bitsLeft <= 0) { break; } // Got enough bits; stop now.
lastCountW = countW;
}
countW = 0;
_watchdogFired = 0;
wdt_enable(WDTO_15MS); // Restart watchdog, with minimum timeout.
WDTCSR |= (1 << WDIE);
}
// Extract RTC jitter vs CPU.
if(t1 == TCNT2) { --countR; }
else // Sub-cycle timer rolled.
{
if(countR != lastCountR) // Got a different value from last; assume one bit of entropy.
{
hash = _crc_ccitt_update(hash, countR);
result = (result << 1) ^ ((uint_fast8_t)hash); // Nominally capturing (at least) lsb of hash.
if(--bitsLeft <= 0) { break; } // Got enough bits; stop now.
lastCountR = countR;
}
countR = 0;
t1 = TCNT2; // Set to look for next roll.
}
}
wdt_disable(); // Ensure no spurious WDT wakeup pending.
return(result);
}
}
<commit_msg>COH-63: adding warning about IDLE.<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2015
*/
/*
Routines for sleeping for various times with particular trade-offs.
Uses a combination of sleep modes, watchdog timer (WDT), and other techniques.
*/
#include "OTV0P2BASE_Sleep.h"
namespace OTV0P2BASE
{
// Define macro to disable BOD during sleep here if not included in Arduino AVR toolset...
// This is only for "pico-power" variants, eg the "P" in ATmega328P.
#ifndef sleep_bod_disable
#define sleep_bod_disable() \
do { \
uint8_t tempreg; \
__asm__ __volatile__("in %[tempreg], %[mcucr]" "\n\t" \
"ori %[tempreg], %[bods_bodse]" "\n\t" \
"out %[mcucr], %[tempreg]" "\n\t" \
"andi %[tempreg], %[not_bodse]" "\n\t" \
"out %[mcucr], %[tempreg]" \
: [tempreg] "=&d" (tempreg) \
: [mcucr] "I" _SFR_IO_ADDR(MCUCR), \
[bods_bodse] "i" (_BV(BODS) | _BV(BODSE)), \
[not_bodse] "i" (~_BV(BODSE))); \
} while (0)
#endif
// Sleep with BOD disabled in power-save mode; will wake on any interrupt.
void sleepPwrSaveWithBODDisabled()
{
set_sleep_mode(SLEEP_MODE_PWR_SAVE); // Stop all but timer 2 and watchdog when sleeping.
cli();
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();
sleep_disable();
sei();
}
// Set non-zero when the watchdog ISR is invoked, ie the watchdog timer has gone off.
// Cleared at the start of the watchdog sleep routine.
// May contain a little entropy concentrated in the least-significant bits, in part from WDT-vs-CPU-clock jitter, especially if not sleeping.
static volatile uint8_t _watchdogFired;
// Catch watchdog timer interrupt to automatically clear WDIE and WDIF.
// This allows use of watchdog for low-power timed sleep.
ISR(WDT_vect)
{
// WDIE and WDIF are cleared in hardware upon entering this ISR.
wdt_disable();
// Note: be careful of what is accessed from this ISR.
// Capture some marginal entropy from the stack position.
uint8_t x;
_watchdogFired = ((uint8_t) 0x80) | ((uint8_t) (int) &x); // Ensure non-zero, retaining any entropy in ls bits.
}
// Idle the CPU for specified time but leave everything else running (eg UART), returning on any interrupt or the watchdog timer.
// * watchdogSleep is one of the WDTO_XX values from <avr/wdt.h>
// Should reduce power consumption vs spinning the CPU more than 3x, though not nearly as much as nap().
// True iff watchdog timer expired; false if something else woke the CPU.
// WARNING: DHD20150827: seems able to cause crash/reset of some REV0 and REV9 boards, eg called from CLI.
bool idleCPU(const int_fast8_t watchdogSleep, const bool allowPrematureWakeup)
{
// Watchdog should (already) be disabled on entry.
_watchdogFired = 0;
wdt_enable(watchdogSleep);
WDTCSR |= (1 << WDIE);
// Keep sleeping until watchdog actually fires, unless premature return is permitted.
for( ; ; )
{
set_sleep_mode(SLEEP_MODE_IDLE); // Leave everything running but the CPU...
sleep_mode();
const bool fired = (0 != _watchdogFired);
if(fired || allowPrematureWakeup)
{
wdt_disable(); // Avoid spurious wakeup later.
return(fired);
}
}
}
// Sleep briefly in as lower-power mode as possible until the specified (watchdog) time expires.
// * watchdogSleep is one of the WDTO_XX values from <avr/wdt.h>
// May be useful to call minimsePowerWithoutSleep() first, when not needing any modules left on.
// NOTE: will stop clocks for UART, etc.
void nap(const int_fast8_t watchdogSleep)
{
// Watchdog should (already) be disabled on entry.
_watchdogFired = 0;
wdt_enable(watchdogSleep);
WDTCSR |= (1 << WDIE);
// Keep sleeping until watchdog actually fires.
for( ; ; )
{
sleepPwrSaveWithBODDisabled();
if(0 != _watchdogFired)
{
wdt_disable(); // Avoid spurious wakeup later.
return; // All done!
}
}
}
// Sleep briefly in as lower-power mode as possible until the specified (watchdog) time expires, or another interrupt.
// * watchdogSleep is one of the WDTO_XX values from <avr/wdt.h>
// * allowPrematureWakeup if true then if woken before watchdog fires return false; default false
// Returns false if the watchdog timer did not go off, true if it did.
// May be useful to call minimsePowerWithoutSleep() first, when not needing any modules left on.
// NOTE: will stop clocks for UART, etc.
bool nap(const int_fast8_t watchdogSleep, const bool allowPrematureWakeup)
{
// Watchdog should (already) be disabled on entry.
_watchdogFired = 0;
wdt_enable(watchdogSleep);
WDTCSR |= (1 << WDIE);
// Keep sleeping until watchdog actually fires, unless premature return is permitted.
for( ; ; )
{
sleepPwrSaveWithBODDisabled();
const bool fired = (0 != _watchdogFired);
if(fired || allowPrematureWakeup)
{
wdt_disable(); // Avoid spurious wakeup later.
return(fired);
}
}
}
// Sleep for specified number of _delay_loop2() loops at minimum available CPU speed.
// Each loop takes 4 cycles at that minimum speed, but entry and exit overheads may take the equivalent of a loop or two.
// Note: inlining is prevented so as to avoid migrating anything into the section where the CPU is running slowly.
//
// Note: may be dubious to run CPU clock less than 4x 32768Hz crystal speed,
// eg at 31250Hz for 8MHz RC clock and max prescale.
// Don't access timer 2 registers at low CPU speed, eg in ISRs.
//
// This may only be safe to use in practice with interrupts disabled.
__attribute__ ((noinline)) void _sleepLowPowerLoopsMinCPUSpeed(uint16_t loops)
{
const clock_div_t prescale = clock_prescale_get(); // Capture current prescale value.
clock_prescale_set(MAX_CPU_PRESCALE); // Reduce clock speed (increase prescale) as far as possible.
_delay_loop_2(loops); // Burn cycles...
clock_prescale_set(prescale); // Restore clock prescale.
}
#include <util/crc16.h>
// Extract and return a little entropy from clock jitter between CPU and WDT clocks; possibly one bit of entropy captured.
// Expensive in terms of CPU time and thus energy.
// TODO: may be able to reduce clock speed to lower energy cost while still detecting useful jitter.
// NOTE: in this file to have direct access to WDT.
uint_fast8_t clockJitterWDT()
{
// Watchdog should be (already) be disabled on entry.
_watchdogFired = false;
wdt_enable(WDTO_15MS); // Set watchdog for minimum time.
WDTCSR |= (1 << WDIE);
uint_fast8_t count = 0;
while(!_watchdogFired) { ++count; } // Effectively count CPU cycles until WDT fires.
return(count);
}
// Combined clock jitter techniques to return approximately 8 bits (the entire result byte) of entropy efficiently on demand.
// Expensive in terms of CPU time and thus energy, though possibly more efficient than basic clockJitterXXX() routines.
// Internally this uses a CRC as a relatively fast and hopefully effective hash over intermediate values.
// Note the that rejection of repeat values will be less effective with two interleaved gathering mechanisms
// as the interaction while not necessarily adding genuine entropy, will make counts differ between runs.
// DHD20130519: measured as taking ~63ms to run, ie ~8ms per bit gathered.
// NOTE: in this file to have direct access to WDT.
uint_fast8_t clockJitterEntropyByte()
{
uint16_t hash = 0;
uint_fast8_t result = 0;
uint_fast8_t countR = 0, lastCountR = 0;
uint_fast8_t countW = 0, lastCountW = 0;
const uint8_t t0 = TCNT2; // Wait for sub-cycle timer to roll.
while(t0 == TCNT2) { ++hash; } // Possibly capture some entropy from recent program activity/timing.
uint8_t t1 = TCNT2;
_watchdogFired = 0;
wdt_enable(WDTO_15MS); // Start watchdog, with minimum timeout.
WDTCSR |= (1 << WDIE);
int_fast8_t bitsLeft = 8; // Decrement when a bit is harvested...
for( ; ; )
{
// Extract watchdog jitter vs CPU.
if(!_watchdogFired) { ++countW; }
else // Watchdog fired.
{
if(countW != lastCountW) // Got a different value from last; assume one bit of entropy.
{
hash = _crc_ccitt_update(hash, countW);
result = (result << 1) ^ ((uint_fast8_t)hash); // Nominally capturing (at least) lsb of hash.
if(--bitsLeft <= 0) { break; } // Got enough bits; stop now.
lastCountW = countW;
}
countW = 0;
_watchdogFired = 0;
wdt_enable(WDTO_15MS); // Restart watchdog, with minimum timeout.
WDTCSR |= (1 << WDIE);
}
// Extract RTC jitter vs CPU.
if(t1 == TCNT2) { --countR; }
else // Sub-cycle timer rolled.
{
if(countR != lastCountR) // Got a different value from last; assume one bit of entropy.
{
hash = _crc_ccitt_update(hash, countR);
result = (result << 1) ^ ((uint_fast8_t)hash); // Nominally capturing (at least) lsb of hash.
if(--bitsLeft <= 0) { break; } // Got enough bits; stop now.
lastCountR = countR;
}
countR = 0;
t1 = TCNT2; // Set to look for next roll.
}
}
wdt_disable(); // Ensure no spurious WDT wakeup pending.
return(result);
}
}
<|endoftext|> |
<commit_before><commit_msg>coverity#738899 unused member<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: tautofmt.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: fme $ $Date: 2001-06-14 17:19:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SW_TAUTOFMT_HXX
#define SW_TAUTOFMT_HXX
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
class SwView;
class SwTableAutoFmt;
class SvxBoxItem;
class SvxBorderLine;
class AutoFmtPreview;
class SwTableAutoFmtTbl;
//------------------------------------------------------------------------
enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };
//========================================================================
class SwAutoFormatDlg : public SfxModalDialog
{
FixedLine aFlFormat;
ListBox aLbFormat;
CheckBox aBtnNumFormat;
CheckBox aBtnBorder;
CheckBox aBtnFont;
CheckBox aBtnPattern;
CheckBox aBtnAlignment;
FixedLine aFlFormats;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
PushButton aBtnAdd;
PushButton aBtnRemove;
PushButton aBtnRename;
MoreButton aBtnMore;
String aStrTitle;
String aStrLabel;
String aStrClose;
String aStrDelTitle;
String aStrDelMsg;
String aStrRenameTitle;
String aStrInvalidFmt;
AutoFmtPreview* pWndPreview;
//------------------------
SwWrtShell* pShell;
SwTableAutoFmtTbl* pTableTbl;
BYTE nIndex;
BYTE nDfltStylePos;
BOOL bCoreDataChanged : 1;
BOOL bSetAutoFmt : 1;
void Init( const SwTableAutoFmt* pSelFmt );
void UpdateChecks( const SwTableAutoFmt&, BOOL bEnableBtn );
//------------------------
DECL_LINK( CheckHdl, Button * );
DECL_LINK( OkHdl, Button * );
DECL_LINK( AddHdl, void * );
DECL_LINK( RemoveHdl, void * );
DECL_LINK( RenameHdl, void * );
DECL_LINK( SelFmtHdl, void * );
public:
SwAutoFormatDlg( Window* pParent, SwWrtShell* pShell,
BOOL bSetAutoFmt = TRUE,
const SwTableAutoFmt* pSelFmt = 0 );
virtual ~SwAutoFormatDlg();
void FillAutoFmtOfIndex( SwTableAutoFmt*& rToFill ) const;
};
#endif // SW_AUTOFMT_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.1448); FILE MERGED 2005/09/05 13:45:44 rt 1.3.1448.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tautofmt.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:08:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SW_TAUTOFMT_HXX
#define SW_TAUTOFMT_HXX
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
class SwView;
class SwTableAutoFmt;
class SvxBoxItem;
class SvxBorderLine;
class AutoFmtPreview;
class SwTableAutoFmtTbl;
//------------------------------------------------------------------------
enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };
//========================================================================
class SwAutoFormatDlg : public SfxModalDialog
{
FixedLine aFlFormat;
ListBox aLbFormat;
CheckBox aBtnNumFormat;
CheckBox aBtnBorder;
CheckBox aBtnFont;
CheckBox aBtnPattern;
CheckBox aBtnAlignment;
FixedLine aFlFormats;
OKButton aBtnOk;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
PushButton aBtnAdd;
PushButton aBtnRemove;
PushButton aBtnRename;
MoreButton aBtnMore;
String aStrTitle;
String aStrLabel;
String aStrClose;
String aStrDelTitle;
String aStrDelMsg;
String aStrRenameTitle;
String aStrInvalidFmt;
AutoFmtPreview* pWndPreview;
//------------------------
SwWrtShell* pShell;
SwTableAutoFmtTbl* pTableTbl;
BYTE nIndex;
BYTE nDfltStylePos;
BOOL bCoreDataChanged : 1;
BOOL bSetAutoFmt : 1;
void Init( const SwTableAutoFmt* pSelFmt );
void UpdateChecks( const SwTableAutoFmt&, BOOL bEnableBtn );
//------------------------
DECL_LINK( CheckHdl, Button * );
DECL_LINK( OkHdl, Button * );
DECL_LINK( AddHdl, void * );
DECL_LINK( RemoveHdl, void * );
DECL_LINK( RenameHdl, void * );
DECL_LINK( SelFmtHdl, void * );
public:
SwAutoFormatDlg( Window* pParent, SwWrtShell* pShell,
BOOL bSetAutoFmt = TRUE,
const SwTableAutoFmt* pSelFmt = 0 );
virtual ~SwAutoFormatDlg();
void FillAutoFmtOfIndex( SwTableAutoFmt*& rToFill ) const;
};
#endif // SW_AUTOFMT_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: initui.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:45:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _INITUI_HXX
#include <initui.hxx>
#endif
#ifndef _EDTWIN_HXX
#include <edtwin.hxx>
#endif
#ifndef _SHELLRES_HXX
#include <shellres.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _GLOSDOC_HXX
#include <glosdoc.hxx>
#endif
#ifndef _GLOSLST_HXX
#include <gloslst.hxx>
#endif
#ifndef _UTLUI_HRC
#include <utlui.hrc>
#endif
#ifndef _INITUI_HRC
#include <initui.hrc>
#endif
#ifndef _COMCORE_HRC
#include <comcore.hrc>
#endif
#ifndef _AUTHFLD_HXX
#include <authfld.hxx>
#endif
#ifndef _DBMGR_HXX
#include <dbmgr.hxx>
#endif
#include <unomid.h>
/*--------------------------------------------------------------------
Beschreibung: globale Pointer
--------------------------------------------------------------------*/
SwGlossaries* pGlossaries = 0;
// Liefert alle benoetigten Pfade. Wird durch UI initialisiert
SwGlossaryList* pGlossaryList = 0;
String* pOldGrfCat = 0;
String* pOldTabCat = 0;
String* pOldFrmCat = 0;
String* pOldDrwCat = 0;
String* pCurrGlosGroup = 0;
String* GetOldGrfCat()
{
return pOldGrfCat;
}
String* GetOldTabCat()
{
return pOldTabCat;
}
String* GetOldFrmCat()
{
return pOldFrmCat;
}
String* GetOldDrwCat()
{
return pOldDrwCat;
}
String* GetCurrGlosGroup()
{
return pCurrGlosGroup;
}
void SetCurrGlosGroup(String* pStr)
{
pCurrGlosGroup = pStr;
}
SvStringsDtor* pDBNameList = 0;
SvStringsDtor* pAuthFieldNameList = 0;
SvStringsDtor* pAuthFieldTypeList = 0;
/*--------------------------------------------------------------------
Beschreibung: UI beenden
--------------------------------------------------------------------*/
void _FinitUI()
{
SwNewDBMgr::RemoveDbtoolsClient();
delete ViewShell::GetShellRes();
ViewShell::SetShellRes( 0 );
SwEditWin::_FinitStaticData();
DELETEZ(pGlossaries);
delete SwFieldType::pFldNames;
delete pOldGrfCat;
delete pOldTabCat;
delete pOldFrmCat;
delete pOldDrwCat;
delete pCurrGlosGroup;
delete pDBNameList;
delete pGlossaryList;
delete pAuthFieldNameList;
delete pAuthFieldTypeList;
}
/*--------------------------------------------------------------------
Beschreibung: Initialisierung
--------------------------------------------------------------------*/
void _InitUI()
{
// ShellResource gibt der CORE die Moeglichkeit mit Resourcen zu arbeiten
ViewShell::SetShellRes( new ShellResource );
pDBNameList = new SvStringsDtor( 5, 5 );
SwEditWin::_InitStaticData();
}
ShellResource::ShellResource()
: Resource( SW_RES(RID_SW_SHELLRES) ),
aPostItAuthor( SW_RES( STR_POSTIT_AUTHOR ) ),
aPostItPage( SW_RES( STR_POSTIT_PAGE ) ),
aPostItLine( SW_RES( STR_POSTIT_LINE ) ),
aCalc_Syntax( SW_RES( STR_CALC_SYNTAX ) ),
aCalc_ZeroDiv( SW_RES( STR_CALC_ZERODIV ) ),
aCalc_Brack( SW_RES( STR_CALC_BRACK ) ),
aCalc_Pow( SW_RES( STR_CALC_POW ) ),
aCalc_VarNFnd( SW_RES( STR_CALC_VARNFND ) ),
aCalc_Overflow( SW_RES( STR_CALC_OVERFLOW ) ),
aCalc_WrongTime( SW_RES( STR_CALC_WRONGTIME ) ),
aCalc_Default( SW_RES( STR_CALC_DEFAULT ) ),
aCalc_Error( SW_RES( STR_CALC_ERROR ) ),
aGetRefFld_Up( SW_RES( STR_GETREFFLD_UP ) ),
aGetRefFld_Down( SW_RES( STR_GETREFFLD_DOWN ) ),
aStrAllPageHeadFoot( SW_RES( STR_ALLPAGE_HEADFOOT ) ),
aStrNone( SW_RES( STR_TEMPLATE_NONE )),
aFixedStr( SW_RES( STR_FIELD_FIXED )),
aTOXIndexName( SW_RES(STR_TOI)),
aTOXUserName( SW_RES(STR_TOU)),
aTOXContentName( SW_RES(STR_TOC)),
aTOXIllustrationsName( SW_RES(STR_TOX_ILL)),
aTOXObjectsName( SW_RES(STR_TOX_OBJ)),
aTOXTablesName( SW_RES(STR_TOX_TBL)),
aTOXAuthoritiesName( SW_RES(STR_TOX_AUTH)),
aHyperlinkClick( SW_RES( STR_HYPERLINK_CLICK)),
sPageDescFirstName( SW_RES(STR_PAGEDESC_FIRSTNAME)),
sPageDescFollowName( SW_RES(STR_PAGEDESC_FOLLOWNAME)),
sPageDescName( SW_RES(STR_PAGEDESC_NAME))
{
const USHORT nCount = FLD_DOCINFO_END - FLD_DOCINFO_BEGIN;
for(USHORT i = 0; i < nCount; ++i)
{
String* pNew = new SW_RESSTR(FLD_DOCINFO_BEGIN + i);
aDocInfoLst.Insert(pNew, aDocInfoLst.Count());
}
FreeResource();
}
ShellResource::~ShellResource()
{
if( pAutoFmtNameLst )
delete pAutoFmtNameLst, pAutoFmtNameLst = 0;
}
String ShellResource::GetPageDescName( USHORT nNo, BOOL bIsFirst, BOOL bFollow )
{
String sRet( bIsFirst ? sPageDescFirstName
: bFollow ? sPageDescFollowName
: sPageDescName );
sRet.SearchAndReplaceAscii( "$(ARG1)", String::CreateFromInt32( nNo ));
return sRet;
}
SwGlossaries* GetGlossaries()
{
if (!pGlossaries)
pGlossaries = new SwGlossaries;
return (pGlossaries);
}
BOOL HasGlossaryList()
{
return pGlossaryList != 0;
}
SwGlossaryList* GetGlossaryList()
{
if(!pGlossaryList)
pGlossaryList = new SwGlossaryList();
return pGlossaryList;
}
struct ImpAutoFmtNameListLoader : public Resource
{
ImpAutoFmtNameListLoader( SvStringsDtor& rLst );
};
void ShellResource::_GetAutoFmtNameLst() const
{
SvStringsDtor** ppLst = (SvStringsDtor**)&pAutoFmtNameLst;
*ppLst = new SvStringsDtor( STR_AUTOFMTREDL_END );
ImpAutoFmtNameListLoader aTmp( **ppLst );
}
ImpAutoFmtNameListLoader::ImpAutoFmtNameListLoader( SvStringsDtor& rLst )
: Resource( ResId(RID_SHELLRES_AUTOFMTSTRS, *pSwResMgr) )
{
for( USHORT n = 0; n < STR_AUTOFMTREDL_END; ++n )
{
String* p = new String( ResId( n + 1, *pSwResMgr) );
if(STR_AUTOFMTREDL_TYPO == n)
{
#ifdef WNT
//fuer Windows Sonderbehandlung, da MS hier ein paar Zeichen im Dialogfont vergessen hat
p->SearchAndReplace(C2S("%1"), C2S(",,"));
p->SearchAndReplace(C2S("%2"), C2S("''"));
#else
LocaleDataWrapper& rLclD = GetAppLocaleData();
//unter richtigen Betriebssystemen funktioniert es auch so
p->SearchAndReplace(C2S("%1"), rLclD.getDoubleQuotationMarkStart());
p->SearchAndReplace(C2S("%2"), rLclD.getDoubleQuotationMarkEnd());
#endif
}
rLst.Insert( p, n );
}
FreeResource();
}
/* -----------------16.09.99 12:28-------------------
--------------------------------------------------*/
const String& SwAuthorityFieldType::GetAuthFieldName(ToxAuthorityField eType)
{
if(!pAuthFieldNameList)
{
pAuthFieldNameList = new SvStringsDtor(AUTH_FIELD_END, 1);
for(USHORT i = 0; i < AUTH_FIELD_END; i++)
{
String* pTmp = new String(SW_RES(STR_AUTH_FIELD_START + i));
pAuthFieldNameList->Insert(pTmp, pAuthFieldNameList->Count());
}
}
return *pAuthFieldNameList->GetObject( static_cast< USHORT >(eType) );
}
/* -----------------16.09.99 12:29-------------------
--------------------------------------------------*/
const String& SwAuthorityFieldType::GetAuthTypeName(ToxAuthorityType eType)
{
if(!pAuthFieldTypeList)
{
pAuthFieldTypeList = new SvStringsDtor(AUTH_TYPE_END, 1);
for(USHORT i = 0; i < AUTH_TYPE_END; i++)
pAuthFieldTypeList->Insert(
new String(SW_RES(STR_AUTH_TYPE_START + i)),
pAuthFieldTypeList->Count());
}
return *pAuthFieldTypeList->GetObject( static_cast< USHORT >(eType) );
}
<commit_msg>INTEGRATION: CWS swcrossref01_DEV300 (1.13.92); FILE MERGED 2007/10/01 15:35:28 od 1.13.92.2: RESYNC: (1.13-1.14); FILE MERGED merge conflict resolved. 2007/09/17 12:36:56 od 1.13.92.1: #i81002# new string for missing reference/bookmark<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: initui.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: obo $ $Date: 2008-02-26 10:49:52 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _INITUI_HXX
#include <initui.hxx>
#endif
#ifndef _EDTWIN_HXX
#include <edtwin.hxx>
#endif
#ifndef _SHELLRES_HXX
#include <shellres.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _GLOSDOC_HXX
#include <glosdoc.hxx>
#endif
#ifndef _GLOSLST_HXX
#include <gloslst.hxx>
#endif
#ifndef _UTLUI_HRC
#include <utlui.hrc>
#endif
#ifndef _INITUI_HRC
#include <initui.hrc>
#endif
#ifndef _COMCORE_HRC
#include <comcore.hrc>
#endif
#ifndef _AUTHFLD_HXX
#include <authfld.hxx>
#endif
#ifndef _DBMGR_HXX
#include <dbmgr.hxx>
#endif
#include <unomid.h>
/*--------------------------------------------------------------------
Beschreibung: globale Pointer
--------------------------------------------------------------------*/
SwGlossaries* pGlossaries = 0;
// Liefert alle benoetigten Pfade. Wird durch UI initialisiert
SwGlossaryList* pGlossaryList = 0;
String* pOldGrfCat = 0;
String* pOldTabCat = 0;
String* pOldFrmCat = 0;
String* pOldDrwCat = 0;
String* pCurrGlosGroup = 0;
String* GetOldGrfCat()
{
return pOldGrfCat;
}
String* GetOldTabCat()
{
return pOldTabCat;
}
String* GetOldFrmCat()
{
return pOldFrmCat;
}
String* GetOldDrwCat()
{
return pOldDrwCat;
}
String* GetCurrGlosGroup()
{
return pCurrGlosGroup;
}
void SetCurrGlosGroup(String* pStr)
{
pCurrGlosGroup = pStr;
}
SvStringsDtor* pDBNameList = 0;
SvStringsDtor* pAuthFieldNameList = 0;
SvStringsDtor* pAuthFieldTypeList = 0;
/*--------------------------------------------------------------------
Beschreibung: UI beenden
--------------------------------------------------------------------*/
void _FinitUI()
{
SwNewDBMgr::RemoveDbtoolsClient();
delete ViewShell::GetShellRes();
ViewShell::SetShellRes( 0 );
SwEditWin::_FinitStaticData();
DELETEZ(pGlossaries);
delete SwFieldType::pFldNames;
delete pOldGrfCat;
delete pOldTabCat;
delete pOldFrmCat;
delete pOldDrwCat;
delete pCurrGlosGroup;
delete pDBNameList;
delete pGlossaryList;
delete pAuthFieldNameList;
delete pAuthFieldTypeList;
}
/*--------------------------------------------------------------------
Beschreibung: Initialisierung
--------------------------------------------------------------------*/
void _InitUI()
{
// ShellResource gibt der CORE die Moeglichkeit mit Resourcen zu arbeiten
ViewShell::SetShellRes( new ShellResource );
pDBNameList = new SvStringsDtor( 5, 5 );
SwEditWin::_InitStaticData();
}
ShellResource::ShellResource()
: Resource( SW_RES(RID_SW_SHELLRES) ),
aPostItAuthor( SW_RES( STR_POSTIT_AUTHOR ) ),
aPostItPage( SW_RES( STR_POSTIT_PAGE ) ),
aPostItLine( SW_RES( STR_POSTIT_LINE ) ),
aCalc_Syntax( SW_RES( STR_CALC_SYNTAX ) ),
aCalc_ZeroDiv( SW_RES( STR_CALC_ZERODIV ) ),
aCalc_Brack( SW_RES( STR_CALC_BRACK ) ),
aCalc_Pow( SW_RES( STR_CALC_POW ) ),
aCalc_VarNFnd( SW_RES( STR_CALC_VARNFND ) ),
aCalc_Overflow( SW_RES( STR_CALC_OVERFLOW ) ),
aCalc_WrongTime( SW_RES( STR_CALC_WRONGTIME ) ),
aCalc_Default( SW_RES( STR_CALC_DEFAULT ) ),
aCalc_Error( SW_RES( STR_CALC_ERROR ) ),
aGetRefFld_Up( SW_RES( STR_GETREFFLD_UP ) ),
aGetRefFld_Down( SW_RES( STR_GETREFFLD_DOWN ) ),
// --> OD 2007-09-13 #i81002#
aGetRefFld_RefItemNotFound( SW_RES( STR_GETREFFLD_REFITEMNOTFOUND ) ),
// <--
aStrAllPageHeadFoot( SW_RES( STR_ALLPAGE_HEADFOOT ) ),
aStrNone( SW_RES( STR_TEMPLATE_NONE )),
aFixedStr( SW_RES( STR_FIELD_FIXED )),
aTOXIndexName( SW_RES(STR_TOI)),
aTOXUserName( SW_RES(STR_TOU)),
aTOXContentName( SW_RES(STR_TOC)),
aTOXIllustrationsName( SW_RES(STR_TOX_ILL)),
aTOXObjectsName( SW_RES(STR_TOX_OBJ)),
aTOXTablesName( SW_RES(STR_TOX_TBL)),
aTOXAuthoritiesName( SW_RES(STR_TOX_AUTH)),
aHyperlinkClick( SW_RES( STR_HYPERLINK_CLICK)),
sPageDescFirstName( SW_RES(STR_PAGEDESC_FIRSTNAME)),
sPageDescFollowName( SW_RES(STR_PAGEDESC_FOLLOWNAME)),
sPageDescName( SW_RES(STR_PAGEDESC_NAME))
{
const USHORT nCount = FLD_DOCINFO_END - FLD_DOCINFO_BEGIN;
for(USHORT i = 0; i < nCount; ++i)
{
String* pNew = new SW_RESSTR(FLD_DOCINFO_BEGIN + i);
aDocInfoLst.Insert(pNew, aDocInfoLst.Count());
}
FreeResource();
}
ShellResource::~ShellResource()
{
if( pAutoFmtNameLst )
delete pAutoFmtNameLst, pAutoFmtNameLst = 0;
}
String ShellResource::GetPageDescName( USHORT nNo, BOOL bIsFirst, BOOL bFollow )
{
String sRet( bIsFirst ? sPageDescFirstName
: bFollow ? sPageDescFollowName
: sPageDescName );
sRet.SearchAndReplaceAscii( "$(ARG1)", String::CreateFromInt32( nNo ));
return sRet;
}
SwGlossaries* GetGlossaries()
{
if (!pGlossaries)
pGlossaries = new SwGlossaries;
return (pGlossaries);
}
BOOL HasGlossaryList()
{
return pGlossaryList != 0;
}
SwGlossaryList* GetGlossaryList()
{
if(!pGlossaryList)
pGlossaryList = new SwGlossaryList();
return pGlossaryList;
}
struct ImpAutoFmtNameListLoader : public Resource
{
ImpAutoFmtNameListLoader( SvStringsDtor& rLst );
};
void ShellResource::_GetAutoFmtNameLst() const
{
SvStringsDtor** ppLst = (SvStringsDtor**)&pAutoFmtNameLst;
*ppLst = new SvStringsDtor( STR_AUTOFMTREDL_END );
ImpAutoFmtNameListLoader aTmp( **ppLst );
}
ImpAutoFmtNameListLoader::ImpAutoFmtNameListLoader( SvStringsDtor& rLst )
: Resource( ResId(RID_SHELLRES_AUTOFMTSTRS, *pSwResMgr) )
{
for( USHORT n = 0; n < STR_AUTOFMTREDL_END; ++n )
{
String* p = new String( ResId( n + 1, *pSwResMgr) );
if(STR_AUTOFMTREDL_TYPO == n)
{
#ifdef WNT
//fuer Windows Sonderbehandlung, da MS hier ein paar Zeichen im Dialogfont vergessen hat
p->SearchAndReplace(C2S("%1"), C2S(",,"));
p->SearchAndReplace(C2S("%2"), C2S("''"));
#else
LocaleDataWrapper& rLclD = GetAppLocaleData();
//unter richtigen Betriebssystemen funktioniert es auch so
p->SearchAndReplace(C2S("%1"), rLclD.getDoubleQuotationMarkStart());
p->SearchAndReplace(C2S("%2"), rLclD.getDoubleQuotationMarkEnd());
#endif
}
rLst.Insert( p, n );
}
FreeResource();
}
/* -----------------16.09.99 12:28-------------------
--------------------------------------------------*/
const String& SwAuthorityFieldType::GetAuthFieldName(ToxAuthorityField eType)
{
if(!pAuthFieldNameList)
{
pAuthFieldNameList = new SvStringsDtor(AUTH_FIELD_END, 1);
for(USHORT i = 0; i < AUTH_FIELD_END; i++)
{
String* pTmp = new String(SW_RES(STR_AUTH_FIELD_START + i));
pAuthFieldNameList->Insert(pTmp, pAuthFieldNameList->Count());
}
}
return *pAuthFieldNameList->GetObject( static_cast< USHORT >(eType) );
}
/* -----------------16.09.99 12:29-------------------
--------------------------------------------------*/
const String& SwAuthorityFieldType::GetAuthTypeName(ToxAuthorityType eType)
{
if(!pAuthFieldTypeList)
{
pAuthFieldTypeList = new SvStringsDtor(AUTH_TYPE_END, 1);
for(USHORT i = 0; i < AUTH_TYPE_END; i++)
pAuthFieldTypeList->Insert(
new String(SW_RES(STR_AUTH_TYPE_START + i)),
pAuthFieldTypeList->Count());
}
return *pAuthFieldTypeList->GetObject( static_cast< USHORT >(eType) );
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "image.h"
#include <iostream>
#include <cstring>
#include <cstdio>
#include <fstream>
namespace embree
{
/*! read a single comment line starting with #, or read a space */
static bool readCommentLine(FILE* file)
{
int c = fgetc(file);
if (isspace(c)) return true;
if (c != '#') {
ungetc(c, file);
return false;
}
char line[1024];
if(fgets(line, sizeof(line), file) == nullptr)
THROW_RUNTIME_ERROR("Error reading PPM file!");
return true;
}
/*! read PPM file from disk */
Ref<Image> loadPPM(const FileName& fileName)
{
/* open PPM file */
FILE* file = fopen(fileName.c_str(), "rb");
if (!file) THROW_RUNTIME_ERROR("cannot open " + fileName.str());
/* read file type */
char type[8];
if (fscanf(file, "%7s", type) != 1)
THROW_RUNTIME_ERROR("Error reading " + fileName.str());
/* skip comment lines */
while (readCommentLine(file)) {};
/* read width, height, and maximal color value */
int width, height, maxColor;
if (fscanf(file, "%i %i %i", &width, &height, &maxColor) != 3)
THROW_RUNTIME_ERROR("Error reading " + fileName.str());
float rcpMaxColor = 1.0f/float(maxColor);
/* get return or space */
fgetc(file);
/* create image and fill with data */
Ref<Image> img = new Image4uc(width,height,fileName);
/* image in text format */
if (!strcmp(type, "P3"))
{
int r, g, b;
for (ssize_t y=0; y<height; y++) {
for (ssize_t x=0; x<width; x++) {
if (fscanf(file, "%i %i %i", &r, &g, &b) != 3)
THROW_RUNTIME_ERROR("Error reading " + fileName.str());
img->set(x,y,Color4(float(r)*rcpMaxColor,float(g)*rcpMaxColor,float(b)*rcpMaxColor,1.0f));
}
}
}
/* image in binary format 8 bit */
else if (!strcmp(type, "P6") && maxColor <= 255)
{
unsigned char rgb[3];
for (ssize_t y=0; y<height; y++) {
for (ssize_t x=0; x<width; x++) {
if (fread(rgb,sizeof(rgb),1,file) != 1)
THROW_RUNTIME_ERROR("Error reading " + fileName.str());
img->set(x,y,Color4(float(rgb[0])*rcpMaxColor,float(rgb[1])*rcpMaxColor,float(rgb[2])*rcpMaxColor,1.0f));
}
}
}
/* image in binary format 16 bit */
else if (!strcmp(type, "P6"))
{
unsigned short rgb[3];
for (ssize_t y=0; y<height; y++) {
for (ssize_t x=0; x<width; x++) {
if (fread(rgb,sizeof(rgb),1,file) != 1)
THROW_RUNTIME_ERROR("Error reading " + fileName.str());
img->set(x,y,Color4(float(rgb[0])*rcpMaxColor,float(rgb[1])*rcpMaxColor,float(rgb[2])*rcpMaxColor,1.0f));
}
}
}
/* invalid magic value */
else {
fclose(file);
THROW_RUNTIME_ERROR("Invalid magic value in PPM file");
}
fclose(file);
return img;
}
/*! store PPM file to disk */
void storePPM(const Ref<Image>& img, const FileName& fileName)
{
/* open file for writing */
std::fstream file;
file.open (fileName.c_str(), std::fstream::out | std::fstream::binary);
if (!file.is_open()) THROW_RUNTIME_ERROR("cannot open file " + fileName.str());
/* write file header */
file << "P6" << std::endl;
file << img->width << " " << img->height << std::endl;
file << 255 << std::endl;
/* write image */
for (size_t y=0; y<img->height; y++) {
for (size_t x=0; x<img->width; x++) {
const Color4 c = img->get(x,y);
file << (unsigned char)(clamp(c.r)*255.0f);
file << (unsigned char)(clamp(c.g)*255.0f);
file << (unsigned char)(clamp(c.b)*255.0f);
}
}
}
}
<commit_msg>using std::fstream in loadPPM<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "image.h"
#include <iostream>
#include <cstring>
#include <cstdio>
#include <fstream>
namespace embree
{
static void skipSpacesAndComments(std::fstream& file)
{
while (true)
{
if (isspace(file.peek())) {
file.ignore();
} else if (file.peek() == '#') {
std::string line; std::getline(file,line);
} else break;
}
}
/*! read PPM file from disk */
Ref<Image> loadPPM(const FileName& fileName)
{
/* open file for reading */
std::fstream file;
file.exceptions (std::fstream::failbit | std::fstream::badbit);
file.open (fileName.c_str(), std::fstream::in | std::fstream::binary);
/* read file type */
char cty[2]; file.read(cty,2);
skipSpacesAndComments(file);
std::string type(cty,2);
/* read width, height, and maximal color value */
int width; file >> width;
skipSpacesAndComments(file);
int height; file >> height;
skipSpacesAndComments(file);
int maxColor; file >> maxColor;
if (maxColor <= 0) THROW_RUNTIME_ERROR("Invalid maxColor value in PPM file");
float rcpMaxColor = 1.0f/float(maxColor);
file.ignore(); // skip space or return
/* create image and fill with data */
Ref<Image> img = new Image4uc(width,height,fileName);
/* image in text format */
if (type == "P3")
{
int r, g, b;
for (ssize_t y=0; y<height; y++) {
for (ssize_t x=0; x<width; x++) {
file >> r; file >> g; file >> b;
img->set(x,y,Color4(float(r)*rcpMaxColor,float(g)*rcpMaxColor,float(b)*rcpMaxColor,1.0f));
}
}
}
/* image in binary format 8 bit */
else if (type == "P6" && maxColor <= 255)
{
unsigned char rgb[3];
for (ssize_t y=0; y<height; y++) {
for (ssize_t x=0; x<width; x++) {
file.read((char*)rgb,sizeof(rgb));
img->set(x,y,Color4(float(rgb[0])*rcpMaxColor,float(rgb[1])*rcpMaxColor,float(rgb[2])*rcpMaxColor,1.0f));
}
}
}
/* image in binary format 16 bit */
else if (type == "P6" && maxColor <= 65535)
{
unsigned short rgb[3];
for (ssize_t y=0; y<height; y++) {
for (ssize_t x=0; x<width; x++) {
file.read((char*)rgb,sizeof(rgb));
img->set(x,y,Color4(float(rgb[0])*rcpMaxColor,float(rgb[1])*rcpMaxColor,float(rgb[2])*rcpMaxColor,1.0f));
}
}
}
/* invalid magic value */
else {
THROW_RUNTIME_ERROR("Invalid magic value in PPM file");
}
return img;
}
/*! store PPM file to disk */
void storePPM(const Ref<Image>& img, const FileName& fileName)
{
/* open file for writing */
std::fstream file;
file.exceptions (std::fstream::failbit | std::fstream::badbit);
file.open (fileName.c_str(), std::fstream::out | std::fstream::binary);
/* write file header */
file << "P6" << std::endl;
file << img->width << " " << img->height << std::endl;
file << 255 << std::endl;
/* write image */
for (size_t y=0; y<img->height; y++) {
for (size_t x=0; x<img->width; x++) {
const Color4 c = img->get(x,y);
file << (unsigned char)(clamp(c.r)*255.0f);
file << (unsigned char)(clamp(c.g)*255.0f);
file << (unsigned char)(clamp(c.b)*255.0f);
}
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: initui.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2007-04-26 09:23:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _INITUI_HXX
#include <initui.hxx>
#endif
#ifndef _EDTWIN_HXX
#include <edtwin.hxx>
#endif
#ifndef _SHELLRES_HXX
#include <shellres.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _GLOSDOC_HXX
#include <glosdoc.hxx>
#endif
#ifndef _GLOSLST_HXX
#include <gloslst.hxx>
#endif
#ifndef _UTLUI_HRC
#include <utlui.hrc>
#endif
#ifndef _INITUI_HRC
#include <initui.hrc>
#endif
#ifndef _COMCORE_HRC
#include <comcore.hrc>
#endif
#ifndef _AUTHFLD_HXX
#include <authfld.hxx>
#endif
#ifndef _DBMGR_HXX
#include <dbmgr.hxx>
#endif
#define C2S(cChar) UniString::CreateFromAscii(cChar)
/*--------------------------------------------------------------------
Beschreibung: globale Pointer
--------------------------------------------------------------------*/
SwGlossaries* pGlossaries = 0;
// Liefert alle benoetigten Pfade. Wird durch UI initialisiert
SwGlossaryList* pGlossaryList = 0;
String* pOldGrfCat = 0;
String* pOldTabCat = 0;
String* pOldFrmCat = 0;
String* pOldDrwCat = 0;
String* pCurrGlosGroup = 0;
//CHINA001 add for swui to access global variables in sw. Begin
String* GetOldGrfCat()
{
return pOldGrfCat;
}
String* GetOldTabCat()
{
return pOldTabCat;
}
String* GetOldFrmCat()
{
return pOldFrmCat;
}
String* GetOldDrwCat()
{
return pOldDrwCat;
}
String* GetCurrGlosGroup()
{
return pCurrGlosGroup;
}
void SetCurrGlosGroup(String* pStr)
{
pCurrGlosGroup = pStr;
}
//CHINA001 End for add
SvStringsDtor* pDBNameList = 0;
SvStringsDtor* pAuthFieldNameList = 0;
SvStringsDtor* pAuthFieldTypeList = 0;
/*--------------------------------------------------------------------
Beschreibung: UI beenden
--------------------------------------------------------------------*/
void _FinitUI()
{
SwNewDBMgr::RemoveDbtoolsClient();
delete ViewShell::GetShellRes();
ViewShell::SetShellRes( 0 );
SwEditWin::_FinitStaticData();
DELETEZ(pGlossaries);
delete SwFieldType::pFldNames;
delete pOldGrfCat;
delete pOldTabCat;
delete pOldFrmCat;
delete pOldDrwCat;
delete pCurrGlosGroup;
delete pDBNameList;
delete pGlossaryList;
delete pAuthFieldNameList;
delete pAuthFieldTypeList;
}
/*--------------------------------------------------------------------
Beschreibung: Initialisierung
--------------------------------------------------------------------*/
void _InitUI()
{
// ShellResource gibt der CORE die Moeglichkeit mit Resourcen zu arbeiten
ViewShell::SetShellRes( new ShellResource );
pDBNameList = new SvStringsDtor( 5, 5 );
SwEditWin::_InitStaticData();
}
ShellResource::ShellResource()
: Resource( SW_RES(RID_SW_SHELLRES) ),
aPostItPage( SW_RES( STR_POSTIT_PAGE ) ),
aPostItAuthor( SW_RES( STR_POSTIT_AUTHOR ) ),
aPostItLine( SW_RES( STR_POSTIT_LINE ) ),
aCalc_Syntax( SW_RES( STR_CALC_SYNTAX ) ),
aCalc_ZeroDiv( SW_RES( STR_CALC_ZERODIV ) ),
aCalc_Brack( SW_RES( STR_CALC_BRACK ) ),
aCalc_Pow( SW_RES( STR_CALC_POW ) ),
aCalc_VarNFnd( SW_RES( STR_CALC_VARNFND ) ),
aCalc_Overflow( SW_RES( STR_CALC_OVERFLOW ) ),
aCalc_WrongTime( SW_RES( STR_CALC_WRONGTIME ) ),
aCalc_Default( SW_RES( STR_CALC_DEFAULT ) ),
aCalc_Error( SW_RES( STR_CALC_ERROR ) ),
aGetRefFld_Up( SW_RES( STR_GETREFFLD_UP ) ),
aGetRefFld_Down( SW_RES( STR_GETREFFLD_DOWN ) ),
aStrAllPageHeadFoot( SW_RES( STR_ALLPAGE_HEADFOOT ) ),
aStrNone( SW_RES( STR_TEMPLATE_NONE )),
aFixedStr( SW_RES( STR_FIELD_FIXED )),
aTOXIndexName( SW_RES(STR_TOI)),
aTOXUserName( SW_RES(STR_TOU)),
aTOXContentName( SW_RES(STR_TOC)),
aTOXIllustrationsName( SW_RES(STR_TOX_ILL)),
aTOXObjectsName( SW_RES(STR_TOX_OBJ)),
aTOXTablesName( SW_RES(STR_TOX_TBL)),
aTOXAuthoritiesName( SW_RES(STR_TOX_AUTH)),
sPageDescFirstName( SW_RES(STR_PAGEDESC_FIRSTNAME)),
sPageDescFollowName( SW_RES(STR_PAGEDESC_FOLLOWNAME)),
sPageDescName( SW_RES(STR_PAGEDESC_NAME)),
pAutoFmtNameLst( 0 )
{
const USHORT nCount = FLD_DOCINFO_END - FLD_DOCINFO_BEGIN;
for(USHORT i = 0; i < nCount; ++i)
{
String* pNew = new SW_RESSTR(FLD_DOCINFO_BEGIN + i);
aDocInfoLst.Insert(pNew, aDocInfoLst.Count());
}
FreeResource();
}
ShellResource::~ShellResource()
{
if( pAutoFmtNameLst )
delete pAutoFmtNameLst, pAutoFmtNameLst = 0;
}
String ShellResource::GetPageDescName( USHORT nNo, BOOL bIsFirst, BOOL bFollow )
{
String sRet( bIsFirst ? sPageDescFirstName
: bFollow ? sPageDescFollowName
: sPageDescName );
sRet.SearchAndReplaceAscii( "$(ARG1)", String::CreateFromInt32( nNo ));
return sRet;
}
SwGlossaries* GetGlossaries()
{
if (!pGlossaries)
pGlossaries = new SwGlossaries;
return (pGlossaries);
}
BOOL HasGlossaryList()
{
return pGlossaryList != 0;
}
SwGlossaryList* GetGlossaryList()
{
if(!pGlossaryList)
pGlossaryList = new SwGlossaryList();
return pGlossaryList;
}
struct ImpAutoFmtNameListLoader : public Resource
{
ImpAutoFmtNameListLoader( SvStringsDtor& rLst );
};
void ShellResource::_GetAutoFmtNameLst() const
{
SvStringsDtor** ppLst = (SvStringsDtor**)&pAutoFmtNameLst;
*ppLst = new SvStringsDtor( STR_AUTOFMTREDL_END );
ImpAutoFmtNameListLoader aTmp( **ppLst );
}
ImpAutoFmtNameListLoader::ImpAutoFmtNameListLoader( SvStringsDtor& rLst )
: Resource( ResId(RID_SHELLRES_AUTOFMTSTRS, *pSwResMgr) )
{
for( USHORT n = 0; n < STR_AUTOFMTREDL_END; ++n )
{
String* p = new String( ResId( n + 1, *pSwResMgr) );
if(STR_AUTOFMTREDL_TYPO == n)
{
LocaleDataWrapper& rLclD = GetAppLocaleData();
#ifdef WNT
//fuer Windows Sonderbehandlung, da MS hier ein paar Zeichen im Dialogfont vergessen hat
p->SearchAndReplace(C2S("%1"), C2S(",,"));
p->SearchAndReplace(C2S("%2"), C2S("''"));
#else
//unter richtigen Betriebssystemen funktioniert es auch so
p->SearchAndReplace(C2S("%1"), rLclD.getDoubleQuotationMarkStart());
p->SearchAndReplace(C2S("%2"), rLclD.getDoubleQuotationMarkEnd());
#endif
}
rLst.Insert( p, n );
}
FreeResource();
}
/* -----------------16.09.99 12:28-------------------
--------------------------------------------------*/
const String& SwAuthorityFieldType::GetAuthFieldName(ToxAuthorityField eType)
{
if(!pAuthFieldNameList)
{
pAuthFieldNameList = new SvStringsDtor(AUTH_FIELD_END, 1);
for(USHORT i = 0; i < AUTH_FIELD_END; i++)
{
String* pTmp = new String(SW_RES(STR_AUTH_FIELD_START + i));
pAuthFieldNameList->Insert(pTmp, pAuthFieldNameList->Count());
}
}
return *pAuthFieldNameList->GetObject(eType);
}
/* -----------------16.09.99 12:29-------------------
--------------------------------------------------*/
const String& SwAuthorityFieldType::GetAuthTypeName(ToxAuthorityType eType)
{
if(!pAuthFieldTypeList)
{
pAuthFieldTypeList = new SvStringsDtor(AUTH_TYPE_END, 1);
for(USHORT i = 0; i < AUTH_TYPE_END; i++)
pAuthFieldTypeList->Insert(
new String(SW_RES(STR_AUTH_TYPE_START + i)),
pAuthFieldTypeList->Count());
}
return *pAuthFieldTypeList->GetObject(eType);
}
<commit_msg>INTEGRATION: CWS smarttags3 (1.11.190); FILE MERGED 2007/05/22 13:25:13 fme 1.11.190.2: RESYNC: (1.11-1.12); FILE MERGED 2007/05/12 06:31:07 fme 1.11.190.1: #i75130# New smart tag API<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: initui.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-06-27 13:28:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _INITUI_HXX
#include <initui.hxx>
#endif
#ifndef _EDTWIN_HXX
#include <edtwin.hxx>
#endif
#ifndef _SHELLRES_HXX
#include <shellres.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _GLOSDOC_HXX
#include <glosdoc.hxx>
#endif
#ifndef _GLOSLST_HXX
#include <gloslst.hxx>
#endif
#ifndef _UTLUI_HRC
#include <utlui.hrc>
#endif
#ifndef _INITUI_HRC
#include <initui.hrc>
#endif
#ifndef _COMCORE_HRC
#include <comcore.hrc>
#endif
#ifndef _AUTHFLD_HXX
#include <authfld.hxx>
#endif
#ifndef _DBMGR_HXX
#include <dbmgr.hxx>
#endif
#define C2S(cChar) UniString::CreateFromAscii(cChar)
/*--------------------------------------------------------------------
Beschreibung: globale Pointer
--------------------------------------------------------------------*/
SwGlossaries* pGlossaries = 0;
// Liefert alle benoetigten Pfade. Wird durch UI initialisiert
SwGlossaryList* pGlossaryList = 0;
String* pOldGrfCat = 0;
String* pOldTabCat = 0;
String* pOldFrmCat = 0;
String* pOldDrwCat = 0;
String* pCurrGlosGroup = 0;
//CHINA001 add for swui to access global variables in sw. Begin
String* GetOldGrfCat()
{
return pOldGrfCat;
}
String* GetOldTabCat()
{
return pOldTabCat;
}
String* GetOldFrmCat()
{
return pOldFrmCat;
}
String* GetOldDrwCat()
{
return pOldDrwCat;
}
String* GetCurrGlosGroup()
{
return pCurrGlosGroup;
}
void SetCurrGlosGroup(String* pStr)
{
pCurrGlosGroup = pStr;
}
//CHINA001 End for add
SvStringsDtor* pDBNameList = 0;
SvStringsDtor* pAuthFieldNameList = 0;
SvStringsDtor* pAuthFieldTypeList = 0;
/*--------------------------------------------------------------------
Beschreibung: UI beenden
--------------------------------------------------------------------*/
void _FinitUI()
{
SwNewDBMgr::RemoveDbtoolsClient();
delete ViewShell::GetShellRes();
ViewShell::SetShellRes( 0 );
SwEditWin::_FinitStaticData();
DELETEZ(pGlossaries);
delete SwFieldType::pFldNames;
delete pOldGrfCat;
delete pOldTabCat;
delete pOldFrmCat;
delete pOldDrwCat;
delete pCurrGlosGroup;
delete pDBNameList;
delete pGlossaryList;
delete pAuthFieldNameList;
delete pAuthFieldTypeList;
}
/*--------------------------------------------------------------------
Beschreibung: Initialisierung
--------------------------------------------------------------------*/
void _InitUI()
{
// ShellResource gibt der CORE die Moeglichkeit mit Resourcen zu arbeiten
ViewShell::SetShellRes( new ShellResource );
pDBNameList = new SvStringsDtor( 5, 5 );
SwEditWin::_InitStaticData();
}
ShellResource::ShellResource()
: Resource( SW_RES(RID_SW_SHELLRES) ),
aPostItPage( SW_RES( STR_POSTIT_PAGE ) ),
aPostItAuthor( SW_RES( STR_POSTIT_AUTHOR ) ),
aPostItLine( SW_RES( STR_POSTIT_LINE ) ),
aCalc_Syntax( SW_RES( STR_CALC_SYNTAX ) ),
aCalc_ZeroDiv( SW_RES( STR_CALC_ZERODIV ) ),
aCalc_Brack( SW_RES( STR_CALC_BRACK ) ),
aCalc_Pow( SW_RES( STR_CALC_POW ) ),
aCalc_VarNFnd( SW_RES( STR_CALC_VARNFND ) ),
aCalc_Overflow( SW_RES( STR_CALC_OVERFLOW ) ),
aCalc_WrongTime( SW_RES( STR_CALC_WRONGTIME ) ),
aCalc_Default( SW_RES( STR_CALC_DEFAULT ) ),
aCalc_Error( SW_RES( STR_CALC_ERROR ) ),
aGetRefFld_Up( SW_RES( STR_GETREFFLD_UP ) ),
aGetRefFld_Down( SW_RES( STR_GETREFFLD_DOWN ) ),
aStrAllPageHeadFoot( SW_RES( STR_ALLPAGE_HEADFOOT ) ),
aStrNone( SW_RES( STR_TEMPLATE_NONE )),
aFixedStr( SW_RES( STR_FIELD_FIXED )),
aTOXIndexName( SW_RES(STR_TOI)),
aTOXUserName( SW_RES(STR_TOU)),
aTOXContentName( SW_RES(STR_TOC)),
aTOXIllustrationsName( SW_RES(STR_TOX_ILL)),
aTOXObjectsName( SW_RES(STR_TOX_OBJ)),
aTOXTablesName( SW_RES(STR_TOX_TBL)),
aTOXAuthoritiesName( SW_RES(STR_TOX_AUTH)),
aHyperlinkClick( SW_RES( STR_HYPERLINK_CLICK)),
sPageDescFirstName( SW_RES(STR_PAGEDESC_FIRSTNAME)),
sPageDescFollowName( SW_RES(STR_PAGEDESC_FOLLOWNAME)),
sPageDescName( SW_RES(STR_PAGEDESC_NAME)),
pAutoFmtNameLst( 0 )
{
const USHORT nCount = FLD_DOCINFO_END - FLD_DOCINFO_BEGIN;
for(USHORT i = 0; i < nCount; ++i)
{
String* pNew = new SW_RESSTR(FLD_DOCINFO_BEGIN + i);
aDocInfoLst.Insert(pNew, aDocInfoLst.Count());
}
FreeResource();
}
ShellResource::~ShellResource()
{
if( pAutoFmtNameLst )
delete pAutoFmtNameLst, pAutoFmtNameLst = 0;
}
String ShellResource::GetPageDescName( USHORT nNo, BOOL bIsFirst, BOOL bFollow )
{
String sRet( bIsFirst ? sPageDescFirstName
: bFollow ? sPageDescFollowName
: sPageDescName );
sRet.SearchAndReplaceAscii( "$(ARG1)", String::CreateFromInt32( nNo ));
return sRet;
}
SwGlossaries* GetGlossaries()
{
if (!pGlossaries)
pGlossaries = new SwGlossaries;
return (pGlossaries);
}
BOOL HasGlossaryList()
{
return pGlossaryList != 0;
}
SwGlossaryList* GetGlossaryList()
{
if(!pGlossaryList)
pGlossaryList = new SwGlossaryList();
return pGlossaryList;
}
struct ImpAutoFmtNameListLoader : public Resource
{
ImpAutoFmtNameListLoader( SvStringsDtor& rLst );
};
void ShellResource::_GetAutoFmtNameLst() const
{
SvStringsDtor** ppLst = (SvStringsDtor**)&pAutoFmtNameLst;
*ppLst = new SvStringsDtor( STR_AUTOFMTREDL_END );
ImpAutoFmtNameListLoader aTmp( **ppLst );
}
ImpAutoFmtNameListLoader::ImpAutoFmtNameListLoader( SvStringsDtor& rLst )
: Resource( ResId(RID_SHELLRES_AUTOFMTSTRS, *pSwResMgr) )
{
for( USHORT n = 0; n < STR_AUTOFMTREDL_END; ++n )
{
String* p = new String( ResId( n + 1, *pSwResMgr) );
if(STR_AUTOFMTREDL_TYPO == n)
{
LocaleDataWrapper& rLclD = GetAppLocaleData();
#ifdef WNT
//fuer Windows Sonderbehandlung, da MS hier ein paar Zeichen im Dialogfont vergessen hat
p->SearchAndReplace(C2S("%1"), C2S(",,"));
p->SearchAndReplace(C2S("%2"), C2S("''"));
#else
//unter richtigen Betriebssystemen funktioniert es auch so
p->SearchAndReplace(C2S("%1"), rLclD.getDoubleQuotationMarkStart());
p->SearchAndReplace(C2S("%2"), rLclD.getDoubleQuotationMarkEnd());
#endif
}
rLst.Insert( p, n );
}
FreeResource();
}
/* -----------------16.09.99 12:28-------------------
--------------------------------------------------*/
const String& SwAuthorityFieldType::GetAuthFieldName(ToxAuthorityField eType)
{
if(!pAuthFieldNameList)
{
pAuthFieldNameList = new SvStringsDtor(AUTH_FIELD_END, 1);
for(USHORT i = 0; i < AUTH_FIELD_END; i++)
{
String* pTmp = new String(SW_RES(STR_AUTH_FIELD_START + i));
pAuthFieldNameList->Insert(pTmp, pAuthFieldNameList->Count());
}
}
return *pAuthFieldNameList->GetObject(eType);
}
/* -----------------16.09.99 12:29-------------------
--------------------------------------------------*/
const String& SwAuthorityFieldType::GetAuthTypeName(ToxAuthorityType eType)
{
if(!pAuthFieldTypeList)
{
pAuthFieldTypeList = new SvStringsDtor(AUTH_TYPE_END, 1);
for(USHORT i = 0; i < AUTH_TYPE_END; i++)
pAuthFieldTypeList->Insert(
new String(SW_RES(STR_AUTH_TYPE_START + i)),
pAuthFieldTypeList->Count());
}
return *pAuthFieldTypeList->GetObject(eType);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael X. Grey <mxgrey@gatech.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "dart/dart.h"
constexpr double default_angle = 20.0*M_PI/180.0;
constexpr double default_distance = 0.01;
constexpr double default_domino_height = 0.07;
constexpr double default_domino_width = 0.03;
using namespace dart::dynamics;
class MyWindow : public dart::gui::SimWindow
{
public:
MyWindow(dart::simulation::WorldPtr world)
{
}
void keyboard(unsigned char key, int x, int y) override
{
if(!_hasEverRun)
{
switch(key)
{
case 'q':
attemptToCreateDomino( default_angle);
case 'w':
attemptToCreateDomino(0.0);
case 'e':
attemptToCreateDomino(-default_angle);
case 'd':
deleteLastDomino();
case ' ':
_hasEverRun = true;
}
}
SimWindow::keyboard(key, x, y);
}
void attemptToCreateDomino(double angle)
{
}
void deleteLastDomino()
{
}
protected:
/// History of the dominoes that have been created
std::vector<SkeletonPtr> _dominoes;
/// History of the angles that the user has specified
std::vector<double> _angles;
/// Sum of all angles so far
double _totalAngle;
/// Set to true the first time spacebar is pressed
bool _hasEverRun;
};
int main(int argc, char* argv[])
{
}
<commit_msg>finished domino portion of the domino tutorial<commit_after>/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael X. Grey <mxgrey@gatech.edu>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "dart/dart.h"
const double default_domino_height = 0.07;
const double default_domino_width = 0.03;
const double default_domino_depth = default_domino_width/5.0;
const double default_distance = default_domino_height/2.0;
const double default_angle = 20.0*M_PI/180.0;
const double default_push_force = 8.0; // N
const int default_push_duration = 200; // # iterations
using namespace dart::dynamics;
using namespace dart::simulation;
class MyWindow : public dart::gui::SimWindow
{
public:
MyWindow(const WorldPtr& world)
: _totalAngle(0.0),
_hasEverRun(false),
_pushCountDown(0)
{
setWorld(world);
_firstDomino = world->getSkeleton("domino");
_floor = world->getSkeleton("floor");
}
void attemptToCreateDomino(double angle)
{
const SkeletonPtr& lastDomino = _dominoes.size()>0?
_dominoes.back() : _firstDomino;
// Compute the position for the new domino
Eigen::Vector3d dx = default_distance*Eigen::Vector3d(
cos(_totalAngle), sin(_totalAngle), 0.0);
Eigen::Vector6d x = lastDomino->getPositions();
x.tail<3>() += dx;
// Adjust the angle for the new domino
x[2] = _totalAngle + angle;
SkeletonPtr newDomino = _firstDomino->clone();
newDomino->setName("domino #" + std::to_string(_dominoes.size()+1));
newDomino->setPositions(x);
mWorld->addSkeleton(newDomino);
// Compute collisions
dart::collision::CollisionDetector* detector =
mWorld->getConstraintSolver()->getCollisionDetector();
detector->detectCollision(true, true);
// Look through the collisions to see if any dominoes are penetrating each
// other
bool dominoCollision = false;
size_t collisionCount = detector->getNumContacts();
for(size_t i=0; i < collisionCount; ++i)
{
// If either of the colliding BodyNodes belongs to the floor, then we know
// that we have colliding dominoes
const dart::collision::Contact& contact = detector->getContact(i);
if( contact.bodyNode1.lock()->getSkeleton() != _floor
&& contact.bodyNode2.lock()->getSkeleton() != _floor)
{
dominoCollision = true;
break;
}
}
if(dominoCollision)
{
// Remove the new domino, because it is penetrating an existing one
mWorld->removeSkeleton(newDomino);
}
else
{
// Record the latest domino addition
_angles.push_back(angle);
_dominoes.push_back(newDomino);
_totalAngle += angle;
}
}
void deleteLastDomino()
{
if(_dominoes.size() > 0)
{
SkeletonPtr lastDomino = _dominoes.back();
_dominoes.pop_back();
mWorld->removeSkeleton(lastDomino);
_totalAngle -= _angles.back();
_angles.pop_back();
}
}
void keyboard(unsigned char key, int x, int y) override
{
if(!_hasEverRun)
{
switch(key)
{
case 'q':
attemptToCreateDomino( default_angle);
break;
case 'w':
attemptToCreateDomino(0.0);
break;
case 'e':
attemptToCreateDomino(-default_angle);
break;
case 'd':
deleteLastDomino();
break;
case ' ':
_hasEverRun = true;
break;
}
}
else
{
switch(key)
{
case 'f':
_pushCountDown = default_push_duration;
break;
}
}
SimWindow::keyboard(key, x, y);
}
void timeStepping() override
{
if(_pushCountDown > 0)
{
_firstDomino->getBodyNode(0)->addExtForce(
default_push_force*Eigen::Vector3d::UnitX(),
default_domino_height/2.0*Eigen::Vector3d::UnitZ());
--_pushCountDown;
}
SimWindow::timeStepping();
}
protected:
/// Base domino. Used to clone new dominoes.
SkeletonPtr _firstDomino;
/// Floor of the scene
SkeletonPtr _floor;
/// History of the dominoes that have been created
std::vector<SkeletonPtr> _dominoes;
/// History of the angles that the user has specified
std::vector<double> _angles;
/// Sum of all angles so far
double _totalAngle;
/// Set to true the first time spacebar is pressed
bool _hasEverRun;
/// The first domino will be pushed on while the value of this is positive
int _pushCountDown;
};
SkeletonPtr createDomino()
{
/// Create a Skeleton with the name "domino"
SkeletonPtr domino = Skeleton::create("domino");
/// Create a body for the domino
BodyNodePtr body =
domino->createJointAndBodyNodePair<FreeJoint>(nullptr).second;
std::shared_ptr<BoxShape> box(
new BoxShape(Eigen::Vector3d(default_domino_depth,
default_domino_width,
default_domino_height)));
body->addVisualizationShape(box);
body->addCollisionShape(box);
domino->getDof("Joint_pos_z")->setPosition(default_domino_height/2.0);
return domino;
}
SkeletonPtr createFloor()
{
SkeletonPtr floor = Skeleton::create("floor");
// Give the floor a body
BodyNodePtr body =
floor->createJointAndBodyNodePair<WeldJoint>(nullptr).second;
// Give the body a shape
double floor_width = 10.0;
double floor_height = 0.01;
std::shared_ptr<BoxShape> box(
new BoxShape(Eigen::Vector3d(floor_width, floor_width, floor_height)));
box->setColor(dart::Color::Black());
body->addVisualizationShape(box);
body->addCollisionShape(box);
// Put the body into position
Eigen::Isometry3d tf(Eigen::Isometry3d::Identity());
tf.translation() = Eigen::Vector3d(0.0, 0.0, -floor_height/2.0);
body->getParentJoint()->setTransformFromParentBodyNode(tf);
return floor;
}
int main(int argc, char* argv[])
{
SkeletonPtr domino = createDomino();
SkeletonPtr floor = createFloor();
WorldPtr world(new World);
world->addSkeleton(domino);
world->addSkeleton(floor);
MyWindow window(world);
std::cout << "Before simulation has started, you can create new dominoes:" << std::endl;
std::cout << "'w': Create new domino angled forward" << std::endl;
std::cout << "'q': Create new domino angled to the left" << std::endl;
std::cout << "'e': Create new domino angled to the right" << std::endl;
std::cout << "'d': Delete the last domino that was created" << std::endl;
std::cout << std::endl;
std::cout << "spacebar: Begin simulation (you can no longer create dominoes)" << std::endl;
std::cout << "'f': Push the first domino so that it falls over" << std::endl;
std::cout << "'v': Turn contact force visualization on/off" << std::endl;
glutInit(&argc, argv);
window.initWindow(640, 480, "Dominoes");
glutMainLoop();
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cmath>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>
using std::begin;
using std::end;
using std::size_t;
std::vector<double> solve_euler(double timestep, size_t size) {
std::vector<double> result;
double current = 1.0;
std::generate_n(std::back_inserter(result), size, [&] {
return std::exchange(current, current - 3.0 * current * timestep);
});
return result;
}
/*
check_result takes an iterator over doubles,
and returns whether any value is outside the passed threshold.
*/
template <typename Iter>
bool check_result(Iter first, Iter last, double threshold, double timestep) {
auto it = first;
for (size_t idx = 0; it != last; ++idx, ++it) {
double solution = std::exp(-3.0 * idx * timestep);
if (std::abs(*it - solution) > threshold) {
std::cout << "We found a value outside the threshold; the " << idx
<< "-th value was " << *it << ", but the expected solution was "
<< solution << '\n';
std::cout << "(the threshold was " << threshold
<< " and the difference was " << std::abs(*it - solution)
<< ")\n";
return true;
}
}
return false;
}
int main() {
double threshold = 0.01;
double timestep = 0.01;
auto result = solve_euler(timestep, 100);
auto outside_threshold =
check_result(begin(result), end(result), threshold, timestep);
auto msg = outside_threshold ? "yes :(" : "no :D";
std::cout << "Were any of the values outside of the threshold (" << threshold
<< ")? " << msg << '\n';
}
<commit_msg>Minor clean up for Forward Euler Method in C++<commit_after>#include <algorithm>
#include <cmath>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>
using std::begin;
using std::end;
using std::size_t;
std::vector<double> solve_euler(double timestep, size_t size) {
std::vector<double> result;
double current = 1.0;
for (size_t i = 0; i < size; ++i) {
result.push_back(current);
current -= 3.0 * current * timestep;
}
return result;
}
// check_result takes an iterator over doubles,
// and returns whether any value is outside the passed threshold.
template <typename Iter>
bool check_result(Iter first, Iter last, double threshold, double timestep) {
auto it = first;
for (size_t idx = 0; it != last; ++idx, ++it) {
double solution = std::exp(-3.0 * idx * timestep);
if (std::abs(*it - solution) > threshold) {
std::cout << "We found a value outside the threshold; the " << idx
<< "-th value was " << *it << ", but the expected solution was "
<< solution << '\n';
std::cout << "(the threshold was " << threshold
<< " and the difference was " << std::abs(*it - solution)
<< ")\n";
return true;
}
}
return false;
}
int main() {
double threshold = 0.01;
double timestep = 0.01;
auto result = solve_euler(timestep, 100);
auto outside_threshold =
check_result(begin(result), end(result), threshold, timestep);
auto msg = outside_threshold ? "yes :(" : "no :D";
std::cout << "Were any of the values outside of the threshold (" << threshold
<< ")? " << msg << '\n';
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#include <hpp/core/path-optimization/simple-time-parameterization.hh>
#include <limits>
#include <pinocchio/multibody/model.hpp>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/liegroup.hh>
#include <hpp/core/interpolated-path.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/straight-path.hh>
#include <hpp/core/time-parameterization/polynomial.hh>
namespace hpp {
namespace core {
namespace pathOptimization {
using timeParameterization::Polynomial;
namespace {
TimeParameterizationPtr_t computeTimeParameterizationFirstOrder (
const value_type& s0, const value_type& s1, const value_type& B,
value_type& T)
{
vector_t a(2);
T = (s1 - s0) / B;
a[0] = s0;
a[1] = B;
hppDout (info, "Time parametrization returned " << a.transpose()
<< ", " << T);
return TimeParameterizationPtr_t (new Polynomial (a));
}
TimeParameterizationPtr_t computeTimeParameterizationThirdOrder (
const value_type& s0, const value_type& s1, const value_type& B,
value_type& T)
{
vector_t a(4);
T = 3 * (s1 - s0) / (2 * B);
a[0] = s0;
a[1] = 0;
a[2] = 3 * (s1 - s0) / (T * T);
a[3] = - 2 * a[2] / (3 * T);
hppDout (info, "Time parametrization returned " << a.transpose()
<< ", " << T);
return TimeParameterizationPtr_t (new Polynomial (a));
}
void checkTimeParameterization (const TimeParameterizationPtr_t tp,
const bool velocity, const interval_t sr, const value_type B, const value_type T)
{
using std::fabs;
const value_type thr = Eigen::NumTraits<value_type>::dummy_precision();
if ( fabs(tp->value(0) - sr.first) >= thr
|| fabs(tp->value(T) - sr.second) >= thr) {
throw std::logic_error("Boundaries of TimeParameterization are not correct.");
}
if (velocity
&& (tp->derivative(0) > thr
|| tp->derivative(T) > thr
|| fabs(tp->derivative(T/2) - B) > thr
|| tp->derivative(0) < 0
|| tp->derivative(T) < 0
|| fabs(tp->derivative(T/2) - B) < 0)
) {
throw std::logic_error("Derivative of TimeParameterization are not correct.");
}
}
}
SimpleTimeParameterizationPtr_t SimpleTimeParameterization::create (const Problem& problem)
{
SimpleTimeParameterizationPtr_t ptr (new SimpleTimeParameterization(problem));
return ptr;
}
PathVectorPtr_t SimpleTimeParameterization::optimize (const PathVectorPtr_t& path)
{
const value_type infinity = std::numeric_limits<value_type>::infinity();
const value_type safety = problem().getParameter("SimpleTimeParameterization/safety", (value_type)1);
const bool velocity = problem().getParameter("SimpleTimeParameterization/velocity", false);
// Retrieve velocity limits
const DevicePtr_t& robot = problem().robot();
size_type d = robot->numberDof() - robot->extraConfigSpace().dimension();
vector_t ub ( robot->model().velocityLimit),
lb (-robot->model().velocityLimit),
cb ((ub + lb) / 2);
assert (cb.size() == d);
// The velocity must be in [lb, ub]
ub = cb + safety * (ub - cb);
lb = cb + safety * (lb - cb);
// When ub or lb are NaN, set them to infinity.
ub = (ub.array() == ub.array()).select(ub, infinity);
lb = (lb.array() == lb.array()).select(lb, -infinity);
hppDout (info, "Lower velocity bound :" << lb.transpose());
hppDout (info, "Upper velocity bound :" << ub.transpose());
if ( ( ub.array() <= 0 ).any()
&& ( lb.array() >= 0 ).any())
throw std::invalid_argument ("The case where zero is not an admissible velocity is not implemented.");
PathVectorPtr_t input = PathVector::create(
path->outputSize(), path->outputDerivativeSize());
PathVectorPtr_t output = PathVector::create(
path->outputSize(), path->outputDerivativeSize());
path->flatten(input);
vector_t v (robot->numberDof());
vector_t v_inv (robot->numberDof());
for (std::size_t i = 0; i < input->numberPaths(); ++i) {
PathPtr_t p = input->pathAtRank(i);
interval_t paramRange = p->paramRange();
// Compute B
p->velocityBound (v, paramRange.first, paramRange.second);
v_inv = (v.array() == 0).select(infinity, v.cwiseInverse());
const value_type B = std::min(
( ub.cwiseProduct(v_inv)).minCoeff(),
(-lb.cwiseProduct(v_inv)).minCoeff());
assert (B > 0);
// Compute the polynom and total time
value_type T;
TimeParameterizationPtr_t tp;
if (velocity)
tp = computeTimeParameterizationThirdOrder (paramRange.first, paramRange.second, B, T);
else
tp = computeTimeParameterizationFirstOrder (paramRange.first, paramRange.second, B, T);
checkTimeParameterization (tp, velocity, paramRange, B, T);
PathPtr_t pp = p->copy();
pp->timeParameterization (tp, interval_t (0, T));
output->appendPath (pp);
}
return output;
}
SimpleTimeParameterization::SimpleTimeParameterization (const Problem& problem):
PathOptimizer(problem) {}
} // namespace pathOptimization
} // namespace core
} // namespace hpp
<commit_msg>Update checkParameterized in SimpleTimeParameterization<commit_after>// Copyright (c) 2017, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-core.
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core. If not, see <http://www.gnu.org/licenses/>.
#include <hpp/core/path-optimization/simple-time-parameterization.hh>
#include <limits>
#include <pinocchio/multibody/model.hpp>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/liegroup.hh>
#include <hpp/core/interpolated-path.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/straight-path.hh>
#include <hpp/core/time-parameterization/polynomial.hh>
namespace hpp {
namespace core {
namespace pathOptimization {
using timeParameterization::Polynomial;
namespace {
TimeParameterizationPtr_t computeTimeParameterizationFirstOrder (
const value_type& s0, const value_type& s1, const value_type& B,
value_type& T)
{
vector_t a(2);
T = (s1 - s0) / B;
a[0] = s0;
a[1] = B;
hppDout (info, "Time parametrization returned " << a.transpose()
<< ", " << T);
return TimeParameterizationPtr_t (new Polynomial (a));
}
TimeParameterizationPtr_t computeTimeParameterizationThirdOrder (
const value_type& s0, const value_type& s1, const value_type& B,
value_type& T)
{
vector_t a(4);
T = 3 * (s1 - s0) / (2 * B);
a[0] = s0;
a[1] = 0;
a[2] = 3 * (s1 - s0) / (T * T);
a[3] = - 2 * a[2] / (3 * T);
hppDout (info, "Time parametrization returned " << a.transpose()
<< ", " << T);
return TimeParameterizationPtr_t (new Polynomial (a));
}
void checkTimeParameterization (const TimeParameterizationPtr_t tp,
const bool velocity, const interval_t sr, const value_type B, const value_type T)
{
using std::fabs;
const value_type thr = Eigen::NumTraits<value_type>::dummy_precision();
if ( fabs(tp->value(0) - sr.first) >= thr
|| fabs(tp->value(T) - sr.second) >= thr) {
throw std::logic_error("Boundaries of TimeParameterization are not correct.");
}
if (velocity
&& (fabs(tp->derivative(0)) > thr
|| fabs(tp->derivative(T)) > thr
|| fabs(tp->derivative(T/2) - B) > thr)
) {
HPP_THROW(std::logic_error,
"Derivative of TimeParameterization are not correct:"
<< "\ntp->derivative(0) = " << tp->derivative(0)
<< "\ntp->derivative(T) = " << tp->derivative(T)
<< "\ntp->derivative(T/2) - B = " << tp->derivative(T/2) - B
<< "\nT = " << T
<< "\nB = " << B
);
}
}
}
SimpleTimeParameterizationPtr_t SimpleTimeParameterization::create (const Problem& problem)
{
SimpleTimeParameterizationPtr_t ptr (new SimpleTimeParameterization(problem));
return ptr;
}
PathVectorPtr_t SimpleTimeParameterization::optimize (const PathVectorPtr_t& path)
{
const value_type infinity = std::numeric_limits<value_type>::infinity();
const value_type safety = problem().getParameter("SimpleTimeParameterization/safety", (value_type)1);
const bool velocity = problem().getParameter("SimpleTimeParameterization/velocity", false);
// Retrieve velocity limits
const DevicePtr_t& robot = problem().robot();
size_type d = robot->numberDof() - robot->extraConfigSpace().dimension();
vector_t ub ( robot->model().velocityLimit),
lb (-robot->model().velocityLimit),
cb ((ub + lb) / 2);
assert (cb.size() == d);
// The velocity must be in [lb, ub]
ub = cb + safety * (ub - cb);
lb = cb + safety * (lb - cb);
// When ub or lb are NaN, set them to infinity.
ub = (ub.array() == ub.array()).select(ub, infinity);
lb = (lb.array() == lb.array()).select(lb, -infinity);
hppDout (info, "Lower velocity bound :" << lb.transpose());
hppDout (info, "Upper velocity bound :" << ub.transpose());
if ( ( ub.array() <= 0 ).any()
&& ( lb.array() >= 0 ).any())
throw std::invalid_argument ("The case where zero is not an admissible velocity is not implemented.");
PathVectorPtr_t input = PathVector::create(
path->outputSize(), path->outputDerivativeSize());
PathVectorPtr_t output = PathVector::create(
path->outputSize(), path->outputDerivativeSize());
path->flatten(input);
vector_t v (robot->numberDof());
vector_t v_inv (robot->numberDof());
for (std::size_t i = 0; i < input->numberPaths(); ++i) {
PathPtr_t p = input->pathAtRank(i);
interval_t paramRange = p->paramRange();
// Compute B
p->velocityBound (v, paramRange.first, paramRange.second);
v_inv = (v.array() == 0).select(infinity, v.cwiseInverse());
const value_type B = std::min(
( ub.cwiseProduct(v_inv)).minCoeff(),
(-lb.cwiseProduct(v_inv)).minCoeff());
assert (B > 0);
// Compute the polynom and total time
value_type T;
TimeParameterizationPtr_t tp;
if (velocity)
tp = computeTimeParameterizationThirdOrder (paramRange.first, paramRange.second, B, T);
else
tp = computeTimeParameterizationFirstOrder (paramRange.first, paramRange.second, B, T);
checkTimeParameterization (tp, velocity, paramRange, B, T);
PathPtr_t pp = p->copy();
pp->timeParameterization (tp, interval_t (0, T));
output->appendPath (pp);
}
return output;
}
SimpleTimeParameterization::SimpleTimeParameterization (const Problem& problem):
PathOptimizer(problem) {}
} // namespace pathOptimization
} // namespace core
} // namespace hpp
<|endoftext|> |
<commit_before>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
Redistribution and use of HOOMD-blue, in source and binary forms, with or
without modification, are permitted, provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// $Id$
// $URL$
// Maintainer: akohlmey
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
#include "HarmonicDihedralForceComputeGPU.h"
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
using namespace std;
#ifdef ENABLE_CUDA
#include "gpu_settings.h"
#endif
/*! \param pdata ParticleData to compute dihedral forces on
*/
HarmonicDihedralForceComputeGPU::HarmonicDihedralForceComputeGPU(boost::shared_ptr<SystemDefinition> sysdef)
: HarmonicDihedralForceCompute(sysdef), m_block_size(64)
{
// can't run on the GPU if there aren't any GPUs in the execution configuration
if (exec_conf.gpu.size() == 0)
{
cerr << endl << "***Error! Creating a DihedralForceComputeGPU with no GPU in the execution configuration" << endl << endl;
throw std::runtime_error("Error initializing DihedralForceComputeGPU");
}
// allocate and zero device memory
m_gpu_params.resize(exec_conf.gpu.size());
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->call(bind(cudaMallocHack, (void**)((void*)&m_gpu_params[cur_gpu]), m_dihedral_data->getNDihedralTypes()*sizeof(float4)));
exec_conf.gpu[cur_gpu]->call(bind(cudaMemset, (void*)m_gpu_params[cur_gpu], 0, m_dihedral_data->getNDihedralTypes()*sizeof(float4)));
}
m_host_params = new float4[m_dihedral_data->getNDihedralTypes()];
memset(m_host_params, 0, m_dihedral_data->getNDihedralTypes()*sizeof(float4));
}
HarmonicDihedralForceComputeGPU::~HarmonicDihedralForceComputeGPU()
{
// free memory on the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->call(bind(cudaFree, (void*)m_gpu_params[cur_gpu]));
m_gpu_params[cur_gpu] = NULL;
}
// free memory on the CPU
delete[] m_host_params;
m_host_params = NULL;
}
/*! \param type Type of the dihedral to set parameters for
\param K Stiffness parameter for the force computation
\param sign the sign of the cosine term
\param multiplicity the multiplicity of the cosine term
Sets parameters for the potential of a particular dihedral type and updates the
parameters on the GPU.
*/
void HarmonicDihedralForceComputeGPU::setParams(unsigned int type, Scalar K, int sign, unsigned int multiplicity)
{
HarmonicDihedralForceCompute::setParams(type, K, sign, multiplicity);
// update the local copy of the memory
m_host_params[type] = make_float4(float(K), float(sign), float(multiplicity), 0.0f);
// copy the parameters to the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->call(bind(cudaMemcpy, m_gpu_params[cur_gpu], m_host_params, m_dihedral_data->getNDihedralTypes()*sizeof(float4), cudaMemcpyHostToDevice));
}
/*! Internal method for computing the forces on the GPU.
\post The force data on the GPU is written with the calculated forces
\param timestep Current time step of the simulation
Calls gpu_compute_harmonic_dihedral_forces to do the dirty work.
*/
void HarmonicDihedralForceComputeGPU::computeForces(unsigned int timestep)
{
// start the profile
if (m_prof) m_prof->push(exec_conf, "Harmonic Dihedral");
vector<gpu_dihedraltable_array>& gpu_dihedraltable = m_dihedral_data->acquireGPU();
// the dihedral table is up to date: we are good to go. Call the kernel
vector<gpu_pdata_arrays>& pdata = m_pdata->acquireReadOnlyGPU();
gpu_boxsize box = m_pdata->getBoxGPU();
// run the kernel in parallel on all GPUs
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->callAsync(bind(gpu_compute_harmonic_dihedral_forces, m_gpu_forces[cur_gpu].d_data, pdata[cur_gpu], box, gpu_dihedraltable[cur_gpu], m_gpu_params[cur_gpu], m_dihedral_data->getNDihedralTypes(), m_block_size));
exec_conf.syncAll();
// the force data is now only up to date on the gpu
m_data_location = gpu;
m_pdata->release();
if (m_prof) m_prof->pop(exec_conf);
}
void export_HarmonicDihedralForceComputeGPU()
{
class_<HarmonicDihedralForceComputeGPU, boost::shared_ptr<HarmonicDihedralForceComputeGPU>, bases<HarmonicDihedralForceCompute>, boost::noncopyable >
("HarmonicDihedralForceComputeGPU", init< boost::shared_ptr<SystemDefinition> >())
.def("setBlockSize", &HarmonicDihedralForceComputeGPU::setBlockSize)
;
}
<commit_msg>fix embedded documentation.<commit_after>/*
Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition
(HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory
Iowa State University and The Regents of the University of Michigan All rights
reserved.
HOOMD-blue may contain modifications ("Contributions") provided, and to which
copyright is held, by various Contributors who have granted The Regents of the
University of Michigan the right to modify and/or distribute such Contributions.
Redistribution and use of HOOMD-blue, in source and binary forms, with or
without modification, are permitted, provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions, and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions, and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of HOOMD-blue's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR
ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// $Id$
// $URL$
// Maintainer: akohlmey
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4244 )
#endif
#include "HarmonicDihedralForceComputeGPU.h"
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
using namespace std;
#ifdef ENABLE_CUDA
#include "gpu_settings.h"
#endif
/*! \param sysdef System to compute bond forces on
*/
HarmonicDihedralForceComputeGPU::HarmonicDihedralForceComputeGPU(boost::shared_ptr<SystemDefinition> sysdef)
: HarmonicDihedralForceCompute(sysdef), m_block_size(64)
{
// can't run on the GPU if there aren't any GPUs in the execution configuration
if (exec_conf.gpu.size() == 0)
{
cerr << endl << "***Error! Creating a DihedralForceComputeGPU with no GPU in the execution configuration" << endl << endl;
throw std::runtime_error("Error initializing DihedralForceComputeGPU");
}
// allocate and zero device memory
m_gpu_params.resize(exec_conf.gpu.size());
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->call(bind(cudaMallocHack, (void**)((void*)&m_gpu_params[cur_gpu]), m_dihedral_data->getNDihedralTypes()*sizeof(float4)));
exec_conf.gpu[cur_gpu]->call(bind(cudaMemset, (void*)m_gpu_params[cur_gpu], 0, m_dihedral_data->getNDihedralTypes()*sizeof(float4)));
}
m_host_params = new float4[m_dihedral_data->getNDihedralTypes()];
memset(m_host_params, 0, m_dihedral_data->getNDihedralTypes()*sizeof(float4));
}
HarmonicDihedralForceComputeGPU::~HarmonicDihedralForceComputeGPU()
{
// free memory on the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->call(bind(cudaFree, (void*)m_gpu_params[cur_gpu]));
m_gpu_params[cur_gpu] = NULL;
}
// free memory on the CPU
delete[] m_host_params;
m_host_params = NULL;
}
/*! \param type Type of the dihedral to set parameters for
\param K Stiffness parameter for the force computation
\param sign the sign of the cosine term
\param multiplicity the multiplicity of the cosine term
Sets parameters for the potential of a particular dihedral type and updates the
parameters on the GPU.
*/
void HarmonicDihedralForceComputeGPU::setParams(unsigned int type, Scalar K, int sign, unsigned int multiplicity)
{
HarmonicDihedralForceCompute::setParams(type, K, sign, multiplicity);
// update the local copy of the memory
m_host_params[type] = make_float4(float(K), float(sign), float(multiplicity), 0.0f);
// copy the parameters to the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->call(bind(cudaMemcpy, m_gpu_params[cur_gpu], m_host_params, m_dihedral_data->getNDihedralTypes()*sizeof(float4), cudaMemcpyHostToDevice));
}
/*! Internal method for computing the forces on the GPU.
\post The force data on the GPU is written with the calculated forces
\param timestep Current time step of the simulation
Calls gpu_compute_harmonic_dihedral_forces to do the dirty work.
*/
void HarmonicDihedralForceComputeGPU::computeForces(unsigned int timestep)
{
// start the profile
if (m_prof) m_prof->push(exec_conf, "Harmonic Dihedral");
vector<gpu_dihedraltable_array>& gpu_dihedraltable = m_dihedral_data->acquireGPU();
// the dihedral table is up to date: we are good to go. Call the kernel
vector<gpu_pdata_arrays>& pdata = m_pdata->acquireReadOnlyGPU();
gpu_boxsize box = m_pdata->getBoxGPU();
// run the kernel in parallel on all GPUs
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->callAsync(bind(gpu_compute_harmonic_dihedral_forces, m_gpu_forces[cur_gpu].d_data, pdata[cur_gpu], box, gpu_dihedraltable[cur_gpu], m_gpu_params[cur_gpu], m_dihedral_data->getNDihedralTypes(), m_block_size));
exec_conf.syncAll();
// the force data is now only up to date on the gpu
m_data_location = gpu;
m_pdata->release();
if (m_prof) m_prof->pop(exec_conf);
}
void export_HarmonicDihedralForceComputeGPU()
{
class_<HarmonicDihedralForceComputeGPU, boost::shared_ptr<HarmonicDihedralForceComputeGPU>, bases<HarmonicDihedralForceCompute>, boost::noncopyable >
("HarmonicDihedralForceComputeGPU", init< boost::shared_ptr<SystemDefinition> >())
.def("setBlockSize", &HarmonicDihedralForceComputeGPU::setBlockSize)
;
}
<|endoftext|> |
<commit_before>/*
* Classify characters in a HTML/XML document.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef HTML_CHARS_HXX
#define HTML_CHARS_HXX
#include "strutil.h"
static inline bool
is_html_name_start_char(char ch)
{
return char_is_letter(ch) ||
ch == ':' || ch == '_';
}
static inline bool
is_html_name_char(char ch)
{
return is_html_name_start_char(ch) || char_is_digit(ch) ||
ch == '-' || ch == '.';
}
#endif
<commit_msg>html_chars: use util/CharUtil.hxx<commit_after>/*
* Classify characters in a HTML/XML document.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef HTML_CHARS_HXX
#define HTML_CHARS_HXX
#include "util/CharUtil.hxx"
static constexpr inline bool
is_html_name_start_char(char ch)
{
return IsAlphaASCII(ch) ||
ch == ':' || ch == '_';
}
static constexpr inline bool
is_html_name_char(char ch)
{
return is_html_name_start_char(ch) || IsDigitASCII(ch) ||
ch == '-' || ch == '.';
}
#endif
<|endoftext|> |
<commit_before>#include <utility>
#include "halley/tools/assets/import_assets_database.h"
#include "halley/bytes/byte_serializer.h"
#include "halley/resources/resource_data.h"
#include "halley/tools/file/filesystem.h"
constexpr static int currentAssetVersion = 73;
using namespace Halley;
AssetPath::AssetPath()
{}
AssetPath::AssetPath(TimestampedPath path)
: path(std::move(path))
{}
AssetPath::AssetPath(TimestampedPath path, Path dataPath)
: path(std::move(path))
, dataPath(std::move(dataPath))
{}
const Path& AssetPath::getPath() const
{
return path.first;
}
const Path& AssetPath::getDataPath() const
{
return dataPath.isEmpty() ? path.first : dataPath;
}
int64_t AssetPath::getTimestamp() const
{
return path.second;
}
void AssetPath::serialize(Serializer& s) const
{
s << path;
s << dataPath;
}
void AssetPath::deserialize(Deserializer& s)
{
s >> path;
s >> dataPath;
}
void ImportAssetsDatabaseEntry::serialize(Serializer& s) const
{
s << assetId;
s << srcDir;
s << inputFiles;
s << additionalInputFiles;
s << outputFiles;
int t = int(assetType);
s << t;
}
void ImportAssetsDatabaseEntry::deserialize(Deserializer& s)
{
s >> assetId;
s >> srcDir;
s >> inputFiles;
s >> additionalInputFiles;
s >> outputFiles;
int t;
s >> t;
assetType = ImportAssetType(t);
}
void ImportAssetsDatabase::AssetEntry::serialize(Serializer& s) const
{
s << asset;
}
void ImportAssetsDatabase::AssetEntry::deserialize(Deserializer& s)
{
s >> asset;
}
void ImportAssetsDatabase::InputFileEntry::serialize(Serializer& s) const
{
const int nTimestamps = int(timestamp.size());
s << nTimestamps;
for (int i = 0; i < nTimestamps; ++i) {
s << timestamp[i];
}
s << metadata;
s << basePath;
}
void ImportAssetsDatabase::InputFileEntry::deserialize(Deserializer& s)
{
int nTimestamps;
s >> nTimestamps;
for (int i = 0; i < nTimestamps; ++i) {
if (i < int(timestamp.size())) {
s >> timestamp[i];
}
}
for (int i = nTimestamps; i < int(timestamp.size()); ++i) {
timestamp[i] = 0;
}
s >> metadata;
s >> basePath;
}
ImportAssetsDatabase::ImportAssetsDatabase(Path directory, Path dbFile, Path assetsDbFile, std::vector<String> platforms)
: platforms(std::move(platforms))
, directory(std::move(directory))
, dbFile(std::move(dbFile))
, assetsDbFile(std::move(assetsDbFile))
{
load();
}
void ImportAssetsDatabase::load()
{
std::lock_guard<std::mutex> lock(mutex);
auto data = FileSystem::readFile(dbFile);
if (data.size() > 0) {
auto s = Deserializer(data);
deserialize(s);
}
}
void ImportAssetsDatabase::save() const
{
std::lock_guard<std::mutex> lock(mutex);
FileSystem::writeFile(dbFile, Serializer::toBytes(*this));
const auto pcAssetDatabase = makeAssetDatabase("pc");
FileSystem::writeFile(assetsDbFile, Serializer::toBytes(*pcAssetDatabase));
}
bool ImportAssetsDatabase::needToLoadInputMetadata(const Path& path, std::array<int64_t, 3> timestamps) const
{
std::lock_guard<std::mutex> lock(mutex);
// Is it an unknown file?
const auto iter = inputFiles.find(path.toString());
if (iter == inputFiles.end()) {
return true;
}
// Any of the timestamps changed?
for (size_t i = 0; i < timestamps.size(); ++i) {
if (iter->second.timestamp[i] != timestamps[i]) {
return true;
}
}
return false;
}
void ImportAssetsDatabase::setInputFileMetadata(const Path& path, std::array<int64_t, 3> timestamps, const Metadata& data, Path basePath)
{
std::lock_guard<std::mutex> lock(mutex);
auto& input = inputFiles[path.toString()];
input.timestamp = timestamps;
input.metadata = data;
input.basePath = std::move(basePath);
input.missing = false;
}
void ImportAssetsDatabase::markInputPresent(const Path& path)
{
std::lock_guard<std::mutex> lock(mutex);
auto& input = inputFiles[path.toString()];
input.missing = false;
}
void ImportAssetsDatabase::markAllInputFilesAsMissing()
{
std::lock_guard<std::mutex> lock(mutex);
for (auto& i: inputFiles) {
i.second.missing = true;
}
}
bool ImportAssetsDatabase::purgeMissingInputs()
{
std::lock_guard<std::mutex> lock(mutex);
bool modified = false;
for (auto iter = inputFiles.begin(); iter != inputFiles.end();) {
if (iter->second.missing) {
modified = true;
iter = inputFiles.erase(iter);
} else {
++iter;
}
}
return modified;
}
std::optional<Metadata> ImportAssetsDatabase::getMetadata(const Path& path) const
{
std::lock_guard<std::mutex> lock(mutex);
const auto pathStr = path.toString();
const auto iter = inputFiles.find(pathStr);
if (iter == inputFiles.end()) {
return {};
} else {
return iter->second.metadata;
}
}
std::optional<Metadata> ImportAssetsDatabase::getMetadata(AssetType type, const String& assetId) const
{
// This method is not very efficient
std::lock_guard<std::mutex> lock(mutex);
for (auto& a: assetsImported) {
const auto& asset = a.second.asset;
for (auto& o: asset.outputFiles) {
if (o.type == type && o.name == assetId) {
const auto inputFile = o.primaryInputFile.isEmpty() ? asset.inputFiles.at(0).getPath() : o.primaryInputFile;
const auto iter = inputFiles.find(inputFile.toString());
if (iter == inputFiles.end()) {
return {};
}
return iter->second.metadata;
}
}
}
return {};
}
Path ImportAssetsDatabase::getPrimaryInputFile(AssetType type, const String& assetId) const
{
// This method is not very efficient
std::lock_guard<std::mutex> lock(mutex);
for (auto& a: assetsImported) {
const auto& asset = a.second.asset;
for (auto& o: asset.outputFiles) {
if (o.type == type && o.name == assetId) {
return o.primaryInputFile.isEmpty() ? asset.inputFiles.at(0).getPath() : o.primaryInputFile;
}
}
}
return {};
}
bool ImportAssetsDatabase::needsImporting(const ImportAssetsDatabaseEntry& asset) const
{
std::lock_guard<std::mutex> lock(mutex);
// Check if it failed loading last time
auto iter = assetsFailed.find(asset.assetId);
bool failed = iter != assetsFailed.end();
if (!failed) {
// No failures, check if this was imported before
iter = assetsImported.find(asset.assetId);
if (iter == assetsImported.end()) {
// Asset didn't even exist before
return true;
}
}
// At this point, iter points to the failed one if it failed, or the the old successful one if it didn't.
auto& oldAsset = iter->second.asset;
// Input directory changed?
if (asset.srcDir != oldAsset.srcDir) {
return true;
}
// Total count of input files changed?
if (asset.inputFiles.size() != oldAsset.inputFiles.size()) {
return true;
}
// Any of the input files changed?
// Note: We don't have to check old files on new input, because the size matches and all entries matched.
for (auto& i: asset.inputFiles) {
auto result = std::find_if(oldAsset.inputFiles.begin(), oldAsset.inputFiles.end(), [&](const AssetPath& entry) { return entry.getDataPath() == i.getDataPath(); });
if (result == oldAsset.inputFiles.end()) {
// File wasn't there before
return true;
} else if (result->getTimestamp() != i.getTimestamp()) {
// Timestamp changed
return true;
}
}
// Any of the additional input files changed?
for (auto& i: oldAsset.additionalInputFiles) {
if (!FileSystem::exists(i.first)) {
// File removed
return true;
} else if (FileSystem::getLastWriteTime(i.first) != i.second) {
// Timestamp changed
return true;
}
}
// Have any of the output files gone missing?
if (!failed) {
for (auto& o: oldAsset.outputFiles) {
for (auto& version: o.platformVersions) {
if (!FileSystem::exists(directory / version.second.filepath)) {
return true;
}
}
}
}
return false;
}
void ImportAssetsDatabase::markAsImported(const ImportAssetsDatabaseEntry& asset)
{
AssetEntry entry;
entry.asset = asset;
entry.present = true;
std::lock_guard<std::mutex> lock(mutex);
assetsImported[asset.assetId] = entry;
auto failIter = assetsFailed.find(asset.assetId);
if (failIter != assetsFailed.end()) {
assetsFailed.erase(failIter);
}
}
void ImportAssetsDatabase::markDeleted(const ImportAssetsDatabaseEntry& asset)
{
std::lock_guard<std::mutex> lock(mutex);
assetsImported.erase(asset.assetId);
}
void ImportAssetsDatabase::markFailed(const ImportAssetsDatabaseEntry& asset)
{
AssetEntry entry;
entry.asset = asset;
entry.present = true;
std::lock_guard<std::mutex> lock(mutex);
assetsFailed[asset.assetId] = entry;
}
void ImportAssetsDatabase::markAssetsAsStillPresent(const std::map<String, ImportAssetsDatabaseEntry>& assets)
{
std::lock_guard<std::mutex> lock(mutex);
for (auto& e: assetsImported) {
e.second.present = assets.find(e.first) != assets.end();
}
}
std::vector<ImportAssetsDatabaseEntry> ImportAssetsDatabase::getAllMissing() const
{
std::lock_guard<std::mutex> lock(mutex);
std::vector<ImportAssetsDatabaseEntry> result;
for (auto& e : assetsImported) {
if (!e.second.present) {
result.push_back(e.second.asset);
}
}
return result;
}
std::vector<AssetResource> ImportAssetsDatabase::getOutFiles(String assetId) const
{
std::lock_guard<std::mutex> lock(mutex);
auto iter = assetsImported.find(assetId);
if (iter != assetsImported.end()) {
return iter->second.asset.outputFiles;
} else {
return {};
}
}
std::vector<String> ImportAssetsDatabase::getInputFiles() const
{
std::lock_guard<std::mutex> lock(mutex);
std::vector<String> result;
for (auto& i: inputFiles) {
result.push_back(i.first);
}
return result;
}
std::vector<std::pair<AssetType, String>> ImportAssetsDatabase::getAssetsFromFile(const Path& inputFile)
{
std::lock_guard<std::mutex> lock(mutex);
std::vector<std::pair<AssetType, String>> result;
for (auto& a: assetsImported) {
const auto& asset = a.second.asset;
for (auto& in: asset.inputFiles) {
if (in.getPath() == inputFile) {
for (auto& out: asset.outputFiles) {
if (out.primaryInputFile.isEmpty() || out.primaryInputFile == inputFile) {
result.emplace_back(out.type, out.name);
}
}
}
}
}
return result;
}
void ImportAssetsDatabase::serialize(Serializer& s) const
{
int version = currentAssetVersion;
s << version;
s << platforms;
s << assetsImported;
s << inputFiles;
}
void ImportAssetsDatabase::deserialize(Deserializer& s)
{
int version;
s >> version;
if (version == currentAssetVersion) {
std::vector<String> platformsRead;
s >> platformsRead;
if (platformsRead == platforms) {
s >> assetsImported;
s >> inputFiles;
}
}
}
std::unique_ptr<AssetDatabase> ImportAssetsDatabase::makeAssetDatabase(const String& platform) const
{
auto result = std::make_unique<AssetDatabase>();
for (auto& a: assetsImported) {
auto& asset = a.second.asset;
for (auto& o: asset.outputFiles) {
auto iter = o.platformVersions.find(platform);
const AssetResource::PlatformVersion* version = nullptr;
if (iter != o.platformVersions.end()) {
version = &iter->second;
} else {
iter = o.platformVersions.find("pc");
if (iter != o.platformVersions.end()) {
version = &iter->second;
}
}
if (version) {
result->addAsset(o.name, o.type, AssetDatabase::Entry(version->filepath, version->metadata));
}
}
}
return result;
}
<commit_msg>bump asset version<commit_after>#include <utility>
#include "halley/tools/assets/import_assets_database.h"
#include "halley/bytes/byte_serializer.h"
#include "halley/resources/resource_data.h"
#include "halley/tools/file/filesystem.h"
constexpr static int currentAssetVersion = 74;
using namespace Halley;
AssetPath::AssetPath()
{}
AssetPath::AssetPath(TimestampedPath path)
: path(std::move(path))
{}
AssetPath::AssetPath(TimestampedPath path, Path dataPath)
: path(std::move(path))
, dataPath(std::move(dataPath))
{}
const Path& AssetPath::getPath() const
{
return path.first;
}
const Path& AssetPath::getDataPath() const
{
return dataPath.isEmpty() ? path.first : dataPath;
}
int64_t AssetPath::getTimestamp() const
{
return path.second;
}
void AssetPath::serialize(Serializer& s) const
{
s << path;
s << dataPath;
}
void AssetPath::deserialize(Deserializer& s)
{
s >> path;
s >> dataPath;
}
void ImportAssetsDatabaseEntry::serialize(Serializer& s) const
{
s << assetId;
s << srcDir;
s << inputFiles;
s << additionalInputFiles;
s << outputFiles;
int t = int(assetType);
s << t;
}
void ImportAssetsDatabaseEntry::deserialize(Deserializer& s)
{
s >> assetId;
s >> srcDir;
s >> inputFiles;
s >> additionalInputFiles;
s >> outputFiles;
int t;
s >> t;
assetType = ImportAssetType(t);
}
void ImportAssetsDatabase::AssetEntry::serialize(Serializer& s) const
{
s << asset;
}
void ImportAssetsDatabase::AssetEntry::deserialize(Deserializer& s)
{
s >> asset;
}
void ImportAssetsDatabase::InputFileEntry::serialize(Serializer& s) const
{
const int nTimestamps = int(timestamp.size());
s << nTimestamps;
for (int i = 0; i < nTimestamps; ++i) {
s << timestamp[i];
}
s << metadata;
s << basePath;
}
void ImportAssetsDatabase::InputFileEntry::deserialize(Deserializer& s)
{
int nTimestamps;
s >> nTimestamps;
for (int i = 0; i < nTimestamps; ++i) {
if (i < int(timestamp.size())) {
s >> timestamp[i];
}
}
for (int i = nTimestamps; i < int(timestamp.size()); ++i) {
timestamp[i] = 0;
}
s >> metadata;
s >> basePath;
}
ImportAssetsDatabase::ImportAssetsDatabase(Path directory, Path dbFile, Path assetsDbFile, std::vector<String> platforms)
: platforms(std::move(platforms))
, directory(std::move(directory))
, dbFile(std::move(dbFile))
, assetsDbFile(std::move(assetsDbFile))
{
load();
}
void ImportAssetsDatabase::load()
{
std::lock_guard<std::mutex> lock(mutex);
auto data = FileSystem::readFile(dbFile);
if (data.size() > 0) {
auto s = Deserializer(data);
deserialize(s);
}
}
void ImportAssetsDatabase::save() const
{
std::lock_guard<std::mutex> lock(mutex);
FileSystem::writeFile(dbFile, Serializer::toBytes(*this));
const auto pcAssetDatabase = makeAssetDatabase("pc");
FileSystem::writeFile(assetsDbFile, Serializer::toBytes(*pcAssetDatabase));
}
bool ImportAssetsDatabase::needToLoadInputMetadata(const Path& path, std::array<int64_t, 3> timestamps) const
{
std::lock_guard<std::mutex> lock(mutex);
// Is it an unknown file?
const auto iter = inputFiles.find(path.toString());
if (iter == inputFiles.end()) {
return true;
}
// Any of the timestamps changed?
for (size_t i = 0; i < timestamps.size(); ++i) {
if (iter->second.timestamp[i] != timestamps[i]) {
return true;
}
}
return false;
}
void ImportAssetsDatabase::setInputFileMetadata(const Path& path, std::array<int64_t, 3> timestamps, const Metadata& data, Path basePath)
{
std::lock_guard<std::mutex> lock(mutex);
auto& input = inputFiles[path.toString()];
input.timestamp = timestamps;
input.metadata = data;
input.basePath = std::move(basePath);
input.missing = false;
}
void ImportAssetsDatabase::markInputPresent(const Path& path)
{
std::lock_guard<std::mutex> lock(mutex);
auto& input = inputFiles[path.toString()];
input.missing = false;
}
void ImportAssetsDatabase::markAllInputFilesAsMissing()
{
std::lock_guard<std::mutex> lock(mutex);
for (auto& i: inputFiles) {
i.second.missing = true;
}
}
bool ImportAssetsDatabase::purgeMissingInputs()
{
std::lock_guard<std::mutex> lock(mutex);
bool modified = false;
for (auto iter = inputFiles.begin(); iter != inputFiles.end();) {
if (iter->second.missing) {
modified = true;
iter = inputFiles.erase(iter);
} else {
++iter;
}
}
return modified;
}
std::optional<Metadata> ImportAssetsDatabase::getMetadata(const Path& path) const
{
std::lock_guard<std::mutex> lock(mutex);
const auto pathStr = path.toString();
const auto iter = inputFiles.find(pathStr);
if (iter == inputFiles.end()) {
return {};
} else {
return iter->second.metadata;
}
}
std::optional<Metadata> ImportAssetsDatabase::getMetadata(AssetType type, const String& assetId) const
{
// This method is not very efficient
std::lock_guard<std::mutex> lock(mutex);
for (auto& a: assetsImported) {
const auto& asset = a.second.asset;
for (auto& o: asset.outputFiles) {
if (o.type == type && o.name == assetId) {
const auto inputFile = o.primaryInputFile.isEmpty() ? asset.inputFiles.at(0).getPath() : o.primaryInputFile;
const auto iter = inputFiles.find(inputFile.toString());
if (iter == inputFiles.end()) {
return {};
}
return iter->second.metadata;
}
}
}
return {};
}
Path ImportAssetsDatabase::getPrimaryInputFile(AssetType type, const String& assetId) const
{
// This method is not very efficient
std::lock_guard<std::mutex> lock(mutex);
for (auto& a: assetsImported) {
const auto& asset = a.second.asset;
for (auto& o: asset.outputFiles) {
if (o.type == type && o.name == assetId) {
return o.primaryInputFile.isEmpty() ? asset.inputFiles.at(0).getPath() : o.primaryInputFile;
}
}
}
return {};
}
bool ImportAssetsDatabase::needsImporting(const ImportAssetsDatabaseEntry& asset) const
{
std::lock_guard<std::mutex> lock(mutex);
// Check if it failed loading last time
auto iter = assetsFailed.find(asset.assetId);
bool failed = iter != assetsFailed.end();
if (!failed) {
// No failures, check if this was imported before
iter = assetsImported.find(asset.assetId);
if (iter == assetsImported.end()) {
// Asset didn't even exist before
return true;
}
}
// At this point, iter points to the failed one if it failed, or the the old successful one if it didn't.
auto& oldAsset = iter->second.asset;
// Input directory changed?
if (asset.srcDir != oldAsset.srcDir) {
return true;
}
// Total count of input files changed?
if (asset.inputFiles.size() != oldAsset.inputFiles.size()) {
return true;
}
// Any of the input files changed?
// Note: We don't have to check old files on new input, because the size matches and all entries matched.
for (auto& i: asset.inputFiles) {
auto result = std::find_if(oldAsset.inputFiles.begin(), oldAsset.inputFiles.end(), [&](const AssetPath& entry) { return entry.getDataPath() == i.getDataPath(); });
if (result == oldAsset.inputFiles.end()) {
// File wasn't there before
return true;
} else if (result->getTimestamp() != i.getTimestamp()) {
// Timestamp changed
return true;
}
}
// Any of the additional input files changed?
for (auto& i: oldAsset.additionalInputFiles) {
if (!FileSystem::exists(i.first)) {
// File removed
return true;
} else if (FileSystem::getLastWriteTime(i.first) != i.second) {
// Timestamp changed
return true;
}
}
// Have any of the output files gone missing?
if (!failed) {
for (auto& o: oldAsset.outputFiles) {
for (auto& version: o.platformVersions) {
if (!FileSystem::exists(directory / version.second.filepath)) {
return true;
}
}
}
}
return false;
}
void ImportAssetsDatabase::markAsImported(const ImportAssetsDatabaseEntry& asset)
{
AssetEntry entry;
entry.asset = asset;
entry.present = true;
std::lock_guard<std::mutex> lock(mutex);
assetsImported[asset.assetId] = entry;
auto failIter = assetsFailed.find(asset.assetId);
if (failIter != assetsFailed.end()) {
assetsFailed.erase(failIter);
}
}
void ImportAssetsDatabase::markDeleted(const ImportAssetsDatabaseEntry& asset)
{
std::lock_guard<std::mutex> lock(mutex);
assetsImported.erase(asset.assetId);
}
void ImportAssetsDatabase::markFailed(const ImportAssetsDatabaseEntry& asset)
{
AssetEntry entry;
entry.asset = asset;
entry.present = true;
std::lock_guard<std::mutex> lock(mutex);
assetsFailed[asset.assetId] = entry;
}
void ImportAssetsDatabase::markAssetsAsStillPresent(const std::map<String, ImportAssetsDatabaseEntry>& assets)
{
std::lock_guard<std::mutex> lock(mutex);
for (auto& e: assetsImported) {
e.second.present = assets.find(e.first) != assets.end();
}
}
std::vector<ImportAssetsDatabaseEntry> ImportAssetsDatabase::getAllMissing() const
{
std::lock_guard<std::mutex> lock(mutex);
std::vector<ImportAssetsDatabaseEntry> result;
for (auto& e : assetsImported) {
if (!e.second.present) {
result.push_back(e.second.asset);
}
}
return result;
}
std::vector<AssetResource> ImportAssetsDatabase::getOutFiles(String assetId) const
{
std::lock_guard<std::mutex> lock(mutex);
auto iter = assetsImported.find(assetId);
if (iter != assetsImported.end()) {
return iter->second.asset.outputFiles;
} else {
return {};
}
}
std::vector<String> ImportAssetsDatabase::getInputFiles() const
{
std::lock_guard<std::mutex> lock(mutex);
std::vector<String> result;
for (auto& i: inputFiles) {
result.push_back(i.first);
}
return result;
}
std::vector<std::pair<AssetType, String>> ImportAssetsDatabase::getAssetsFromFile(const Path& inputFile)
{
std::lock_guard<std::mutex> lock(mutex);
std::vector<std::pair<AssetType, String>> result;
for (auto& a: assetsImported) {
const auto& asset = a.second.asset;
for (auto& in: asset.inputFiles) {
if (in.getPath() == inputFile) {
for (auto& out: asset.outputFiles) {
if (out.primaryInputFile.isEmpty() || out.primaryInputFile == inputFile) {
result.emplace_back(out.type, out.name);
}
}
}
}
}
return result;
}
void ImportAssetsDatabase::serialize(Serializer& s) const
{
int version = currentAssetVersion;
s << version;
s << platforms;
s << assetsImported;
s << inputFiles;
}
void ImportAssetsDatabase::deserialize(Deserializer& s)
{
int version;
s >> version;
if (version == currentAssetVersion) {
std::vector<String> platformsRead;
s >> platformsRead;
if (platformsRead == platforms) {
s >> assetsImported;
s >> inputFiles;
}
}
}
std::unique_ptr<AssetDatabase> ImportAssetsDatabase::makeAssetDatabase(const String& platform) const
{
auto result = std::make_unique<AssetDatabase>();
for (auto& a: assetsImported) {
auto& asset = a.second.asset;
for (auto& o: asset.outputFiles) {
auto iter = o.platformVersions.find(platform);
const AssetResource::PlatformVersion* version = nullptr;
if (iter != o.platformVersions.end()) {
version = &iter->second;
} else {
iter = o.platformVersions.find("pc");
if (iter != o.platformVersions.end()) {
version = &iter->second;
}
}
if (version) {
result->addAsset(o.name, o.type, AssetDatabase::Entry(version->filepath, version->metadata));
}
}
}
return result;
}
<|endoftext|> |
<commit_before>
#include "system.h"
#include <array>
#include <iostream>
#include <string>
#include <cstdio>
namespace
{
std::string exec(const std::string& cmd)
{
std::array<char, 128> buffer;
std::string result;
// std::cout << "Opening reading pipe" << std::endl;
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe)
{
std::cerr << "Couldn't start command." << std::endl;
return "";
}
while (fgets(buffer.data(), 128, pipe) != NULL)
{
// std::cout << "Reading..." << std::endl;
result += buffer.data();
}
/*auto returnCode =*/pclose(pipe);
// std::cout << result << std::endl;
// std::cout << returnCode << std::endl;
return result;
}
void check_package(const std::string& pckg_name)
{
std::string cmd = "dpkg-query --showformat='${Version}' --show " + pckg_name + " 2>&1";
std::string dpkg = exec(cmd);
if (dpkg.find("no packages found") != std::string::npos)
{
std::cout << pckg_name << " is not installed."
<< "\n";
}
else
{
std::cout << pckg_name << ": " << dpkg << "\n";
}
}
void check_system_info(const std::string& info)
{
if (info.find("is not installed") != std::string::npos)
{
std::cout << "Executing '" << info << "' requires sudo."
<< "\n\n";
}
std::string cmd = info + " 2>&1";
std::string out = exec(cmd);
std::cout << "======= " << info << "\n\n";
std::cout << out << "\n\n";
}
} // namespace
void tcam::tools::print_packages()
{
if (system("which dpkg-query > /dev/null 2>&1"))
{
std::cerr << "dplg-query could not be found. No package information available." << std::endl;
return;
}
check_package("tiscamera");
check_package("tiscamera-tcamprop");
check_package("tiscamera-dutils");
check_package("tispimipisrc");
check_package("tistegrasrc");
check_package("ic_barcode");
}
void tcam::tools::print_system_info_general()
{
check_system_info("lsb_release -a");
check_system_info("uname -a");
// check_system_info("sudo lshw");
check_system_info("lscpu");
}
void tcam::tools::print_system_info_gige()
{
check_system_info("ip a");
}
void tcam::tools::print_system_info_usb()
{
check_system_info("lsusb");
check_system_info("lsusb -t");
}
void tcam::tools::print_system_info()
{
std::cout << "=============" << std::endl;
std::cout << "= General =" << std::endl;
std::cout << "=============" << std::endl;
print_system_info_general();
std::cout << "=============" << std::endl;
std::cout << "= USB =" << std::endl;
std::cout << "=============" << std::endl;
print_system_info_usb();
std::cout << "=============" << std::endl;
std::cout << "= Network =" << std::endl;
std::cout << "=============" << std::endl;
print_system_info_gige();
std::cout << "=============" << std::endl;
std::cout << "= Packaging =" << std::endl;
std::cout << "=============" << std::endl;
print_packages();
std::cout << std::endl;
std::cerr << "Please review the printed information to ensure" << std::endl
<< "that nothing you consider confidential is given to other parties." << std::endl;
}
<commit_msg>tcam-ctrl: Change names of the packages listed to agreed upon list<commit_after>
#include "system.h"
#include <array>
#include <iostream>
#include <string>
#include <cstdio>
namespace
{
std::string exec(const std::string& cmd)
{
std::array<char, 128> buffer;
std::string result;
// std::cout << "Opening reading pipe" << std::endl;
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe)
{
std::cerr << "Couldn't start command." << std::endl;
return "";
}
while (fgets(buffer.data(), 128, pipe) != NULL)
{
// std::cout << "Reading..." << std::endl;
result += buffer.data();
}
/*auto returnCode =*/pclose(pipe);
// std::cout << result << std::endl;
// std::cout << returnCode << std::endl;
return result;
}
void check_package(const std::string& pckg_name)
{
std::string cmd = "dpkg-query --showformat='${Version}' --show " + pckg_name + " 2>&1";
std::string dpkg = exec(cmd);
if (dpkg.find("no packages found") != std::string::npos)
{
std::cout << pckg_name << " is not installed."
<< "\n";
}
else
{
std::cout << pckg_name << ": " << dpkg << "\n";
}
}
void check_system_info(const std::string& info)
{
if (info.find("is not installed") != std::string::npos)
{
std::cout << "Executing '" << info << "' requires sudo."
<< "\n\n";
}
std::string cmd = info + " 2>&1";
std::string out = exec(cmd);
std::cout << "======= " << info << "\n\n";
std::cout << out << "\n\n";
}
} // namespace
void tcam::tools::print_packages()
{
if (system("which dpkg-query > /dev/null 2>&1"))
{
std::cerr << "dplg-query could not be found. No package information available." << std::endl;
return;
}
check_package("tiscamera");
check_package("tiscamera-tcamproperty");
check_package("tcamdutils");
check_package("tcamdutils-cuda");
check_package("tcampimipisrc");
check_package("tcamtegrasrc");
check_package("ic_barcode");
}
void tcam::tools::print_system_info_general()
{
check_system_info("lsb_release -a");
check_system_info("uname -a");
// check_system_info("sudo lshw");
check_system_info("lscpu");
}
void tcam::tools::print_system_info_gige()
{
check_system_info("ip a");
}
void tcam::tools::print_system_info_usb()
{
check_system_info("lsusb");
check_system_info("lsusb -t");
}
void tcam::tools::print_system_info()
{
std::cout << "=============" << std::endl;
std::cout << "= General =" << std::endl;
std::cout << "=============" << std::endl;
print_system_info_general();
std::cout << "=============" << std::endl;
std::cout << "= USB =" << std::endl;
std::cout << "=============" << std::endl;
print_system_info_usb();
std::cout << "=============" << std::endl;
std::cout << "= Network =" << std::endl;
std::cout << "=============" << std::endl;
print_system_info_gige();
std::cout << "=============" << std::endl;
std::cout << "= Packaging =" << std::endl;
std::cout << "=============" << std::endl;
print_packages();
std::cout << std::endl;
std::cerr << "Please review the printed information to ensure" << std::endl
<< "that nothing you consider confidential is given to other parties." << std::endl;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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 "src/trace_processor/importers/common/clock_tracker.h"
#include <inttypes.h>
#include <algorithm>
#include <queue>
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/hash.h"
#include "src/trace_processor/storage/trace_storage.h"
#include "src/trace_processor/types/trace_processor_context.h"
#include "protos/perfetto/common/builtin_clock.pbzero.h"
#include "protos/perfetto/trace/clock_snapshot.pbzero.h"
namespace perfetto {
namespace trace_processor {
using Clock = protos::pbzero::ClockSnapshot::Clock;
ClockTracker::ClockTracker(TraceProcessorContext* ctx)
: context_(ctx),
trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}
ClockTracker::~ClockTracker() = default;
void ClockTracker::AddSnapshot(const std::vector<ClockValue>& clocks) {
const auto snapshot_id = cur_snapshot_id_++;
// Clear the cache
static_assert(std::is_trivial<decltype(cache_)>::value, "must be trivial");
memset(&cache_[0], 0, sizeof(cache_));
// Compute the fingerprint of the snapshot by hashing all clock ids. This is
// used by the clock pathfinding logic.
base::Hash hasher;
for (const auto& clock : clocks)
hasher.Update(clock.clock_id);
const auto snapshot_hash = static_cast<SnapshotHash>(hasher.digest());
// Add a new entry in each clock's snapshot vector.
for (const auto& clock : clocks) {
ClockId clock_id = clock.clock_id;
ClockDomain& domain = clocks_[clock_id];
if (domain.snapshots.empty()) {
if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {
PERFETTO_ELOG("Clock sync error: the global clock with id=%" PRIu64
" cannot use incremental encoding; this is only "
"supported for sequence-scoped clocks.",
clock_id);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
domain.unit_multiplier_ns = clock.unit_multiplier_ns;
domain.is_incremental = clock.is_incremental;
} else if (PERFETTO_UNLIKELY(
domain.unit_multiplier_ns != clock.unit_multiplier_ns ||
domain.is_incremental != clock.is_incremental)) {
PERFETTO_ELOG("Clock sync error: the clock domain with id=%" PRIu64
" (unit=%" PRIu64
", incremental=%d), was previously registered with "
"different properties (unit=%" PRIu64 ", incremental=%d).",
clock_id, clock.unit_multiplier_ns, clock.is_incremental,
domain.unit_multiplier_ns, domain.is_incremental);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
const int64_t timestamp_ns =
clock.absolute_timestamp * domain.unit_multiplier_ns;
domain.last_timestamp_ns = timestamp_ns;
ClockSnapshots& vect = domain.snapshots[snapshot_hash];
if (!vect.snapshot_ids.empty() &&
PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {
PERFETTO_ELOG("Clock sync error: duplicate clock domain with id=%" PRIu64
" at snapshot %" PRIu32 ".",
clock_id, snapshot_id);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
// Clock ids in the range [64, 128) are sequence-scoped and must be
// translated to global ids via SeqScopedClockIdToGlobal() before calling
// this function.
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));
// Snapshot IDs must be always monotonic.
PERFETTO_DCHECK(vect.snapshot_ids.empty() ||
vect.snapshot_ids.back() < snapshot_id);
if (!vect.timestamps_ns.empty() &&
timestamp_ns < vect.timestamps_ns.back()) {
// Clock is not monotonic.
if (clock_id == trace_time_clock_id_) {
// The trace clock cannot be non-monotonic.
PERFETTO_ELOG("Clock sync error: the trace clock (id=%" PRIu64
") is not monotonic at snapshot %" PRIu32 ". %" PRId64
" not >= %" PRId64 ".",
clock_id, snapshot_id, timestamp_ns,
vect.timestamps_ns.back());
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
PERFETTO_DLOG("Detected non-monotonic clock with ID %" PRIu64, clock_id);
// For the other clocks the best thing we can do is mark it as
// non-monotonic and refuse to use it as a source clock in the resolution
// graph. We can still use it as a target clock, but not viceversa.
// The concrete example is the CLOCK_REALTIME going 1h backwards during
// daylight saving. We can still answer the question "what was the
// REALTIME timestamp when BOOTTIME was X?" but we can't answer the
// opposite question because there can be two valid BOOTTIME(s) for the
// same REALTIME instant because of the 1:many relationship.
non_monotonic_clocks_.insert(clock_id);
// Erase all edges from the graph that start from this clock (but keep the
// ones that end on this clock).
auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});
auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});
graph_.erase(begin, end);
}
vect.snapshot_ids.emplace_back(snapshot_id);
vect.timestamps_ns.emplace_back(timestamp_ns);
}
// Create graph edges for all the possible tuples of clocks in this snapshot.
// If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,
// cd] and the symmetrical ones [ba, ca, da, bc, db, dc].
// This is to store the information: Clock A is syncable to Clock B via the
// snapshots of type (hash).
// Clocks that were previously marked as non-monotonic won't be added as
// valid sources.
for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {
auto it2 = it1;
++it2;
for (; it2 != clocks.end(); ++it2) {
if (!non_monotonic_clocks_.count(it1->clock_id))
graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);
if (!non_monotonic_clocks_.count(it2->clock_id))
graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);
}
}
}
// Finds the shortest clock resolution path in the graph that allows to
// translate a timestamp from |src| to |target| clocks.
// The return value looks like the following: "If you want to convert a
// timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the
// snapshot hash A, then convert C3 -> C2 via snapshot hash B".
ClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {
// This is a classic breadth-first search. Each node in the queue holds also
// the full path to reach that node.
// We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will
// stop the search anyways.
PERFETTO_CHECK(src != target);
std::queue<ClockPath> queue;
queue.emplace(src);
while (!queue.empty()) {
ClockPath cur_path = queue.front();
queue.pop();
const ClockId cur_clock_id = cur_path.last;
if (cur_clock_id == target)
return cur_path;
if (cur_path.len >= ClockPath::kMaxLen)
continue;
// Expore all the adjacent clocks.
// The lower_bound() below returns an iterator to the first edge that starts
// on |cur_clock_id|. The edges are sorted by (src, target, hash).
for (auto it = std::lower_bound(graph_.begin(), graph_.end(),
ClockGraphEdge(cur_clock_id, 0, 0));
it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {
ClockId next_clock_id = std::get<1>(*it);
SnapshotHash hash = std::get<2>(*it);
queue.push(ClockPath(cur_path, next_clock_id, hash));
}
}
return ClockPath(); // invalid path.
}
base::Optional<int64_t> ClockTracker::ConvertSlowpath(ClockId src_clock_id,
int64_t src_timestamp,
ClockId target_clock_id) {
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));
context_->storage->IncrementStats(stats::clock_sync_cache_miss);
ClockPath path = FindPath(src_clock_id, target_clock_id);
if (!path.valid()) {
PERFETTO_DLOG("No path from clock %" PRIu64 " to %" PRIu64
" at timestamp %" PRId64,
src_clock_id, target_clock_id, src_timestamp);
context_->storage->IncrementStats(stats::clock_sync_failure);
return base::nullopt;
}
// We can cache only single-path resolutions between two clocks.
// Caching multi-path resolutions is harder because the (src,target) tuple
// is not enough as a cache key: at any step the |ns| value can yield to a
// different choice of the next snapshot. Multi-path resolutions don't seem
// too frequent these days, so we focus only on caching the more frequent
// one-step resolutions (typically from any clock to the trace clock).
const bool cacheable = path.len == 1;
CachedClockPath cache_entry{};
// Iterate trough the path found and translate timestamps onto the new clock
// domain on each step, until the target domain is reached.
ClockDomain* src_domain = GetClock(src_clock_id);
int64_t ns = src_domain->ToNs(src_timestamp);
for (uint32_t i = 0; i < path.len; ++i) {
const ClockGraphEdge edge = path.at(i);
ClockDomain* cur_clock = GetClock(std::get<0>(edge));
ClockDomain* next_clock = GetClock(std::get<1>(edge));
const SnapshotHash hash = std::get<2>(edge);
// Find the closest timestamp within the snapshots of the source clock.
const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);
const auto& ts_vec = cur_snap.timestamps_ns;
auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);
if (it != ts_vec.begin())
--it;
// Now lookup the snapshot id that matches the closest timestamp.
size_t index = static_cast<size_t>(std::distance(ts_vec.begin(), it));
PERFETTO_DCHECK(index < ts_vec.size());
PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());
uint32_t snapshot_id = cur_snap.snapshot_ids[index];
// And use that to retrieve the corresponding time in the next clock domain.
// The snapshot id must exist in the target clock domain. If it doesn't
// either the hash logic or the pathfinding logic are bugged.
const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);
auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),
next_snap.snapshot_ids.end(), snapshot_id);
PERFETTO_DCHECK(next_it != next_snap.snapshot_ids.end() &&
*next_it == snapshot_id);
size_t next_index = static_cast<size_t>(
std::distance(next_snap.snapshot_ids.begin(), next_it));
PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());
int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];
// The translated timestamp is the relative delta of the source timestamp
// from the closest snapshot found (ns - *it), plus the timestamp in
// the new clock domain for the same snapshot id.
const int64_t adj = next_timestamp_ns - *it;
ns += adj;
// On the first iteration, keep track of the bounds for the cache entry.
// This will allow future Convert() calls to skip the pathfinder logic
// as long as the query stays within the bound.
if (cacheable) {
PERFETTO_DCHECK(i == 0);
const int64_t kInt64Min = std::numeric_limits<int64_t>::min();
const int64_t kInt64Max = std::numeric_limits<int64_t>::max();
cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;
auto ubound = it + 1;
cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;
cache_entry.translation_ns = adj;
}
// The last clock in the path must be the target clock.
PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);
}
if (cacheable) {
cache_entry.src = src_clock_id;
cache_entry.src_domain = src_domain;
cache_entry.target = target_clock_id;
cache_[rnd_() % cache_.size()] = cache_entry;
}
return ns;
}
} // namespace trace_processor
} // namespace perfetto
<commit_msg>Remove unnecessarily standard-incompliant code.<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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 "src/trace_processor/importers/common/clock_tracker.h"
#include <inttypes.h>
#include <algorithm>
#include <queue>
#include "perfetto/base/logging.h"
#include "perfetto/ext/base/hash.h"
#include "src/trace_processor/storage/trace_storage.h"
#include "src/trace_processor/types/trace_processor_context.h"
#include "protos/perfetto/common/builtin_clock.pbzero.h"
#include "protos/perfetto/trace/clock_snapshot.pbzero.h"
namespace perfetto {
namespace trace_processor {
using Clock = protos::pbzero::ClockSnapshot::Clock;
ClockTracker::ClockTracker(TraceProcessorContext* ctx)
: context_(ctx),
trace_time_clock_id_(protos::pbzero::BUILTIN_CLOCK_BOOTTIME) {}
ClockTracker::~ClockTracker() = default;
void ClockTracker::AddSnapshot(const std::vector<ClockValue>& clocks) {
const auto snapshot_id = cur_snapshot_id_++;
// Clear the cache
cache_.fill({});
// Compute the fingerprint of the snapshot by hashing all clock ids. This is
// used by the clock pathfinding logic.
base::Hash hasher;
for (const auto& clock : clocks)
hasher.Update(clock.clock_id);
const auto snapshot_hash = static_cast<SnapshotHash>(hasher.digest());
// Add a new entry in each clock's snapshot vector.
for (const auto& clock : clocks) {
ClockId clock_id = clock.clock_id;
ClockDomain& domain = clocks_[clock_id];
if (domain.snapshots.empty()) {
if (clock.is_incremental && !ClockIsSeqScoped(clock_id)) {
PERFETTO_ELOG("Clock sync error: the global clock with id=%" PRIu64
" cannot use incremental encoding; this is only "
"supported for sequence-scoped clocks.",
clock_id);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
domain.unit_multiplier_ns = clock.unit_multiplier_ns;
domain.is_incremental = clock.is_incremental;
} else if (PERFETTO_UNLIKELY(
domain.unit_multiplier_ns != clock.unit_multiplier_ns ||
domain.is_incremental != clock.is_incremental)) {
PERFETTO_ELOG("Clock sync error: the clock domain with id=%" PRIu64
" (unit=%" PRIu64
", incremental=%d), was previously registered with "
"different properties (unit=%" PRIu64 ", incremental=%d).",
clock_id, clock.unit_multiplier_ns, clock.is_incremental,
domain.unit_multiplier_ns, domain.is_incremental);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
const int64_t timestamp_ns =
clock.absolute_timestamp * domain.unit_multiplier_ns;
domain.last_timestamp_ns = timestamp_ns;
ClockSnapshots& vect = domain.snapshots[snapshot_hash];
if (!vect.snapshot_ids.empty() &&
PERFETTO_UNLIKELY(vect.snapshot_ids.back() == snapshot_id)) {
PERFETTO_ELOG("Clock sync error: duplicate clock domain with id=%" PRIu64
" at snapshot %" PRIu32 ".",
clock_id, snapshot_id);
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
// Clock ids in the range [64, 128) are sequence-scoped and must be
// translated to global ids via SeqScopedClockIdToGlobal() before calling
// this function.
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(clock_id));
// Snapshot IDs must be always monotonic.
PERFETTO_DCHECK(vect.snapshot_ids.empty() ||
vect.snapshot_ids.back() < snapshot_id);
if (!vect.timestamps_ns.empty() &&
timestamp_ns < vect.timestamps_ns.back()) {
// Clock is not monotonic.
if (clock_id == trace_time_clock_id_) {
// The trace clock cannot be non-monotonic.
PERFETTO_ELOG("Clock sync error: the trace clock (id=%" PRIu64
") is not monotonic at snapshot %" PRIu32 ". %" PRId64
" not >= %" PRId64 ".",
clock_id, snapshot_id, timestamp_ns,
vect.timestamps_ns.back());
context_->storage->IncrementStats(stats::invalid_clock_snapshots);
return;
}
PERFETTO_DLOG("Detected non-monotonic clock with ID %" PRIu64, clock_id);
// For the other clocks the best thing we can do is mark it as
// non-monotonic and refuse to use it as a source clock in the resolution
// graph. We can still use it as a target clock, but not viceversa.
// The concrete example is the CLOCK_REALTIME going 1h backwards during
// daylight saving. We can still answer the question "what was the
// REALTIME timestamp when BOOTTIME was X?" but we can't answer the
// opposite question because there can be two valid BOOTTIME(s) for the
// same REALTIME instant because of the 1:many relationship.
non_monotonic_clocks_.insert(clock_id);
// Erase all edges from the graph that start from this clock (but keep the
// ones that end on this clock).
auto begin = graph_.lower_bound(ClockGraphEdge{clock_id, 0, 0});
auto end = graph_.lower_bound(ClockGraphEdge{clock_id + 1, 0, 0});
graph_.erase(begin, end);
}
vect.snapshot_ids.emplace_back(snapshot_id);
vect.timestamps_ns.emplace_back(timestamp_ns);
}
// Create graph edges for all the possible tuples of clocks in this snapshot.
// If the snapshot contains clock a, b, c, d create edges [ab, ac, ad, bc, bd,
// cd] and the symmetrical ones [ba, ca, da, bc, db, dc].
// This is to store the information: Clock A is syncable to Clock B via the
// snapshots of type (hash).
// Clocks that were previously marked as non-monotonic won't be added as
// valid sources.
for (auto it1 = clocks.begin(); it1 != clocks.end(); ++it1) {
auto it2 = it1;
++it2;
for (; it2 != clocks.end(); ++it2) {
if (!non_monotonic_clocks_.count(it1->clock_id))
graph_.emplace(it1->clock_id, it2->clock_id, snapshot_hash);
if (!non_monotonic_clocks_.count(it2->clock_id))
graph_.emplace(it2->clock_id, it1->clock_id, snapshot_hash);
}
}
}
// Finds the shortest clock resolution path in the graph that allows to
// translate a timestamp from |src| to |target| clocks.
// The return value looks like the following: "If you want to convert a
// timestamp from clock C1 to C2 you need to first convert C1 -> C3 using the
// snapshot hash A, then convert C3 -> C2 via snapshot hash B".
ClockTracker::ClockPath ClockTracker::FindPath(ClockId src, ClockId target) {
// This is a classic breadth-first search. Each node in the queue holds also
// the full path to reach that node.
// We assume the graph is acyclic, if it isn't the ClockPath::kMaxLen will
// stop the search anyways.
PERFETTO_CHECK(src != target);
std::queue<ClockPath> queue;
queue.emplace(src);
while (!queue.empty()) {
ClockPath cur_path = queue.front();
queue.pop();
const ClockId cur_clock_id = cur_path.last;
if (cur_clock_id == target)
return cur_path;
if (cur_path.len >= ClockPath::kMaxLen)
continue;
// Expore all the adjacent clocks.
// The lower_bound() below returns an iterator to the first edge that starts
// on |cur_clock_id|. The edges are sorted by (src, target, hash).
for (auto it = std::lower_bound(graph_.begin(), graph_.end(),
ClockGraphEdge(cur_clock_id, 0, 0));
it != graph_.end() && std::get<0>(*it) == cur_clock_id; ++it) {
ClockId next_clock_id = std::get<1>(*it);
SnapshotHash hash = std::get<2>(*it);
queue.push(ClockPath(cur_path, next_clock_id, hash));
}
}
return ClockPath(); // invalid path.
}
base::Optional<int64_t> ClockTracker::ConvertSlowpath(ClockId src_clock_id,
int64_t src_timestamp,
ClockId target_clock_id) {
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(src_clock_id));
PERFETTO_DCHECK(!IsReservedSeqScopedClockId(target_clock_id));
context_->storage->IncrementStats(stats::clock_sync_cache_miss);
ClockPath path = FindPath(src_clock_id, target_clock_id);
if (!path.valid()) {
PERFETTO_DLOG("No path from clock %" PRIu64 " to %" PRIu64
" at timestamp %" PRId64,
src_clock_id, target_clock_id, src_timestamp);
context_->storage->IncrementStats(stats::clock_sync_failure);
return base::nullopt;
}
// We can cache only single-path resolutions between two clocks.
// Caching multi-path resolutions is harder because the (src,target) tuple
// is not enough as a cache key: at any step the |ns| value can yield to a
// different choice of the next snapshot. Multi-path resolutions don't seem
// too frequent these days, so we focus only on caching the more frequent
// one-step resolutions (typically from any clock to the trace clock).
const bool cacheable = path.len == 1;
CachedClockPath cache_entry{};
// Iterate trough the path found and translate timestamps onto the new clock
// domain on each step, until the target domain is reached.
ClockDomain* src_domain = GetClock(src_clock_id);
int64_t ns = src_domain->ToNs(src_timestamp);
for (uint32_t i = 0; i < path.len; ++i) {
const ClockGraphEdge edge = path.at(i);
ClockDomain* cur_clock = GetClock(std::get<0>(edge));
ClockDomain* next_clock = GetClock(std::get<1>(edge));
const SnapshotHash hash = std::get<2>(edge);
// Find the closest timestamp within the snapshots of the source clock.
const ClockSnapshots& cur_snap = cur_clock->GetSnapshot(hash);
const auto& ts_vec = cur_snap.timestamps_ns;
auto it = std::upper_bound(ts_vec.begin(), ts_vec.end(), ns);
if (it != ts_vec.begin())
--it;
// Now lookup the snapshot id that matches the closest timestamp.
size_t index = static_cast<size_t>(std::distance(ts_vec.begin(), it));
PERFETTO_DCHECK(index < ts_vec.size());
PERFETTO_DCHECK(cur_snap.snapshot_ids.size() == ts_vec.size());
uint32_t snapshot_id = cur_snap.snapshot_ids[index];
// And use that to retrieve the corresponding time in the next clock domain.
// The snapshot id must exist in the target clock domain. If it doesn't
// either the hash logic or the pathfinding logic are bugged.
const ClockSnapshots& next_snap = next_clock->GetSnapshot(hash);
auto next_it = std::lower_bound(next_snap.snapshot_ids.begin(),
next_snap.snapshot_ids.end(), snapshot_id);
PERFETTO_DCHECK(next_it != next_snap.snapshot_ids.end() &&
*next_it == snapshot_id);
size_t next_index = static_cast<size_t>(
std::distance(next_snap.snapshot_ids.begin(), next_it));
PERFETTO_DCHECK(next_index < next_snap.snapshot_ids.size());
int64_t next_timestamp_ns = next_snap.timestamps_ns[next_index];
// The translated timestamp is the relative delta of the source timestamp
// from the closest snapshot found (ns - *it), plus the timestamp in
// the new clock domain for the same snapshot id.
const int64_t adj = next_timestamp_ns - *it;
ns += adj;
// On the first iteration, keep track of the bounds for the cache entry.
// This will allow future Convert() calls to skip the pathfinder logic
// as long as the query stays within the bound.
if (cacheable) {
PERFETTO_DCHECK(i == 0);
const int64_t kInt64Min = std::numeric_limits<int64_t>::min();
const int64_t kInt64Max = std::numeric_limits<int64_t>::max();
cache_entry.min_ts_ns = it == ts_vec.begin() ? kInt64Min : *it;
auto ubound = it + 1;
cache_entry.max_ts_ns = ubound == ts_vec.end() ? kInt64Max : *ubound;
cache_entry.translation_ns = adj;
}
// The last clock in the path must be the target clock.
PERFETTO_DCHECK(i < path.len - 1 || std::get<1>(edge) == target_clock_id);
}
if (cacheable) {
cache_entry.src = src_clock_id;
cache_entry.src_domain = src_domain;
cache_entry.target = target_clock_id;
cache_[rnd_() % cache_.size()] = cache_entry;
}
return ns;
}
} // namespace trace_processor
} // namespace perfetto
<|endoftext|> |
<commit_before>/**\file
* \brief "Hello World" HTTP Server
*
* This is an example HTTP server that serves a simple "Hello World!" on /, and
* a 404 on all other resources.
*
* Call it like this:
* \code
* $ ./http-hello localhost 8080
* \endcode
*
* With localhost and 8080 being a host name and port of your choosing. Then,
* while the programme is running, open a browser and go to
* http://localhost:8080/ and you should see the familiar greeting.
*
* \copyright
* Copyright (c) 2015, ef.gy Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/libefgy
* \see Project Source Code: https://github.com/ef-gy/libefgy
*/
#define ASIO_DISABLE_THREADS
#include <ef.gy/http.h>
#include <iostream>
using namespace efgy;
using asio::ip::tcp;
/**\brief Hello World request handler
*
* This function serves the familiar "Hello World!" when called.
*
* \param[out] session The HTTP session to answer on.
*
* \returns true (always, as we always reply).
*/
static bool hello(typename net::http::server<tcp>::session &session,
std::smatch &) {
session.reply(200, "Hello World!");
return true;
}
/**\brief Hello World request handler for /quit
*
* When this handler is invoked, it stops the ASIO IO handler (after replying,
* maybe...).
*
* \note Having this on your production server in this exact way is PROBABLY a
* really bad idea, unless you gate it in an upstream forward proxy. Or
* you have some way of automatically respawning your server. Or both.
*
* \param[out] session The HTTP session to answer on.
*
* \returns true (always, as we always reply).
*/
static bool quit(typename net::http::server<tcp>::session &session,
std::smatch &) {
session.reply(200, "Good-Bye, Cruel World!");
session.server.io.stop();
return true;
}
/**\brief Main function for the HTTP demo
*
* This is the main function for the HTTP Hello World demo.
*
* \param[in] argc Process argument count.
* \param[in] argv Process argument vector
*
* \returns 0 when nothing bad happened, 1 otherwise.
*/
int main(int argc, char *argv[]) {
try {
if (argc != 3) {
std::cerr << "Usage: http-hello <host> <port>\n";
return 1;
}
asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], argv[2]);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
if (endpoint_iterator != end) {
tcp::endpoint endpoint = *endpoint_iterator;
net::http::server<tcp> s(io_service, endpoint, std::cout);
s.processor.add("^/$", hello);
s.processor.add("^/quit$", quit);
io_service.run();
}
return 0;
}
catch (std::exception & e) {
std::cerr << "Exception: " << e.what() << "\n";
}
catch (std::system_error & e) {
std::cerr << "System Error: " << e.what() << "\n";
}
return 1;
}
<commit_msg>forgot to add anappropriate group tag<commit_after>/**\file
* \ingroup example-programmes
* \brief "Hello World" HTTP Server
*
* This is an example HTTP server that serves a simple "Hello World!" on /, and
* a 404 on all other resources.
*
* Call it like this:
* \code
* $ ./http-hello localhost 8080
* \endcode
*
* With localhost and 8080 being a host name and port of your choosing. Then,
* while the programme is running, open a browser and go to
* http://localhost:8080/ and you should see the familiar greeting.
*
* \copyright
* Copyright (c) 2015, ef.gy Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/libefgy
* \see Project Source Code: https://github.com/ef-gy/libefgy
*/
#define ASIO_DISABLE_THREADS
#include <ef.gy/http.h>
#include <iostream>
using namespace efgy;
using asio::ip::tcp;
/**\brief Hello World request handler
*
* This function serves the familiar "Hello World!" when called.
*
* \param[out] session The HTTP session to answer on.
*
* \returns true (always, as we always reply).
*/
static bool hello(typename net::http::server<tcp>::session &session,
std::smatch &) {
session.reply(200, "Hello World!");
return true;
}
/**\brief Hello World request handler for /quit
*
* When this handler is invoked, it stops the ASIO IO handler (after replying,
* maybe...).
*
* \note Having this on your production server in this exact way is PROBABLY a
* really bad idea, unless you gate it in an upstream forward proxy. Or
* you have some way of automatically respawning your server. Or both.
*
* \param[out] session The HTTP session to answer on.
*
* \returns true (always, as we always reply).
*/
static bool quit(typename net::http::server<tcp>::session &session,
std::smatch &) {
session.reply(200, "Good-Bye, Cruel World!");
session.server.io.stop();
return true;
}
/**\brief Main function for the HTTP demo
*
* This is the main function for the HTTP Hello World demo.
*
* \param[in] argc Process argument count.
* \param[in] argv Process argument vector
*
* \returns 0 when nothing bad happened, 1 otherwise.
*/
int main(int argc, char *argv[]) {
try {
if (argc != 3) {
std::cerr << "Usage: http-hello <host> <port>\n";
return 1;
}
asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], argv[2]);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
if (endpoint_iterator != end) {
tcp::endpoint endpoint = *endpoint_iterator;
net::http::server<tcp> s(io_service, endpoint, std::cout);
s.processor.add("^/$", hello);
s.processor.add("^/quit$", quit);
io_service.run();
}
return 0;
}
catch (std::exception & e) {
std::cerr << "Exception: " << e.what() << "\n";
}
catch (std::system_error & e) {
std::cerr << "System Error: " << e.what() << "\n";
}
return 1;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2019 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "tools/viewer/SkSLSlide.h"
#include "include/core/SkCanvas.h"
#include "include/effects/SkGradientShader.h"
#include "include/effects/SkPerlinNoiseShader.h"
#include "src/core/SkEnumerate.h"
#include "tools/Resources.h"
#include "tools/viewer/Viewer.h"
#include <algorithm>
#include "imgui.h"
using namespace sk_app;
///////////////////////////////////////////////////////////////////////////////
static int InputTextCallback(ImGuiInputTextCallbackData* data) {
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) {
SkString* s = (SkString*)data->UserData;
SkASSERT(data->Buf == s->writable_str());
SkString tmp(data->Buf, data->BufTextLen);
s->swap(tmp);
data->Buf = s->writable_str();
}
return 0;
}
SkSLSlide::SkSLSlide() {
// Register types for serialization
fName = "SkSL";
fSkSL =
"uniform shader child;\n"
"\n"
"half4 main(float2 p) {\n"
" return sample(child, p);\n"
"}\n";
fCodeIsDirty = true;
}
void SkSLSlide::load(SkScalar winWidth, SkScalar winHeight) {
SkPoint points[] = { { 0, 0 }, { 256, 0 } };
SkColor colors[] = { SK_ColorRED, SK_ColorGREEN };
sk_sp<SkShader> shader;
fShaders.push_back(std::make_pair("Null", nullptr));
shader = SkGradientShader::MakeLinear(points, colors, nullptr, 2, SkTileMode::kClamp);
fShaders.push_back(std::make_pair("Linear Gradient", shader));
shader = SkGradientShader::MakeRadial({ 128, 128 }, 128, colors, nullptr, 2,
SkTileMode::kClamp);
fShaders.push_back(std::make_pair("Radial Gradient", shader));
shader = SkGradientShader::MakeSweep(128, 128, colors, nullptr, 2);
fShaders.push_back(std::make_pair("Sweep Gradient", shader));
shader = GetResourceAsImage("images/mandrill_256.png")->makeShader(SkSamplingOptions());
fShaders.push_back(std::make_pair("Mandrill", shader));
shader = SkPerlinNoiseShader::MakeImprovedNoise(0.025f, 0.025f, 3, 0.0f);
fShaders.push_back(std::make_pair("Perlin Noise", shader));
}
void SkSLSlide::unload() {
fEffect.reset();
fInputs.reset();
fChildren.reset();
fShaders.reset();
}
bool SkSLSlide::rebuild() {
SkString sksl("uniform float iTime;\n");
sksl.append(fSkSL);
auto [effect, errorText] = SkRuntimeEffect::Make(sksl);
if (!effect) {
Viewer::ShaderErrorHandler()->compileError(sksl.c_str(), errorText.c_str());
return false;
}
size_t oldSize = fEffect ? fEffect->uniformSize() : 0;
fInputs.realloc(effect->uniformSize());
if (effect->uniformSize() > oldSize) {
memset(fInputs.get() + oldSize, 0, effect->uniformSize() - oldSize);
}
fChildren.resize_back(effect->children().count());
fEffect = effect;
fCodeIsDirty = false;
return true;
}
void SkSLSlide::draw(SkCanvas* canvas) {
canvas->clear(SK_ColorWHITE);
ImGui::Begin("SkSL", nullptr, ImGuiWindowFlags_AlwaysVerticalScrollbar);
// Edit box for shader code
ImGuiInputTextFlags flags = ImGuiInputTextFlags_CallbackResize;
ImVec2 boxSize(-1.0f, ImGui::GetTextLineHeight() * 30);
if (ImGui::InputTextMultiline("Code", fSkSL.writable_str(), fSkSL.size() + 1, boxSize, flags,
InputTextCallback, &fSkSL)) {
fCodeIsDirty = true;
}
if (fCodeIsDirty || !fEffect) {
this->rebuild();
}
if (!fEffect) {
ImGui::End();
return;
}
for (const auto& v : fEffect->uniforms()) {
if (v.fName.equals("iTime")) {
*(float*)(fInputs.get() + v.fOffset) = fSeconds;
continue;
}
switch (v.fType) {
case SkRuntimeEffect::Uniform::Type::kFloat:
case SkRuntimeEffect::Uniform::Type::kFloat2:
case SkRuntimeEffect::Uniform::Type::kFloat3:
case SkRuntimeEffect::Uniform::Type::kFloat4: {
int rows = ((int)v.fType - (int)SkRuntimeEffect::Uniform::Type::kFloat) + 1;
float* f = (float*)(fInputs.get() + v.fOffset);
for (int c = 0; c < v.fCount; ++c, f += rows) {
SkString name = v.isArray() ? SkStringPrintf("%s[%d]", v.fName.c_str(), c)
: v.fName;
ImGui::PushID(c);
ImGui::DragScalarN(name.c_str(), ImGuiDataType_Float, f, rows, 1.0f);
ImGui::PopID();
}
break;
}
case SkRuntimeEffect::Uniform::Type::kFloat2x2:
case SkRuntimeEffect::Uniform::Type::kFloat3x3:
case SkRuntimeEffect::Uniform::Type::kFloat4x4: {
int rows = ((int)v.fType - (int)SkRuntimeEffect::Uniform::Type::kFloat2x2) + 2;
int cols = rows;
float* f = (float*)(fInputs.get() + v.fOffset);
for (int e = 0; e < v.fCount; ++e) {
for (int c = 0; c < cols; ++c, f += rows) {
SkString name = v.isArray()
? SkStringPrintf("%s[%d][%d]", v.fName.c_str(), e, c)
: SkStringPrintf("%s[%d]", v.fName.c_str(), c);
ImGui::DragScalarN(name.c_str(), ImGuiDataType_Float, f, rows, 1.0f);
}
}
break;
}
}
}
for (const auto& [i, name] : SkMakeEnumerate(fEffect->children())) {
auto curShader = std::find_if(fShaders.begin(), fShaders.end(),
[tgt = fChildren[i]](auto p) { return p.second == tgt; });
SkASSERT(curShader!= fShaders.end());
if (ImGui::BeginCombo(name.c_str(), curShader->first)) {
for (const auto& namedShader : fShaders) {
if (ImGui::Selectable(namedShader.first, curShader->second == namedShader.second)) {
fChildren[i] = namedShader.second;
}
}
ImGui::EndCombo();
}
}
static SkColor4f gPaintColor { 1.0f, 1.0f, 1.0f , 1.0f };
ImGui::ColorEdit4("Paint Color", gPaintColor.vec());
ImGui::End();
auto inputs = SkData::MakeWithoutCopy(fInputs.get(), fEffect->uniformSize());
auto shader = fEffect->makeShader(std::move(inputs), fChildren.data(), fChildren.count(),
nullptr, false);
SkPaint p;
p.setColor4f(gPaintColor);
p.setShader(std::move(shader));
canvas->drawRect({ 0, 0, 256, 256 }, p);
}
bool SkSLSlide::animate(double nanos) {
fSeconds = static_cast<float>(nanos * 1E-9);
return true;
}
<commit_msg>SkSLSlide: Fill the entire canvas with the user shader<commit_after>/*
* Copyright 2019 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "tools/viewer/SkSLSlide.h"
#include "include/core/SkCanvas.h"
#include "include/effects/SkGradientShader.h"
#include "include/effects/SkPerlinNoiseShader.h"
#include "src/core/SkEnumerate.h"
#include "tools/Resources.h"
#include "tools/viewer/Viewer.h"
#include <algorithm>
#include "imgui.h"
using namespace sk_app;
///////////////////////////////////////////////////////////////////////////////
static int InputTextCallback(ImGuiInputTextCallbackData* data) {
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) {
SkString* s = (SkString*)data->UserData;
SkASSERT(data->Buf == s->writable_str());
SkString tmp(data->Buf, data->BufTextLen);
s->swap(tmp);
data->Buf = s->writable_str();
}
return 0;
}
SkSLSlide::SkSLSlide() {
// Register types for serialization
fName = "SkSL";
fSkSL =
"uniform shader child;\n"
"\n"
"half4 main(float2 p) {\n"
" return sample(child, p);\n"
"}\n";
fCodeIsDirty = true;
}
void SkSLSlide::load(SkScalar winWidth, SkScalar winHeight) {
SkPoint points[] = { { 0, 0 }, { 256, 0 } };
SkColor colors[] = { SK_ColorRED, SK_ColorGREEN };
sk_sp<SkShader> shader;
fShaders.push_back(std::make_pair("Null", nullptr));
shader = SkGradientShader::MakeLinear(points, colors, nullptr, 2, SkTileMode::kClamp);
fShaders.push_back(std::make_pair("Linear Gradient", shader));
shader = SkGradientShader::MakeRadial({ 256, 256 }, 256, colors, nullptr, 2,
SkTileMode::kClamp);
fShaders.push_back(std::make_pair("Radial Gradient", shader));
shader = SkGradientShader::MakeSweep(256, 256, colors, nullptr, 2);
fShaders.push_back(std::make_pair("Sweep Gradient", shader));
shader = GetResourceAsImage("images/mandrill_256.png")->makeShader(SkSamplingOptions());
fShaders.push_back(std::make_pair("Mandrill", shader));
shader = SkPerlinNoiseShader::MakeImprovedNoise(0.025f, 0.025f, 3, 0.0f);
fShaders.push_back(std::make_pair("Perlin Noise", shader));
}
void SkSLSlide::unload() {
fEffect.reset();
fInputs.reset();
fChildren.reset();
fShaders.reset();
}
bool SkSLSlide::rebuild() {
SkString sksl("uniform float iTime;\n");
sksl.append(fSkSL);
auto [effect, errorText] = SkRuntimeEffect::Make(sksl);
if (!effect) {
Viewer::ShaderErrorHandler()->compileError(sksl.c_str(), errorText.c_str());
return false;
}
size_t oldSize = fEffect ? fEffect->uniformSize() : 0;
fInputs.realloc(effect->uniformSize());
if (effect->uniformSize() > oldSize) {
memset(fInputs.get() + oldSize, 0, effect->uniformSize() - oldSize);
}
fChildren.resize_back(effect->children().count());
fEffect = effect;
fCodeIsDirty = false;
return true;
}
void SkSLSlide::draw(SkCanvas* canvas) {
canvas->clear(SK_ColorWHITE);
ImGui::Begin("SkSL", nullptr, ImGuiWindowFlags_AlwaysVerticalScrollbar);
// Edit box for shader code
ImGuiInputTextFlags flags = ImGuiInputTextFlags_CallbackResize;
ImVec2 boxSize(-1.0f, ImGui::GetTextLineHeight() * 30);
if (ImGui::InputTextMultiline("Code", fSkSL.writable_str(), fSkSL.size() + 1, boxSize, flags,
InputTextCallback, &fSkSL)) {
fCodeIsDirty = true;
}
if (fCodeIsDirty || !fEffect) {
this->rebuild();
}
if (!fEffect) {
ImGui::End();
return;
}
for (const auto& v : fEffect->uniforms()) {
if (v.fName.equals("iTime")) {
*(float*)(fInputs.get() + v.fOffset) = fSeconds;
continue;
}
switch (v.fType) {
case SkRuntimeEffect::Uniform::Type::kFloat:
case SkRuntimeEffect::Uniform::Type::kFloat2:
case SkRuntimeEffect::Uniform::Type::kFloat3:
case SkRuntimeEffect::Uniform::Type::kFloat4: {
int rows = ((int)v.fType - (int)SkRuntimeEffect::Uniform::Type::kFloat) + 1;
float* f = (float*)(fInputs.get() + v.fOffset);
for (int c = 0; c < v.fCount; ++c, f += rows) {
SkString name = v.isArray() ? SkStringPrintf("%s[%d]", v.fName.c_str(), c)
: v.fName;
ImGui::PushID(c);
ImGui::DragScalarN(name.c_str(), ImGuiDataType_Float, f, rows, 1.0f);
ImGui::PopID();
}
break;
}
case SkRuntimeEffect::Uniform::Type::kFloat2x2:
case SkRuntimeEffect::Uniform::Type::kFloat3x3:
case SkRuntimeEffect::Uniform::Type::kFloat4x4: {
int rows = ((int)v.fType - (int)SkRuntimeEffect::Uniform::Type::kFloat2x2) + 2;
int cols = rows;
float* f = (float*)(fInputs.get() + v.fOffset);
for (int e = 0; e < v.fCount; ++e) {
for (int c = 0; c < cols; ++c, f += rows) {
SkString name = v.isArray()
? SkStringPrintf("%s[%d][%d]", v.fName.c_str(), e, c)
: SkStringPrintf("%s[%d]", v.fName.c_str(), c);
ImGui::DragScalarN(name.c_str(), ImGuiDataType_Float, f, rows, 1.0f);
}
}
break;
}
}
}
for (const auto& [i, name] : SkMakeEnumerate(fEffect->children())) {
auto curShader = std::find_if(fShaders.begin(), fShaders.end(),
[tgt = fChildren[i]](auto p) { return p.second == tgt; });
SkASSERT(curShader!= fShaders.end());
if (ImGui::BeginCombo(name.c_str(), curShader->first)) {
for (const auto& namedShader : fShaders) {
if (ImGui::Selectable(namedShader.first, curShader->second == namedShader.second)) {
fChildren[i] = namedShader.second;
}
}
ImGui::EndCombo();
}
}
static SkColor4f gPaintColor { 1.0f, 1.0f, 1.0f , 1.0f };
ImGui::ColorEdit4("Paint Color", gPaintColor.vec());
ImGui::End();
auto inputs = SkData::MakeWithoutCopy(fInputs.get(), fEffect->uniformSize());
auto shader = fEffect->makeShader(std::move(inputs), fChildren.data(), fChildren.count(),
nullptr, false);
SkPaint p;
p.setColor4f(gPaintColor);
p.setShader(std::move(shader));
canvas->drawPaint(p);
}
bool SkSLSlide::animate(double nanos) {
fSeconds = static_cast<float>(nanos * 1E-9);
return true;
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(IDENTITYCONSTRAINT_HPP)
#define IDENTITYCONSTRAINT_HPP
/**
* The class act as a base class for schema identity constraints.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/RefVectorOf.hpp>
// ---------------------------------------------------------------------------
// Forward Declarations
// ---------------------------------------------------------------------------
class IC_Selector;
class IC_Field;
class VALIDATORS_EXPORT IdentityConstraint
{
public:
// -----------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------
enum {
UNIQUE = 0,
KEY = 1,
KEYREF = 2
};
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
virtual ~IdentityConstraint();
// -----------------------------------------------------------------------
// operators
// -----------------------------------------------------------------------
bool operator== (const IdentityConstraint& other) const;
bool operator!= (const IdentityConstraint& other) const;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
virtual short getType() const = 0;
int getFieldCount() const;
XMLCh* getIdentityConstraintName() const;
XMLCh* getElementName() const;
IC_Selector* getSelector() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setSelector(IC_Selector* const selector);
// -----------------------------------------------------------------------
// Access methods
// -----------------------------------------------------------------------
void addField(IC_Field* const field);
const IC_Field* getFieldAt(const unsigned int index) const;
IC_Field* getFieldAt(const unsigned int index);
protected:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
IdentityConstraint(const XMLCh* const identityConstraintName,
const XMLCh* const elementName);
private:
// -----------------------------------------------------------------------
// Unimplemented contstructors and operators
// -----------------------------------------------------------------------
IdentityConstraint(const IdentityConstraint& other);
IdentityConstraint& operator= (const IdentityConstraint& other);
// -----------------------------------------------------------------------
// CleanUp methods
// -----------------------------------------------------------------------
void cleanUp();
// -----------------------------------------------------------------------
// Data members
//
// fIdentityConstraintName
// The identity constraint name
//
// fElemName
// The element name
//
// fSelector
// The selector information
//
// fFields
// The field(s) information
// -----------------------------------------------------------------------
XMLCh* fIdentityConstraintName;
XMLCh* fElemName;
IC_Selector* fSelector;
RefVectorOf<IC_Field>* fFields;
};
// ---------------------------------------------------------------------------
// IdentityConstraint: Getter methods
// ---------------------------------------------------------------------------
inline int IdentityConstraint::getFieldCount() const {
if (fFields) {
return fFields->size();
}
return 0;
}
inline XMLCh* IdentityConstraint::getIdentityConstraintName() const {
return fIdentityConstraintName;
}
inline XMLCh* IdentityConstraint::getElementName() const {
return fElemName;
}
inline IC_Selector* IdentityConstraint::getSelector() const {
return fSelector;
}
// ---------------------------------------------------------------------------
// IdentityConstraint: Access methods
// ---------------------------------------------------------------------------
inline void IdentityConstraint::addField(IC_Field* const field) {
if (!fFields) {
fFields = new RefVectorOf<IC_Field>(4);
}
fFields->addElement(field);
}
inline const IC_Field* IdentityConstraint::getFieldAt(const unsigned int index) const {
if (fFields) {
return (fFields->elementAt(index));
}
return 0;
}
inline IC_Field* IdentityConstraint::getFieldAt(const unsigned int index) {
if (fFields) {
return (fFields->elementAt(index));
}
return 0;
}
#endif
/**
* End of file IdentityConstraint.hpp
*/
<commit_msg>Eliminate Warning from AIX xlC 3.6: 1540-399: (W) "IC_Field" is undefined. The delete operator will not call a destructor.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 2001, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#if !defined(IDENTITYCONSTRAINT_HPP)
#define IDENTITYCONSTRAINT_HPP
/**
* The class act as a base class for schema identity constraints.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/RefVectorOf.hpp>
#include <validators/schema/identity/IC_Field.hpp>
// ---------------------------------------------------------------------------
// Forward Declarations
// ---------------------------------------------------------------------------
class IC_Selector;
class VALIDATORS_EXPORT IdentityConstraint
{
public:
// -----------------------------------------------------------------------
// Constants
// -----------------------------------------------------------------------
enum {
UNIQUE = 0,
KEY = 1,
KEYREF = 2
};
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
virtual ~IdentityConstraint();
// -----------------------------------------------------------------------
// operators
// -----------------------------------------------------------------------
bool operator== (const IdentityConstraint& other) const;
bool operator!= (const IdentityConstraint& other) const;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
virtual short getType() const = 0;
int getFieldCount() const;
XMLCh* getIdentityConstraintName() const;
XMLCh* getElementName() const;
IC_Selector* getSelector() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setSelector(IC_Selector* const selector);
// -----------------------------------------------------------------------
// Access methods
// -----------------------------------------------------------------------
void addField(IC_Field* const field);
const IC_Field* getFieldAt(const unsigned int index) const;
IC_Field* getFieldAt(const unsigned int index);
protected:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
IdentityConstraint(const XMLCh* const identityConstraintName,
const XMLCh* const elementName);
private:
// -----------------------------------------------------------------------
// Unimplemented contstructors and operators
// -----------------------------------------------------------------------
IdentityConstraint(const IdentityConstraint& other);
IdentityConstraint& operator= (const IdentityConstraint& other);
// -----------------------------------------------------------------------
// CleanUp methods
// -----------------------------------------------------------------------
void cleanUp();
// -----------------------------------------------------------------------
// Data members
//
// fIdentityConstraintName
// The identity constraint name
//
// fElemName
// The element name
//
// fSelector
// The selector information
//
// fFields
// The field(s) information
// -----------------------------------------------------------------------
XMLCh* fIdentityConstraintName;
XMLCh* fElemName;
IC_Selector* fSelector;
RefVectorOf<IC_Field>* fFields;
};
// ---------------------------------------------------------------------------
// IdentityConstraint: Getter methods
// ---------------------------------------------------------------------------
inline int IdentityConstraint::getFieldCount() const {
if (fFields) {
return fFields->size();
}
return 0;
}
inline XMLCh* IdentityConstraint::getIdentityConstraintName() const {
return fIdentityConstraintName;
}
inline XMLCh* IdentityConstraint::getElementName() const {
return fElemName;
}
inline IC_Selector* IdentityConstraint::getSelector() const {
return fSelector;
}
// ---------------------------------------------------------------------------
// IdentityConstraint: Access methods
// ---------------------------------------------------------------------------
inline void IdentityConstraint::addField(IC_Field* const field) {
if (!fFields) {
fFields = new RefVectorOf<IC_Field>(4);
}
fFields->addElement(field);
}
inline const IC_Field* IdentityConstraint::getFieldAt(const unsigned int index) const {
if (fFields) {
return (fFields->elementAt(index));
}
return 0;
}
inline IC_Field* IdentityConstraint::getFieldAt(const unsigned int index) {
if (fFields) {
return (fFields->elementAt(index));
}
return 0;
}
#endif
/**
* End of file IdentityConstraint.hpp
*/
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
#include <xercesc/validators/schema/identity/FieldActivator.hpp>
#include <xercesc/validators/schema/identity/ValueStore.hpp>
#include <xercesc/validators/schema/identity/IC_Field.hpp>
#include <xercesc/validators/schema/identity/IC_KeyRef.hpp>
#include <xercesc/validators/schema/identity/ValueStoreCache.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ValueStore: Constructors and Destructor
// ---------------------------------------------------------------------------
ValueStore::ValueStore(IdentityConstraint* const ic,
XMLScanner* const scanner,
MemoryManager* const manager)
: fDoReportError(false)
, fValuesCount(0)
, fIdentityConstraint(ic)
, fValues(manager)
, fValueTuples(0)
, fKeyValueStore(0)
, fScanner(scanner)
, fMemoryManager(manager)
{
fDoReportError = (scanner && (scanner->getValidationScheme() == XMLScanner::Val_Always));
}
ValueStore::~ValueStore()
{
delete fValueTuples;
}
// ---------------------------------------------------------------------------
// ValueStore: Helper methods
// ---------------------------------------------------------------------------
void ValueStore::addValue(FieldActivator* const fieldActivator,
IC_Field* const field,
DatatypeValidator* const dv,
const XMLCh* const value) {
if (!fieldActivator->getMayMatch(field) && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_FieldMultipleMatch);
}
// do we even know this field?
int index = fValues.indexOf(field);
if (index == -1) {
if (fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_UnknownField);
}
return;
}
// store value
if (!fValues.getDatatypeValidatorAt(index) &&
!fValues.getValueAt(index)) {
fValuesCount++;
}
fValues.put(field, dv, value);
if (fValuesCount == (int) fValues.size()) {
// is this value as a group duplicated?
if (contains(&fValues)) {
duplicateValue();
}
// store values
if (!fValueTuples) {
fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager);
}
fValueTuples->addElement(new (fMemoryManager) FieldValueMap(fValues));
}
}
void ValueStore::append(const ValueStore* const other) {
if (!other->fValueTuples) {
return;
}
unsigned int tupleSize = other->fValueTuples->size();
for (unsigned int i=0; i<tupleSize; i++) {
FieldValueMap* valueMap = other->fValueTuples->elementAt(i);
if (!contains(valueMap)) {
if (!fValueTuples) {
fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager);
}
fValueTuples->addElement(new (fMemoryManager) FieldValueMap(*valueMap));
}
}
}
void ValueStore::startValueScope() {
fValuesCount = 0;
int count = fIdentityConstraint->getFieldCount();
for (int i = 0; i < count; i++) {
fValues.put(fIdentityConstraint->getFieldAt(i), 0, 0);
}
}
void ValueStore::endValueScope() {
if (fValuesCount == 0) {
if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEY && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_AbsentKeyValue,
fIdentityConstraint->getElementName());
}
return;
}
// do we have enough values?
if ((fValuesCount != fIdentityConstraint->getFieldCount()) && fDoReportError) {
if(fIdentityConstraint->getType()==IdentityConstraint::KEY)
{
fScanner->getValidator()->emitError(XMLValid::IC_KeyNotEnoughValues,
fIdentityConstraint->getElementName(), fIdentityConstraint->getIdentityConstraintName());
}
}
}
bool ValueStore::contains(const FieldValueMap* const other) {
if (fValueTuples) {
unsigned int otherSize = other->size();
unsigned int tupleSize = fValueTuples->size();
for (unsigned int i=0; i<tupleSize; i++) {
FieldValueMap* valueMap = fValueTuples->elementAt(i);
if (otherSize == valueMap->size()) {
bool matchFound = true;
for (unsigned int j=0; j<otherSize; j++) {
if (!isDuplicateOf(valueMap->getDatatypeValidatorAt(j), valueMap->getValueAt(j),
other->getDatatypeValidatorAt(j), other->getValueAt(j))) {
matchFound = false;
break;
}
}
if (matchFound) { // found it
return true;
}
}
}
}
return false;
}
bool ValueStore::isDuplicateOf(DatatypeValidator* const dv1, const XMLCh* const val1,
DatatypeValidator* const dv2, const XMLCh* const val2) {
// if either validator's null, fall back on string comparison
if(!dv1 || !dv2) {
return (XMLString::equals(val1, val2));
}
bool val1IsEmpty = (val1==0 || *val1==0);
bool val2IsEmpty = (val2==0 || *val2==0);
if (val1IsEmpty && val2IsEmpty) {
if (dv1 == dv2) {
return true;
}
return false;
}
if (val1IsEmpty || val2IsEmpty) {
return false;
}
// are the validators equal?
// As always we are obliged to compare by reference...
if (dv1 == dv2) {
return ((dv1->compare(val1, val2, fMemoryManager)) == 0);
}
// see if this.fValidator is derived from value.fValidator:
DatatypeValidator* tempVal = dv1;
for(; !tempVal || tempVal == dv2; tempVal = tempVal->getBaseValidator()) ;
if (tempVal) { // was derived!
return ((dv2->compare(val1, val2, fMemoryManager)) == 0);
}
// see if value.fValidator is derived from this.fValidator:
for(tempVal = dv2; !tempVal || tempVal == dv1; tempVal = tempVal->getBaseValidator()) ;
if(tempVal) { // was derived!
return ((dv1->compare(val1, val2, fMemoryManager)) == 0);
}
// if we're here it means the types weren't related. Must fall back to strings:
return (XMLString::equals(val1, val2));
}
// ---------------------------------------------------------------------------
// ValueStore: Document handling methods
// ---------------------------------------------------------------------------
void ValueStore::endDocumentFragment(ValueStoreCache* const valueStoreCache) {
if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEYREF) {
// verify references
// get the key store corresponding (if it exists):
fKeyValueStore = valueStoreCache->getGlobalValueStoreFor(((IC_KeyRef*) fIdentityConstraint)->getKey());
if (!fKeyValueStore) {
if (fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyRefOutOfScope,
fIdentityConstraint->getIdentityConstraintName());
}
return;
}
unsigned int count = (fValueTuples) ? fValueTuples->size() : 0;
for (unsigned int i = 0; i < count; i++) {
FieldValueMap* valueMap = fValueTuples->elementAt(i);
if (!fKeyValueStore->contains(valueMap) && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyNotFound,
fIdentityConstraint->getElementName());
}
}
}
}
// ---------------------------------------------------------------------------
// ValueStore: Error reporting methods
// ---------------------------------------------------------------------------
void ValueStore::reportNilError(IdentityConstraint* const ic) {
if (fDoReportError && ic->getType() == IdentityConstraint::ICType_KEY) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyMatchesNillable,
ic->getElementName());
}
}
void ValueStore::duplicateValue() {
if (fDoReportError) {
switch (fIdentityConstraint->getType()) {
case IdentityConstraint::ICType_UNIQUE:
{
fScanner->getValidator()->emitError(XMLValid::IC_DuplicateUnique,
fIdentityConstraint->getElementName());
break;
}
case IdentityConstraint::ICType_KEY:
{
fScanner->getValidator()->emitError(XMLValid::IC_DuplicateKey,
fIdentityConstraint->getElementName());
break;
}
}
}
}
XERCES_CPP_NAMESPACE_END
/**
* End of file ValueStore.cpp
*/
<commit_msg>Fix backport of XERCESC-1237<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/framework/XMLValidator.hpp>
#include <xercesc/validators/datatype/DatatypeValidator.hpp>
#include <xercesc/validators/schema/identity/FieldActivator.hpp>
#include <xercesc/validators/schema/identity/ValueStore.hpp>
#include <xercesc/validators/schema/identity/IC_Field.hpp>
#include <xercesc/validators/schema/identity/IC_KeyRef.hpp>
#include <xercesc/validators/schema/identity/ValueStoreCache.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ValueStore: Constructors and Destructor
// ---------------------------------------------------------------------------
ValueStore::ValueStore(IdentityConstraint* const ic,
XMLScanner* const scanner,
MemoryManager* const manager)
: fDoReportError(false)
, fValuesCount(0)
, fIdentityConstraint(ic)
, fValues(manager)
, fValueTuples(0)
, fKeyValueStore(0)
, fScanner(scanner)
, fMemoryManager(manager)
{
fDoReportError = (scanner && (scanner->getValidationScheme() == XMLScanner::Val_Always));
}
ValueStore::~ValueStore()
{
delete fValueTuples;
}
// ---------------------------------------------------------------------------
// ValueStore: Helper methods
// ---------------------------------------------------------------------------
void ValueStore::addValue(FieldActivator* const fieldActivator,
IC_Field* const field,
DatatypeValidator* const dv,
const XMLCh* const value) {
if (!fieldActivator->getMayMatch(field) && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_FieldMultipleMatch);
}
// do we even know this field?
int index = fValues.indexOf(field);
if (index == -1) {
if (fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_UnknownField);
}
return;
}
// store value
if (!fValues.getDatatypeValidatorAt(index) &&
!fValues.getValueAt(index)) {
fValuesCount++;
}
fValues.put(field, dv, value);
if (fValuesCount == (int) fValues.size()) {
// is this value as a group duplicated?
if (contains(&fValues)) {
duplicateValue();
}
// store values
if (!fValueTuples) {
fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager);
}
fValueTuples->addElement(new (fMemoryManager) FieldValueMap(fValues));
}
}
void ValueStore::append(const ValueStore* const other) {
if (!other->fValueTuples) {
return;
}
unsigned int tupleSize = other->fValueTuples->size();
for (unsigned int i=0; i<tupleSize; i++) {
FieldValueMap* valueMap = other->fValueTuples->elementAt(i);
if (!contains(valueMap)) {
if (!fValueTuples) {
fValueTuples = new (fMemoryManager) RefVectorOf<FieldValueMap>(4, true, fMemoryManager);
}
fValueTuples->addElement(new (fMemoryManager) FieldValueMap(*valueMap));
}
}
}
void ValueStore::startValueScope() {
fValuesCount = 0;
int count = fIdentityConstraint->getFieldCount();
for (int i = 0; i < count; i++) {
fValues.put(fIdentityConstraint->getFieldAt(i), 0, 0);
}
}
void ValueStore::endValueScope() {
if (fValuesCount == 0) {
if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEY && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_AbsentKeyValue,
fIdentityConstraint->getElementName());
}
return;
}
// do we have enough values?
if ((fValuesCount != fIdentityConstraint->getFieldCount()) && fDoReportError) {
if(fIdentityConstraint->getType()==IdentityConstraint::ICType_KEY)
{
fScanner->getValidator()->emitError(XMLValid::IC_KeyNotEnoughValues,
fIdentityConstraint->getElementName(), fIdentityConstraint->getIdentityConstraintName());
}
}
}
bool ValueStore::contains(const FieldValueMap* const other) {
if (fValueTuples) {
unsigned int otherSize = other->size();
unsigned int tupleSize = fValueTuples->size();
for (unsigned int i=0; i<tupleSize; i++) {
FieldValueMap* valueMap = fValueTuples->elementAt(i);
if (otherSize == valueMap->size()) {
bool matchFound = true;
for (unsigned int j=0; j<otherSize; j++) {
if (!isDuplicateOf(valueMap->getDatatypeValidatorAt(j), valueMap->getValueAt(j),
other->getDatatypeValidatorAt(j), other->getValueAt(j))) {
matchFound = false;
break;
}
}
if (matchFound) { // found it
return true;
}
}
}
}
return false;
}
bool ValueStore::isDuplicateOf(DatatypeValidator* const dv1, const XMLCh* const val1,
DatatypeValidator* const dv2, const XMLCh* const val2) {
// if either validator's null, fall back on string comparison
if(!dv1 || !dv2) {
return (XMLString::equals(val1, val2));
}
bool val1IsEmpty = (val1==0 || *val1==0);
bool val2IsEmpty = (val2==0 || *val2==0);
if (val1IsEmpty && val2IsEmpty) {
if (dv1 == dv2) {
return true;
}
return false;
}
if (val1IsEmpty || val2IsEmpty) {
return false;
}
// are the validators equal?
// As always we are obliged to compare by reference...
if (dv1 == dv2) {
return ((dv1->compare(val1, val2, fMemoryManager)) == 0);
}
// see if this.fValidator is derived from value.fValidator:
DatatypeValidator* tempVal = dv1;
for(; !tempVal || tempVal == dv2; tempVal = tempVal->getBaseValidator()) ;
if (tempVal) { // was derived!
return ((dv2->compare(val1, val2, fMemoryManager)) == 0);
}
// see if value.fValidator is derived from this.fValidator:
for(tempVal = dv2; !tempVal || tempVal == dv1; tempVal = tempVal->getBaseValidator()) ;
if(tempVal) { // was derived!
return ((dv1->compare(val1, val2, fMemoryManager)) == 0);
}
// if we're here it means the types weren't related. Must fall back to strings:
return (XMLString::equals(val1, val2));
}
// ---------------------------------------------------------------------------
// ValueStore: Document handling methods
// ---------------------------------------------------------------------------
void ValueStore::endDocumentFragment(ValueStoreCache* const valueStoreCache) {
if (fIdentityConstraint->getType() == IdentityConstraint::ICType_KEYREF) {
// verify references
// get the key store corresponding (if it exists):
fKeyValueStore = valueStoreCache->getGlobalValueStoreFor(((IC_KeyRef*) fIdentityConstraint)->getKey());
if (!fKeyValueStore) {
if (fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyRefOutOfScope,
fIdentityConstraint->getIdentityConstraintName());
}
return;
}
unsigned int count = (fValueTuples) ? fValueTuples->size() : 0;
for (unsigned int i = 0; i < count; i++) {
FieldValueMap* valueMap = fValueTuples->elementAt(i);
if (!fKeyValueStore->contains(valueMap) && fDoReportError) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyNotFound,
fIdentityConstraint->getElementName());
}
}
}
}
// ---------------------------------------------------------------------------
// ValueStore: Error reporting methods
// ---------------------------------------------------------------------------
void ValueStore::reportNilError(IdentityConstraint* const ic) {
if (fDoReportError && ic->getType() == IdentityConstraint::ICType_KEY) {
fScanner->getValidator()->emitError(XMLValid::IC_KeyMatchesNillable,
ic->getElementName());
}
}
void ValueStore::duplicateValue() {
if (fDoReportError) {
switch (fIdentityConstraint->getType()) {
case IdentityConstraint::ICType_UNIQUE:
{
fScanner->getValidator()->emitError(XMLValid::IC_DuplicateUnique,
fIdentityConstraint->getElementName());
break;
}
case IdentityConstraint::ICType_KEY:
{
fScanner->getValidator()->emitError(XMLValid::IC_DuplicateKey,
fIdentityConstraint->getElementName());
break;
}
}
}
}
XERCES_CPP_NAMESPACE_END
/**
* End of file ValueStore.cpp
*/
<|endoftext|> |
<commit_before>#include "treemodel.h"
TreeModel::TreeModel (QObject * parent, tree_data_t * data)
: QAbstractItemModel(parent)
, m_tree_data(data)
{ }
TreeModel::~TreeModel () { /* leave m_tree_data untouched. they are owned by sessionState */ }
QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
//if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
// return QString("grr");
return QVariant();
}
int TreeModel::rowCount (QModelIndex const & parent) const
{
node_t const * const parent_node = itemFromIndex(parent);
int count = 0;
node_t const * child = parent_node->children;
while (child)
{
++count;
child = child->next;
}
return count;
}
int TreeModel::columnCount (QModelIndex const & parent) const
{
return 1; // @TODO: not supported yet
}
TreeModel::node_t const * TreeModel::itemFromIndex (QModelIndex const & index) const
{
if (index.isValid())
if (node_t const * node = static_cast<node_t const *>(index.internalPointer()))
return node;
return m_tree_data->root;
}
TreeModel::node_t * TreeModel::itemFromIndex (QModelIndex const & index)
{
if (index.isValid())
if (node_t * node = static_cast<node_t *>(index.internalPointer()))
return node;
return m_tree_data->root;
}
QModelIndex TreeModel::index (int row, int column, QModelIndex const & parent) const
{
if (parent.isValid() && parent.column() != 0)
return QModelIndex();
if (node_t * const parent_item = const_cast<node_t *>(itemFromIndex(parent))) // sigh, const_cast
if (node_t * const child_item = node_t::node_child(parent_item, row))
return createIndex(row, column, child_item);
return QModelIndex();
}
QModelIndex TreeModel::parent (QModelIndex const & index) const
{
if (!index.isValid())
return QModelIndex();
node_t const * const item = itemFromIndex(index);
node_t * const parent_node = item->parent;
if (parent_node == m_tree_data->root)
return QModelIndex();
int const parent_row = parent_node->row;
int const parent_column = 0;
QModelIndex const parent = createIndex(parent_row, parent_column, parent_node);
return parent;
}
QModelIndex TreeModel::indexFromItem (node_t const * item) const
{
int const row = item->row;
int const column = 0;
int const parent_row = item->parent->row;
int const parent_column = 0;
void * const parent_node = item->parent;
QModelIndex const parent = createIndex(parent_row, parent_column, parent_node);
QModelIndex const idx = index(row, column, parent);
return idx;
}
QVariant TreeModel::data (QModelIndex const & index, int role) const
{
if (!index.isValid())
return QVariant();
node_t const * const item = itemFromIndex(index);
if (role == Qt::DisplayRole)
{
return QVariant(QString::fromStdString(item->key));
//@TODO: columns: return item->data(index.column());
}
else if (role == Qt::UserRole) // collapsed or expanded?
{
return static_cast<bool>(item->data.m_collapsed);
}
else if (role == Qt::CheckStateRole)
{
return static_cast<Qt::CheckState>(item->data.m_state);
}
return QVariant();
}
void TreeModel::onExpanded (QModelIndex const & idx)
{
setData(idx, 0, Qt::UserRole);
}
void TreeModel::onCollapsed (QModelIndex const & idx)
{
setData(idx, 1, Qt::UserRole);
}
bool TreeModel::insertItem (std::string const & path)
{
TreeModelItem i;
bool const present = m_tree_data->is_present(path, i);
if (present)
return false;
node_t const * const n = m_tree_data->set_to_state(path, i);
QModelIndex idx = indexFromItem(n);
emit dataChanged(idx, idx);
}
bool TreeModel::selectItem (std::string const & s)
{
return true; // @TODO
}
bool TreeModel::setData (QModelIndex const & index, QVariant const & value, int role)
{
if (!index.isValid()) return false;
node_t * const item = itemFromIndex(index);
if (role == Qt::DisplayRole)
return false;
else if (role == Qt::UserRole)
{
bool const collapsed = value.toBool();
item->data.m_collapsed = collapsed;
}
else if (role == Qt::CheckStateRole)
{
int const state = value.toInt();
item->data.m_state = state;
}
else
return false;
emit dataChanged(index, index);
}
Qt::ItemFlags TreeModel::flags (QModelIndex const & index) const
{
return QAbstractItemModel::flags(index)
| Qt::ItemIsEnabled
| Qt::ItemIsUserCheckable
| Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled
| Qt::ItemIsSelectable
| Qt::ItemIsTristate;
}
bool TreeModel::insertColumns (int position, int columns, QModelIndex const & parent)
{
bool success = true;
beginInsertColumns(parent, position, position + columns - 1);
//success = rootItem->insertColumns(position, columns);
endInsertColumns();
return success;
}
bool TreeModel::insertRows (int position, int rows, QModelIndex const & parent)
{
node_t * parent_item = itemFromIndex(parent);
bool success = true;
beginInsertRows(parent, position, position + rows - 1);
//success = parentItem->insertChildren(position, rows, rootItem->columnCount());
endInsertRows();
return success;
}
<commit_msg>* pokus<commit_after>#include "treemodel.h"
TreeModel::TreeModel (QObject * parent, tree_data_t * data)
: QAbstractItemModel(parent)
, m_tree_data(data)
{ }
TreeModel::~TreeModel () { /* leave m_tree_data untouched. they are owned by sessionState */ }
QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
//if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
// return QString("grr");
return QVariant();
}
int TreeModel::rowCount (QModelIndex const & parent) const
{
node_t const * const parent_node = itemFromIndex(parent);
int count = 0;
node_t const * child = parent_node->children;
while (child)
{
++count;
child = child->next;
}
return count;
}
int TreeModel::columnCount (QModelIndex const & parent) const
{
return 1; // @TODO: not supported yet
}
TreeModel::node_t const * TreeModel::itemFromIndex (QModelIndex const & index) const
{
if (index.isValid())
if (node_t const * node = static_cast<node_t const *>(index.internalPointer()))
return node;
return m_tree_data->root;
}
TreeModel::node_t * TreeModel::itemFromIndex (QModelIndex const & index)
{
if (index.isValid())
if (node_t * node = static_cast<node_t *>(index.internalPointer()))
return node;
return m_tree_data->root;
}
QModelIndex TreeModel::index (int row, int column, QModelIndex const & parent) const
{
if (parent.isValid() && parent.column() != 0)
return QModelIndex();
if (node_t * const parent_item = const_cast<node_t *>(itemFromIndex(parent))) // sigh, const_cast
if (node_t * const child_item = node_t::node_child(parent_item, row))
return createIndex(row, column, child_item);
return QModelIndex();
}
QModelIndex TreeModel::parent (QModelIndex const & index) const
{
if (!index.isValid())
return QModelIndex();
node_t const * const item = itemFromIndex(index);
node_t * const parent_node = item->parent;
if (parent_node == m_tree_data->root)
return QModelIndex();
int const parent_row = parent_node->row;
int const parent_column = 0;
QModelIndex const parent = createIndex(parent_row, parent_column, parent_node);
return parent;
}
QModelIndex TreeModel::indexFromItem (node_t const * item) const
{
int const row = item->row;
int const column = 0;
int const parent_row = item->parent->row;
int const parent_column = 0;
void * const parent_node = item->parent;
QModelIndex const parent = createIndex(parent_row, parent_column, parent_node);
QModelIndex const idx = index(row, column, parent);
return idx;
}
QVariant TreeModel::data (QModelIndex const & index, int role) const
{
if (!index.isValid())
return QVariant();
node_t const * const item = itemFromIndex(index);
if (role == Qt::DisplayRole)
{
return QVariant(QString::fromStdString(item->key));
//@TODO: columns: return item->data(index.column());
}
else if (role == Qt::UserRole) // collapsed or expanded?
{
return static_cast<bool>(item->data.m_collapsed);
}
else if (role == Qt::CheckStateRole)
{
return static_cast<Qt::CheckState>(item->data.m_state);
}
return QVariant();
}
void TreeModel::onExpanded (QModelIndex const & idx)
{
setData(idx, 0, Qt::UserRole);
}
void TreeModel::onCollapsed (QModelIndex const & idx)
{
setData(idx, 1, Qt::UserRole);
}
bool TreeModel::insertItem (std::string const & path)
{
TreeModelItem i;
bool const present = m_tree_data->is_present(path, i);
if (present)
return false;
node_t const * const n = m_tree_data->set_to_state(path, i);
QModelIndex idx = indexFromItem(n);
emit dataChanged(idx, idx);
}
bool TreeModel::selectItem (std::string const & s)
{
return true; // @TODO
}
bool TreeModel::setData (QModelIndex const & index, QVariant const & value, int role)
{
if (!index.isValid()) return false;
node_t * const item = itemFromIndex(index);
if (role == Qt::DisplayRole)
return false;
else if (role == Qt::UserRole)
{
bool const collapsed = value.toBool();
item->data.m_collapsed = collapsed;
}
else if (role == Qt::CheckStateRole)
{
int const state = value.toInt();
item->data.m_state = state;
}
else
return false;
emit dataChanged(index, index);
}
Qt::ItemFlags TreeModel::flags (QModelIndex const & index) const
{
return QAbstractItemModel::flags(index)
| Qt::ItemIsEnabled
| Qt::ItemIsUserCheckable
| Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled
| Qt::ItemIsSelectable
| Qt::ItemIsTristate;
}
bool TreeModel::insertColumns (int position, int columns, QModelIndex const & parent)
{
bool success = true;
beginInsertColumns(parent, position, position + columns - 1);
//success = rootItem->insertColumns(position, columns);
endInsertColumns();
return success;
}
bool TreeModel::insertRows (int position, int rows, QModelIndex const & parent)
{
node_t * parent_item = itemFromIndex(parent);
bool success = true;
beginInsertRows(parent, position, position + rows - 1);
//success = parentItem->insertChildren(position, rows, rootItem->columnCount());
endInsertRows();
return success;
}
void TreeModel::modelItemChanged (QStandardItem * item)
{
QStandardItem * parent = item->parent();
int checkCount = 0;
int rowCount = parent->rowCount();
for (int i = 0; i < rowCount; i++)
if (parent->child(i)->checkState() == Qt::Checked)
checkCount++;
switch (checkCount)
{
case 0:
parent->setCheckState(Qt::Unchecked);
break;
case rowCount:
parent->setCheckState(Qt::Checked);
break;
default:
parent->setCheckState(Qt::PartiallyChecked);
}
}
void TreeModel::ModelItemChanged (QStandardItem * item)
{
QStandardItem * parent = item->parent();
if (parent == 0)
{
//folder state changed--> update children if not partially selected
Qt::CheckState newState = item->checkState();
if(newState != Qt::PartiallyChecked){
for (int i = 0; i < item->rowCount(); i++)
{
item->child(i)->setCheckState(newState);
}
}
}
else
{
//child item changed--> count parent's children that are checked
int checkCount = 0;
for (int i = 0; i < parent->rowCount(); i++)
{
if (parent->child(i)->checkState() == Qt::Checked)
checkCount++;
}
if(checkCount == 0)
parent->setCheckState(Qt::Unchecked);
else if (checkCount == parent->rowCount())
parent->setCheckState(Qt::Checked);
else
parent->setCheckState(Qt::PartiallyChecked);
}
}
<|endoftext|> |
<commit_before>//
// Sophos - Forward Private Searchable Encryption
// Copyright (C) 2016 Raphael Bost
//
// This file is part of Sophos.
//
// Sophos 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.
//
// Sophos 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 Sophos. If not, see <http://www.gnu.org/licenses/>.
//
#pragma once
#include <utility>
#include <memory>
#include <grpc/grpc.h>
namespace sse {
namespace sophos {
typedef struct
{
std::unique_ptr< google::protobuf::Empty > reply;
std::unique_ptr< grpc::Status > status;
std::unique_ptr< size_t > index;
} update_tag_type;
}
}<commit_msg>Include the Empty protobuf type.<commit_after>//
// Sophos - Forward Private Searchable Encryption
// Copyright (C) 2016 Raphael Bost
//
// This file is part of Sophos.
//
// Sophos 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.
//
// Sophos 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 Sophos. If not, see <http://www.gnu.org/licenses/>.
//
#pragma once
#include <utility>
#include <memory>
#include <grpc/grpc.h>
#include <google/protobuf/empty.pb.h>
namespace sse {
namespace sophos {
typedef struct
{
std::unique_ptr< google::protobuf::Empty > reply;
std::unique_ptr< grpc::Status > status;
std::unique_ptr< size_t > index;
} update_tag_type;
}
}<|endoftext|> |
<commit_before>#include "dagent/dagent.h"
#include "base/logger.h"
#include "dcreporter.h"
#include "dcreport_collect.h"
int reporter_ready(){
return dagent_ready();
}
int reporter_init(const char * parent, const char * name){
dagent_config_t conf;
conf.addr = "push://";
conf.addr += parent;
conf.name = name;
if (dagent_init(conf)){
GLOG_TRA("dagent init error !");
return -1;
}
return 0;
}
void reporter_destroy(){
dagent_destroy();
}
void reporter_update(int timeout_ms){
return dagent_update(timeout_ms);
}
int report_set(const char * k, const char * val){
if (strchr(k, ':')){
GLOG_TRA("error input param or k !");
return -1;
}
std::string msg = k;
msg += ":";
msg += val;
return dagent_send("dccollector", REPORT_MSG_SET, msg_buffer_t(msg));
}
int report_inc(const char * k, int inc , const char * param){
if (strchr(k, ':') || (param && strchr(param, ':'))){
GLOG_TRA("error input param or k !");
return -1;
}
std::string msg = k;
msg += ":";
msg += std::to_string(inc);
if (param){
msg += ":";
msg += param;
}
return dagent_send("dccollector", REPORT_MSG_INC, msg_buffer_t(msg));
}
int report_dec(const char * k, int dec, const char * param){
if (strchr(k, ':') || (param && strchr(param, ':'))){
GLOG_TRA("error input param or k !");
return -1;
}
std::string msg = k;
msg += ":";
msg += std::to_string(dec);
if (param){
msg += ":";
msg += param;
}
return dagent_send("dccollector", REPORT_MSG_DEC, msg_buffer_t(msg));
}<commit_msg>error<commit_after>#include "dagent/dagent.h"
#include "base/logger.h"
#include "dcreporter.h"
#include "dcreport_collect.h"
int reporter_ready(){
return dagent_ready();
}
int reporter_init(const char * parent, const char * name){
dagent_config_t conf;
conf.addr = "push:";
conf.addr += parent;
conf.name = name;
if (dagent_init(conf)){
GLOG_TRA("dagent init error !");
return -1;
}
return 0;
}
void reporter_destroy(){
dagent_destroy();
}
void reporter_update(int timeout_ms){
return dagent_update(timeout_ms);
}
int report_set(const char * k, const char * val){
if (strchr(k, ':')){
GLOG_TRA("error input param or k !");
return -1;
}
std::string msg = k;
msg += ":";
msg += val;
return dagent_send("dccollector", REPORT_MSG_SET, msg_buffer_t(msg));
}
int report_inc(const char * k, int inc , const char * param){
if (strchr(k, ':') || (param && strchr(param, ':'))){
GLOG_TRA("error input param or k !");
return -1;
}
std::string msg = k;
msg += ":";
msg += std::to_string(inc);
if (param){
msg += ":";
msg += param;
}
return dagent_send("dccollector", REPORT_MSG_INC, msg_buffer_t(msg));
}
int report_dec(const char * k, int dec, const char * param){
if (strchr(k, ':') || (param && strchr(param, ':'))){
GLOG_TRA("error input param or k !");
return -1;
}
std::string msg = k;
msg += ":";
msg += std::to_string(dec);
if (param){
msg += ":";
msg += param;
}
return dagent_send("dccollector", REPORT_MSG_DEC, msg_buffer_t(msg));
}<|endoftext|> |
<commit_before>#include <fstream>
#include <sstream>
#include <glog/logging.h>
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
// Name of the main program window
static const std::string W_NAME = "WINDOW";
cv::Mat orignal_image, mask;
cv::Mat lum, red, blu;
// Drawing vars
bool drawing = false;
std::vector<cv::Rect*> boxes;
int box_size = 10;
cv::Scalar box_color(0,0,255);
std::string getUsage() {
std::stringstream ss;
ss << "Usage: <image> <min_area> <max_area>";
return ss.str();
}
std::string getDesc() {
std::stringstream ss;
ss << "Description: All inputs should be normalized: [0, 1]";
return ss.str();
}
void draw() {
cv::Mat masked;
orignal_image.copyTo(masked, mask);
for (cv::Rect *box : boxes) {
cv::rectangle(masked, *box, box_color, box_size);
}
cv::imshow(W_NAME, masked);
}
void onMouseCallback(int event, int x, int y, int flags, void *) {
if (event == cv::EVENT_LBUTTONDOWN) {
drawing = true;
boxes.push_back(new cv::Rect(x,y,0,0));
} else if (event == cv::EVENT_LBUTTONUP) {
cv::Rect *box = boxes.back();
drawing = false;
if (box->width <= 0) {
box->x += box->width;
box->width *= -1;
}
if (box->height <= 0) {
box->y += box->height;
box->height *= -1;
}
draw();
} else if (event == cv::EVENT_MOUSEMOVE) {
if (drawing) {
cv::Rect *box = boxes.back();
box->width = x - box->x;
box->height = y - box->y;
draw();
}
}
}
void onBisonSlider(int slider_value, void*) {
mask = red > slider_value;
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5,5), cv::Point(0,0));
cv::morphologyEx(mask, mask, cv::MORPH_OPEN, kernel);
cv::morphologyEx(mask, mask, cv::MORPH_CLOSE, kernel);
draw();
}
void onCalfSlider(int slider_value, void*) {
return;
}
void cropImage(int, void*) {
//Mask image
cv::Mat masked;
orignal_image.copyTo(masked, mask);
for (cv::Rect *box : boxes) {
cv::rectangle(masked, *box, cv::Scalar(0,0,0), CV_FILLED);
}
imwrite("masked.jpg", masked);
// Loop to extract training data from the bison mask
unsigned int inc = 0;
for (int r = 0; r < orignal_image.rows-33; r++) {
for (int c = 0; c < orignal_image.cols-33; c++) {
cv::Vec3f pixel = masked.at<cv::Vec3b>(r+16,c+16);
uchar blue = pixel[0];
uchar green = pixel[1];
uchar red = pixel[2];
if (blue > 0 || green > 0 || red > 0) {
cv::Rect crop_rect = cv::Rect(c, r, 32, 32);
std::stringstream ss;
ss << "Cropping " << crop_rect;
cv::displayStatusBar(W_NAME, ss.str());
cv::Mat crop_image(32, 32, CV_8UC3, cv::Scalar(0, 0, 0));
orignal_image(crop_rect).copyTo(crop_image);
imwrite("training_data/" + std::to_string(inc) + ".jpg", crop_image);
inc++;
}
}
}
cv::displayStatusBar(W_NAME, "Created " + std::to_string(inc) + " images.", 60000);
}
void toggleRects(int checked, void*) {
if (checked) {
box_size = 10;
box_color = cv::Scalar(0,0,255);
} else {
box_size = CV_FILLED;
box_color = cv::Scalar(0,0,0);
}
draw();
}
void clearRects(int, void*) {
for (cv::Rect *box : boxes) {
delete(box);
}
boxes.clear();
draw();
}
int main(int argc, char** argv) {
// Log to stderr instead of to the tmp directory
FLAGS_logtostderr = 1;
// Initiate Google Logging
google::InitGoogleLogging(argv[0]);
if (argc < 2) {
LOG(ERROR) << "Not enough arguments:";
LOG(ERROR) << getUsage();
LOG(ERROR) << getDesc();
exit(1);
}
// Read input values
std::string img_filename = argv[1];
orignal_image = cv::imread(img_filename, CV_LOAD_IMAGE_COLOR);
//cv::GaussianBlur(original_image, image, cv::Size(0, 0), 5);
if (orignal_image.empty()) {
LOG(FATAL) << "Image failed to load...";
}
cv::Mat ycc;
cv::cvtColor(orignal_image, ycc, CV_BGR2YCrCb);
std::vector<cv::Mat> ycc_channels;
cv::split(ycc, ycc_channels);
lum = ycc_channels[0];
red = ycc_channels[1];
blu = ycc_channels[2];
int bison_slider = 132;
int calf_slider = 141;
cv::namedWindow(W_NAME, CV_GUI_EXPANDED);
cv::setMouseCallback(W_NAME, onMouseCallback);
cv::createButton("Show Boxes", toggleRects, NULL, CV_CHECKBOX,1);
cv::createTrackbar("Bison", "", &bison_slider, 255, onBisonSlider);
cv::createTrackbar("Calf", "", &calf_slider, 255, onCalfSlider);
cv::createButton("Clear Rectangles", clearRects);
cv::createButton("Run Crop", cropImage);
onBisonSlider(bison_slider, 0);
cv::waitKey(0);
return 0;
}
<commit_msg>Add min and max sliders and transparency to image crop<commit_after>#include <fstream>
#include <sstream>
#include <glog/logging.h>
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
// Name of the main program window
static const std::string W_NAME = "WINDOW";
cv::Mat original_image, mask;
cv::Mat lum, red, blu;
int min_slider = 132;
int max_slider = 141;
// Drawing vars
bool drawing = false;
std::vector<cv::Rect*> boxes;
int box_size = 10;
cv::Scalar box_color(0,0,255);
std::string getUsage() {
std::stringstream ss;
ss << "Usage: <image> <min_area> <max_area>";
return ss.str();
}
std::string getDesc() {
std::stringstream ss;
ss << "Description: All inputs should be normalized: [0, 1]";
return ss.str();
}
void draw() {
cv::Mat temp_mask, masked;
cv::cvtColor(mask, temp_mask, CV_GRAY2BGR);
for (cv::Rect *box : boxes) {
cv::rectangle(temp_mask, *box, box_color, box_size);
}
masked = original_image*0.5 + temp_mask*0.5;
cv::imshow(W_NAME, masked);
}
void onMouseCallback(int event, int x, int y, int flags, void *) {
if (event == cv::EVENT_LBUTTONDOWN) {
drawing = true;
boxes.push_back(new cv::Rect(x,y,0,0));
} else if (event == cv::EVENT_LBUTTONUP) {
cv::Rect *box = boxes.back();
drawing = false;
if (box->width <= 0) {
box->x += box->width;
box->width *= -1;
}
if (box->height <= 0) {
box->y += box->height;
box->height *= -1;
}
draw();
} else if (event == cv::EVENT_MOUSEMOVE) {
if (drawing) {
cv::Rect *box = boxes.back();
box->width = x - box->x;
box->height = y - box->y;
draw();
}
}
}
void onSlider(int slider_value, void*) {
cv::Mat max_mask = red <= max_slider;
cv::Mat min_mask = red >= min_slider;
cv::bitwise_and(max_mask, min_mask, mask);
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5,5), cv::Point(0,0));
cv::morphologyEx(mask, mask, cv::MORPH_OPEN, kernel);
cv::morphologyEx(mask, mask, cv::MORPH_CLOSE, kernel);
draw();
}
void cropImage(int, void*) {
//Mask image
cv::Mat masked;
original_image.copyTo(masked, mask);
for (cv::Rect *box : boxes) {
cv::rectangle(masked, *box, cv::Scalar(0,0,0), CV_FILLED);
}
imwrite("masked.jpg", masked);
// Loop to extract training data from the bison mask
unsigned int inc = 0;
for (int r = 0; r < original_image.rows-33; r++) {
for (int c = 0; c < original_image.cols-33; c++) {
cv::Vec3f pixel = masked.at<cv::Vec3b>(r+16,c+16);
uchar blue = pixel[0];
uchar green = pixel[1];
uchar red = pixel[2];
if (blue > 0 || green > 0 || red > 0) {
cv::Rect crop_rect = cv::Rect(c, r, 32, 32);
std::stringstream ss;
ss << "Cropping " << crop_rect;
cv::displayStatusBar(W_NAME, ss.str());
cv::Mat crop_image(32, 32, CV_8UC3, cv::Scalar(0, 0, 0));
original_image(crop_rect).copyTo(crop_image);
imwrite("training_data/" + std::to_string(inc) + ".jpg", crop_image);
inc++;
}
}
}
cv::displayStatusBar(W_NAME, "Created " + std::to_string(inc) + " images.", 60000);
}
void toggleRects(int checked, void*) {
if (checked) {
box_size = 10;
box_color = cv::Scalar(0,0,255);
} else {
box_size = CV_FILLED;
box_color = cv::Scalar(0,0,0);
}
draw();
}
void clearRects(int, void*) {
for (cv::Rect *box : boxes) {
delete(box);
}
boxes.clear();
draw();
}
int main(int argc, char** argv) {
// Log to stderr instead of to the tmp directory
FLAGS_logtostderr = 1;
// Initiate Google Logging
google::InitGoogleLogging(argv[0]);
if (argc < 2) {
LOG(ERROR) << "Not enough arguments:";
LOG(ERROR) << getUsage();
LOG(ERROR) << getDesc();
exit(1);
}
// Read input values
std::string img_filename = argv[1];
original_image = cv::imread(img_filename, CV_LOAD_IMAGE_COLOR);
//cv::GaussianBlur(original_image, image, cv::Size(0, 0), 5);
if (original_image.empty()) {
LOG(FATAL) << "Image failed to load...";
}
cv::Mat ycc;
cv::cvtColor(original_image, ycc, CV_BGR2YCrCb);
std::vector<cv::Mat> ycc_channels;
cv::split(ycc, ycc_channels);
lum = ycc_channels[0];
red = ycc_channels[1];
blu = ycc_channels[2];
cv::namedWindow(W_NAME, CV_GUI_EXPANDED);
cv::setMouseCallback(W_NAME, onMouseCallback);
cv::createButton("Show Boxes", toggleRects, NULL, CV_CHECKBOX,1);
cv::createTrackbar("Max", W_NAME, &max_slider, 255, onSlider);
cv::createTrackbar("Min", W_NAME, &min_slider, 255, onSlider);
cv::createButton("Clear Rectangles", clearRects);
cv::createButton("Run Crop", cropImage);
onSlider(max_slider, 0);
cv::waitKey(0);
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: image_util.cpp 36 2005-04-05 14:32:18Z pavlenko $
// stl
#include <string>
// mapnik
#include <mapnik/graphics.hpp>
#include <mapnik/memory.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_view.hpp>
// jpeg png
extern "C"
{
#include <png.h>
#include <jpeglib.h>
}
namespace mapnik
{
//use memory manager for mem allocation in libpng
png_voidp malloc_fn(png_structp png_ptr,png_size_t size)
{
return Object::operator new(size);
}
void free_fn(png_structp png_ptr, png_voidp ptr)
{
Object::operator delete(ptr);
}
template <typename T>
void save_to_file(std::string const& filename,
std::string const& type,
T const& image)
{
//all that should go into image_writer factory
if (type=="png")
{
save_as_png(filename,image);
}
else if (type=="jpeg")
{
save_as_jpeg(filename,85,image);
}
}
template <typename T>
void save_as_png(std::string const& filename, T const& image)
{
FILE *fp=fopen(filename.c_str(), "wb");
if (!fp) return;
png_voidp mem_ptr=0;
png_structp png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING,
(png_voidp)mem_ptr,0, 0);
if (!png_ptr) return;
png_set_mem_fn(png_ptr,mem_ptr,malloc_fn,free_fn);
// switch on optimization only if supported
#if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
png_uint_32 mask, flags;
flags = png_get_asm_flags(png_ptr);
mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE);
png_set_asm_flags(png_ptr, flags | mask);
#endif
png_set_filter (png_ptr, 0, PNG_FILTER_NONE);
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
png_destroy_write_struct(&png_ptr,(png_infopp)0);
fclose(fp);
return;
}
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return;
}
png_init_io(png_ptr, fp);
//png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
//png_set_compression_strategy(png_ptr, Z_FILTERED);
png_set_IHDR(png_ptr, info_ptr,image.width(),image.height(),8,
PNG_COLOR_TYPE_RGB_ALPHA,PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
for (unsigned i=0;i<image.height();i++)
{
png_write_row(png_ptr,(png_bytep)image.getRow(i));
}
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
}
template <typename T>
void save_as_jpeg(std::string const& filename,int quality, T const& image)
{
FILE *fp=fopen(filename.c_str(), "wb");
if (!fp) return;
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
int width=image.width();
int height=image.height();
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, fp);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality,1);
jpeg_start_compress(&cinfo, 1);
JSAMPROW row_pointer[1];
JSAMPLE* row=new JSAMPLE[width*3];
while (cinfo.next_scanline < cinfo.image_height)
{
const unsigned* imageRow=image.getRow(cinfo.next_scanline);
int index=0;
for (int i=0;i<width;++i)
{
row[index++]=(imageRow[i])&0xff;
row[index++]=(imageRow[i]>>8)&0xff;
row[index++]=(imageRow[i]>>16)&0xff;
}
row_pointer[0] = &row[0];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
delete [] row;
jpeg_finish_compress(&cinfo);
fclose(fp);
jpeg_destroy_compress(&cinfo);
}
template void save_to_file<ImageData32>(std::string const&,
std::string const& ,
ImageData32 const&);
template void save_to_file<image_view<ImageData32> > (std::string const&,
std::string const& ,
image_view<ImageData32> const&);
}
<commit_msg>use libpng native alloc/dealloc (/valgrind-new-delete2.patch from Jon Burgess)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id: image_util.cpp 36 2005-04-05 14:32:18Z pavlenko $
// stl
#include <string>
// mapnik
#include <mapnik/graphics.hpp>
#include <mapnik/memory.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_view.hpp>
// jpeg png
extern "C"
{
#include <png.h>
#include <jpeglib.h>
}
namespace mapnik
{
template <typename T>
void save_to_file(std::string const& filename,
std::string const& type,
T const& image)
{
//all that should go into image_writer factory
if (type=="png")
{
save_as_png(filename,image);
}
else if (type=="jpeg")
{
save_as_jpeg(filename,85,image);
}
}
template <typename T>
void save_as_png(std::string const& filename, T const& image)
{
FILE *fp=fopen(filename.c_str(), "wb");
if (!fp) return;
png_voidp error_ptr=0;
png_structp png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING,
error_ptr,0, 0);
if (!png_ptr) return;
// switch on optimization only if supported
#if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER >= 10200) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
png_uint_32 mask, flags;
flags = png_get_asm_flags(png_ptr);
mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE);
png_set_asm_flags(png_ptr, flags | mask);
#endif
png_set_filter (png_ptr, 0, PNG_FILTER_NONE);
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
{
png_destroy_write_struct(&png_ptr,(png_infopp)0);
fclose(fp);
return;
}
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return;
}
png_init_io(png_ptr, fp);
//png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
//png_set_compression_strategy(png_ptr, Z_FILTERED);
png_set_IHDR(png_ptr, info_ptr,image.width(),image.height(),8,
PNG_COLOR_TYPE_RGB_ALPHA,PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
for (unsigned i=0;i<image.height();i++)
{
png_write_row(png_ptr,(png_bytep)image.getRow(i));
}
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
}
template <typename T>
void save_as_jpeg(std::string const& filename,int quality, T const& image)
{
FILE *fp=fopen(filename.c_str(), "wb");
if (!fp) return;
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
int width=image.width();
int height=image.height();
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, fp);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality,1);
jpeg_start_compress(&cinfo, 1);
JSAMPROW row_pointer[1];
JSAMPLE* row=new JSAMPLE[width*3];
while (cinfo.next_scanline < cinfo.image_height)
{
const unsigned* imageRow=image.getRow(cinfo.next_scanline);
int index=0;
for (int i=0;i<width;++i)
{
row[index++]=(imageRow[i])&0xff;
row[index++]=(imageRow[i]>>8)&0xff;
row[index++]=(imageRow[i]>>16)&0xff;
}
row_pointer[0] = &row[0];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
delete [] row;
jpeg_finish_compress(&cinfo);
fclose(fp);
jpeg_destroy_compress(&cinfo);
}
template void save_to_file<ImageData32>(std::string const&,
std::string const& ,
ImageData32 const&);
template void save_to_file<image_view<ImageData32> > (std::string const&,
std::string const& ,
image_view<ImageData32> const&);
}
<|endoftext|> |
<commit_before>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "wafconfig.h"
#include <iostream>
#include <string>
#include <signal.h>
#include <dlfcn.h>
#include <boost/optional.hpp>
#include <glibmm/convert.h>
#include <glibmm/miscutils.h>
#include <glibmm/spawn.h>
#include <glibmm/thread.h>
#include "raul/Path.hpp"
#include "raul/SharedPtr.hpp"
#include "redlandmm/World.hpp"
#include "shared/runtime_paths.hpp"
#include "module/global.hpp"
#include "module/Module.hpp"
#include "module/World.hpp"
#include "engine/tuning.hpp"
#include "engine/Engine.hpp"
#include "engine/QueuedEngineInterface.hpp"
#include "engine/JackAudioDriver.hpp"
#include "serialisation/Parser.hpp"
#include "cmdline.h"
#ifdef HAVE_LIBLO
#include "engine/OSCEngineReceiver.hpp"
#endif
#ifdef HAVE_SOUP
#include "engine/HTTPEngineReceiver.hpp"
#endif
#ifdef WITH_BINDINGS
#include "bindings/ingen_bindings.hpp"
#endif
using namespace std;
using namespace Ingen;
SharedPtr<Engine> engine;
void
catch_int(int)
{
signal(SIGINT, catch_int);
signal(SIGTERM, catch_int);
cout << "[Main] Ingen interrupted." << endl;
engine->quit();
}
int
main(int argc, char** argv)
{
/* Parse command line options */
gengetopt_args_info args;
if (cmdline_parser (argc, argv, &args) != 0)
return 1;
if (argc <= 1) {
cmdline_parser_print_help();
cerr << endl << "*** Ingen requires at least one command line parameter" << endl;
cerr << "*** Just want a graphical application? Try 'ingen -eg'" << endl;
return 1;
} else if (args.connect_given && args.engine_flag) {
cerr << "\n*** Nonsense arguments, can't both run a local engine "
<< "and connect to a remote one." << endl
<< "*** Run separate instances if that is what you want" << endl;
return 1;
}
/* Set bundle path from executable location so resources/modules can be found */
Shared::set_bundle_path_from_code((void*)&main);
SharedPtr<Glib::Module> engine_module;
SharedPtr<Glib::Module> engine_http_module;
SharedPtr<Glib::Module> engine_osc_module;
SharedPtr<Glib::Module> engine_queued_module;
SharedPtr<Glib::Module> engine_jack_module;
SharedPtr<Glib::Module> client_module;
SharedPtr<Glib::Module> gui_module;
SharedPtr<Glib::Module> bindings_module;
SharedPtr<Shared::EngineInterface> engine_interface;
Glib::thread_init();
#if HAVE_SOUP
g_type_init();
#endif
Ingen::Shared::World* world = Ingen::Shared::get_world();
/* Set up RDF world */
world->rdf_world->add_prefix("xsd", "http://www.w3.org/2001/XMLSchema#");
world->rdf_world->add_prefix("ingen", "http://drobilla.net/ns/ingen#");
world->rdf_world->add_prefix("ingenuity", "http://drobilla.net/ns/ingenuity#");
world->rdf_world->add_prefix("lv2", "http://lv2plug.in/ns/lv2core#");
world->rdf_world->add_prefix("lv2ev", "http://lv2plug.in/ns/ext/event#");
world->rdf_world->add_prefix("lv2var", "http://lv2plug.in/ns/ext/instance-var#");
world->rdf_world->add_prefix("lv2midi", "http://lv2plug.in/ns/ext/midi");
world->rdf_world->add_prefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
world->rdf_world->add_prefix("owl", "http://www.w3.org/2002/07/owl#");
world->rdf_world->add_prefix("doap", "http://usefulinc.com/ns/doap#");
world->rdf_world->add_prefix("dc", "http://purl.org/dc/elements/1.1/");
/* Run engine */
if (args.engine_flag) {
engine_module = Ingen::Shared::load_module("ingen_engine");
engine_http_module = Ingen::Shared::load_module("ingen_engine_http");
engine_osc_module = Ingen::Shared::load_module("ingen_engine_osc");
engine_jack_module = Ingen::Shared::load_module("ingen_engine_jack");
engine_queued_module = Ingen::Shared::load_module("ingen_engine_queued");
if (!engine_queued_module) {
cerr << "ERROR: Unable to load (queued) engine interface module" << endl;
Ingen::Shared::destroy_world();
return 1;
}
if (engine_module) {
Engine* (*new_engine)(Ingen::Shared::World* world) = NULL;
if (engine_module->get_symbol("new_engine", (void*&)new_engine)) {
engine = SharedPtr<Engine>(new_engine(world));
world->local_engine = engine;
/* Load queued (direct in-process) engine interface */
if (args.gui_given && engine_queued_module) {
Ingen::QueuedEngineInterface* (*new_interface)(Ingen::Engine& engine);
if (engine_osc_module->get_symbol("new_queued_interface", (void*&)new_interface)) {
SharedPtr<QueuedEngineInterface> interface(new_interface(*engine));
world->local_engine->add_event_source(interface);
engine_interface = interface;
world->engine = engine_interface;
}
} else {
#ifdef HAVE_LIBLO
if (engine_osc_module) {
Ingen::OSCEngineReceiver* (*new_receiver)(
Ingen::Engine& engine, size_t queue_size, uint16_t port);
if (engine_osc_module->get_symbol("new_osc_receiver", (void*&)new_receiver)) {
SharedPtr<EventSource> source(new_receiver(*engine,
pre_processor_queue_size, args.engine_port_arg));
world->local_engine->add_event_source(source);
}
}
#endif
#ifdef HAVE_SOUP
if (engine_http_module) {
// FIXE: leak
Ingen::HTTPEngineReceiver* (*new_receiver)(Ingen::Engine& engine, uint16_t port);
if (engine_http_module->get_symbol("new_http_receiver", (void*&)new_receiver)) {
boost::shared_ptr<HTTPEngineReceiver> receiver(new_receiver(
*world->local_engine, args.engine_port_arg));
world->local_engine->add_event_source(receiver);
receiver->activate();
}
}
#endif
}
} else {
engine_module.reset();
}
} else {
cerr << "Unable to load engine module." << endl;
}
}
/* Load client library */
if (args.load_given || args.gui_given) {
client_module = Ingen::Shared::load_module("ingen_client");
if (!client_module)
cerr << "Unable to load client module." << endl;
}
/* If we don't have a local engine interface (for GUI), use network */
if (client_module && ! engine_interface) {
SharedPtr<Shared::EngineInterface> (*new_remote_interface)(const std::string&) = NULL;
if (client_module->get_symbol("new_remote_interface", (void*&)new_remote_interface)) {
engine_interface = new_remote_interface(args.connect_arg);
} else {
cerr << "Unable to find symbol 'new_remote_interface' in "
"ingen_client module, aborting." << endl;
return -1;
}
}
/* Activate the engine, if we have one */
if (engine) {
Ingen::JackAudioDriver* (*new_driver)(
Ingen::Engine& engine,
const std::string server_name,
const std::string client_name,
void* jack_client) = NULL;
if (engine_jack_module->get_symbol("new_jack_audio_driver", (void*&)new_driver)) {
engine->set_driver(DataType::AUDIO, SharedPtr<Driver>(new_driver(
*engine, "default", args.jack_name_arg, NULL)));
} else {
cerr << Glib::Module::get_last_error() << endl;
}
engine->activate(args.parallelism_arg);
}
world->engine = engine_interface;
void (*gui_run)() = NULL;
/* Load GUI */
bool run_gui = false;
if (args.gui_given) {
gui_module = Ingen::Shared::load_module("ingen_gui");
if (gui_module) {
void (*init)(int, char**, Ingen::Shared::World*);
bool found = gui_module->get_symbol("init", (void*&)init);
found = found && gui_module->get_symbol("run", (void*&)gui_run);
if (found) {
run_gui = true;
init(argc, argv, world);
} else {
cerr << "Unable to find hooks in GUI module, GUI not loaded." << endl;
}
} else {
cerr << "Unable to load GUI module." << endl;
}
}
/* Load a patch */
if (args.load_given && engine_interface) {
boost::optional<Path> data_path = Path("/");
boost::optional<Path> parent;
boost::optional<Symbol> symbol;
if (args.path_given) {
const Glib::ustring path = args.path_arg;
if (Path::is_valid(path)) {
const Path p(path);
if (p != "/") {
parent = p.parent();
const string s = p.name();
if (Symbol::is_valid(s))
symbol = s;
}
} else {
cerr << "Invalid path given: '" << path << endl;
}
}
bool found = false;
if (!world->serialisation_module)
world->serialisation_module = Ingen::Shared::load_module("ingen_serialisation");
Serialisation::Parser* (*new_parser)() = NULL;
if (world->serialisation_module)
found = world->serialisation_module->get_symbol("new_parser", (void*&)new_parser);
if (world->serialisation_module && found) {
SharedPtr<Serialisation::Parser> parser(new_parser());
// Assumption: Containing ':' means URI, otherwise filename
string uri = args.load_arg;
if (uri.find(':') == string::npos) {
if (Glib::path_is_absolute(args.load_arg))
uri = Glib::filename_to_uri(args.load_arg);
else
uri = Glib::filename_to_uri(Glib::build_filename(
Glib::get_current_dir(), args.load_arg));
}
engine_interface->load_plugins();
parser->parse_document(world, engine_interface.get(), uri, data_path, parent, symbol);
} else {
cerr << "Unable to load serialisation module, aborting." << endl;
return -1;
}
}
/* Run GUI (if applicable) */
if (run_gui)
gui_run();
/* Run a script */
if (args.run_given) {
#ifdef WITH_BINDINGS
bool (*run_script)(Ingen::Shared::World*, const char*) = NULL;
SharedPtr<Glib::Module> bindings_module = Ingen::Shared::load_module("ingen_bindings");
if (bindings_module) {
bindings_module->make_resident();
bool found = bindings_module->get_symbol("run", (void*&)(run_script));
if (found) {
setenv("PYTHONPATH", "../../bindings", 1);
run_script(world, args.run_arg);
} else {
cerr << "FAILED: " << Glib::Module::get_last_error() << endl;
}
} else {
cerr << Glib::Module::get_last_error() << endl;
}
#else
cerr << "This build of ingen does not support scripting." << endl;
#endif
/* Listen to OSC and do our own main thing. */
} else if (engine && !run_gui) {
signal(SIGINT, catch_int);
signal(SIGTERM, catch_int);
engine->main();
}
if (engine) {
engine->deactivate();
engine.reset();
}
engine_interface.reset();
client_module.reset();
world->serialisation_module.reset();
gui_module.reset();
engine_module.reset();
Ingen::Shared::destroy_world();
return 0;
}
<commit_msg>Load queued interface from the appropriate module.<commit_after>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "wafconfig.h"
#include <iostream>
#include <string>
#include <signal.h>
#include <dlfcn.h>
#include <boost/optional.hpp>
#include <glibmm/convert.h>
#include <glibmm/miscutils.h>
#include <glibmm/spawn.h>
#include <glibmm/thread.h>
#include "raul/Path.hpp"
#include "raul/SharedPtr.hpp"
#include "redlandmm/World.hpp"
#include "shared/runtime_paths.hpp"
#include "module/global.hpp"
#include "module/Module.hpp"
#include "module/World.hpp"
#include "engine/tuning.hpp"
#include "engine/Engine.hpp"
#include "engine/QueuedEngineInterface.hpp"
#include "engine/JackAudioDriver.hpp"
#include "serialisation/Parser.hpp"
#include "cmdline.h"
#ifdef HAVE_LIBLO
#include "engine/OSCEngineReceiver.hpp"
#endif
#ifdef HAVE_SOUP
#include "engine/HTTPEngineReceiver.hpp"
#endif
#ifdef WITH_BINDINGS
#include "bindings/ingen_bindings.hpp"
#endif
using namespace std;
using namespace Ingen;
SharedPtr<Engine> engine;
void
catch_int(int)
{
signal(SIGINT, catch_int);
signal(SIGTERM, catch_int);
cout << "[Main] Ingen interrupted." << endl;
engine->quit();
}
int
main(int argc, char** argv)
{
/* Parse command line options */
gengetopt_args_info args;
if (cmdline_parser (argc, argv, &args) != 0)
return 1;
if (argc <= 1) {
cmdline_parser_print_help();
cerr << endl << "*** Ingen requires at least one command line parameter" << endl;
cerr << "*** Just want a graphical application? Try 'ingen -eg'" << endl;
return 1;
} else if (args.connect_given && args.engine_flag) {
cerr << "\n*** Nonsense arguments, can't both run a local engine "
<< "and connect to a remote one." << endl
<< "*** Run separate instances if that is what you want" << endl;
return 1;
}
/* Set bundle path from executable location so resources/modules can be found */
Shared::set_bundle_path_from_code((void*)&main);
SharedPtr<Glib::Module> engine_module;
SharedPtr<Glib::Module> engine_http_module;
SharedPtr<Glib::Module> engine_osc_module;
SharedPtr<Glib::Module> engine_queued_module;
SharedPtr<Glib::Module> engine_jack_module;
SharedPtr<Glib::Module> client_module;
SharedPtr<Glib::Module> gui_module;
SharedPtr<Glib::Module> bindings_module;
SharedPtr<Shared::EngineInterface> engine_interface;
Glib::thread_init();
#if HAVE_SOUP
g_type_init();
#endif
Ingen::Shared::World* world = Ingen::Shared::get_world();
/* Set up RDF world */
world->rdf_world->add_prefix("xsd", "http://www.w3.org/2001/XMLSchema#");
world->rdf_world->add_prefix("ingen", "http://drobilla.net/ns/ingen#");
world->rdf_world->add_prefix("ingenuity", "http://drobilla.net/ns/ingenuity#");
world->rdf_world->add_prefix("lv2", "http://lv2plug.in/ns/lv2core#");
world->rdf_world->add_prefix("lv2ev", "http://lv2plug.in/ns/ext/event#");
world->rdf_world->add_prefix("lv2var", "http://lv2plug.in/ns/ext/instance-var#");
world->rdf_world->add_prefix("lv2midi", "http://lv2plug.in/ns/ext/midi");
world->rdf_world->add_prefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
world->rdf_world->add_prefix("owl", "http://www.w3.org/2002/07/owl#");
world->rdf_world->add_prefix("doap", "http://usefulinc.com/ns/doap#");
world->rdf_world->add_prefix("dc", "http://purl.org/dc/elements/1.1/");
/* Run engine */
if (args.engine_flag) {
engine_module = Ingen::Shared::load_module("ingen_engine");
engine_http_module = Ingen::Shared::load_module("ingen_engine_http");
engine_osc_module = Ingen::Shared::load_module("ingen_engine_osc");
engine_jack_module = Ingen::Shared::load_module("ingen_engine_jack");
engine_queued_module = Ingen::Shared::load_module("ingen_engine_queued");
if (!engine_queued_module) {
cerr << "ERROR: Unable to load (queued) engine interface module" << endl;
Ingen::Shared::destroy_world();
return 1;
}
if (engine_module) {
Engine* (*new_engine)(Ingen::Shared::World* world) = NULL;
if (engine_module->get_symbol("new_engine", (void*&)new_engine)) {
engine = SharedPtr<Engine>(new_engine(world));
world->local_engine = engine;
/* Load queued (direct in-process) engine interface */
if (args.gui_given && engine_queued_module) {
Ingen::QueuedEngineInterface* (*new_interface)(Ingen::Engine& engine);
if (engine_queued_module->get_symbol("new_queued_interface", (void*&)new_interface)) {
SharedPtr<QueuedEngineInterface> interface(new_interface(*engine));
world->local_engine->add_event_source(interface);
engine_interface = interface;
world->engine = engine_interface;
}
} else {
#ifdef HAVE_LIBLO
if (engine_osc_module) {
Ingen::OSCEngineReceiver* (*new_receiver)(
Ingen::Engine& engine, size_t queue_size, uint16_t port);
if (engine_osc_module->get_symbol("new_osc_receiver", (void*&)new_receiver)) {
SharedPtr<EventSource> source(new_receiver(*engine,
pre_processor_queue_size, args.engine_port_arg));
world->local_engine->add_event_source(source);
}
}
#endif
#ifdef HAVE_SOUP
if (engine_http_module) {
// FIXE: leak
Ingen::HTTPEngineReceiver* (*new_receiver)(Ingen::Engine& engine, uint16_t port);
if (engine_http_module->get_symbol("new_http_receiver", (void*&)new_receiver)) {
boost::shared_ptr<HTTPEngineReceiver> receiver(new_receiver(
*world->local_engine, args.engine_port_arg));
world->local_engine->add_event_source(receiver);
receiver->activate();
}
}
#endif
}
} else {
engine_module.reset();
}
} else {
cerr << "Unable to load engine module." << endl;
}
}
/* Load client library */
if (args.load_given || args.gui_given) {
client_module = Ingen::Shared::load_module("ingen_client");
if (!client_module)
cerr << "Unable to load client module." << endl;
}
/* If we don't have a local engine interface (for GUI), use network */
if (client_module && ! engine_interface) {
SharedPtr<Shared::EngineInterface> (*new_remote_interface)(const std::string&) = NULL;
if (client_module->get_symbol("new_remote_interface", (void*&)new_remote_interface)) {
engine_interface = new_remote_interface(args.connect_arg);
} else {
cerr << "Unable to find symbol 'new_remote_interface' in "
"ingen_client module, aborting." << endl;
return -1;
}
}
/* Activate the engine, if we have one */
if (engine) {
Ingen::JackAudioDriver* (*new_driver)(
Ingen::Engine& engine,
const std::string server_name,
const std::string client_name,
void* jack_client) = NULL;
if (engine_jack_module->get_symbol("new_jack_audio_driver", (void*&)new_driver)) {
engine->set_driver(DataType::AUDIO, SharedPtr<Driver>(new_driver(
*engine, "default", args.jack_name_arg, NULL)));
} else {
cerr << Glib::Module::get_last_error() << endl;
}
engine->activate(args.parallelism_arg);
}
world->engine = engine_interface;
void (*gui_run)() = NULL;
/* Load GUI */
bool run_gui = false;
if (args.gui_given) {
gui_module = Ingen::Shared::load_module("ingen_gui");
if (gui_module) {
void (*init)(int, char**, Ingen::Shared::World*);
bool found = gui_module->get_symbol("init", (void*&)init);
found = found && gui_module->get_symbol("run", (void*&)gui_run);
if (found) {
run_gui = true;
init(argc, argv, world);
} else {
cerr << "Unable to find hooks in GUI module, GUI not loaded." << endl;
}
} else {
cerr << "Unable to load GUI module." << endl;
}
}
/* Load a patch */
if (args.load_given && engine_interface) {
boost::optional<Path> data_path = Path("/");
boost::optional<Path> parent;
boost::optional<Symbol> symbol;
if (args.path_given) {
const Glib::ustring path = args.path_arg;
if (Path::is_valid(path)) {
const Path p(path);
if (p != "/") {
parent = p.parent();
const string s = p.name();
if (Symbol::is_valid(s))
symbol = s;
}
} else {
cerr << "Invalid path given: '" << path << endl;
}
}
bool found = false;
if (!world->serialisation_module)
world->serialisation_module = Ingen::Shared::load_module("ingen_serialisation");
Serialisation::Parser* (*new_parser)() = NULL;
if (world->serialisation_module)
found = world->serialisation_module->get_symbol("new_parser", (void*&)new_parser);
if (world->serialisation_module && found) {
SharedPtr<Serialisation::Parser> parser(new_parser());
// Assumption: Containing ':' means URI, otherwise filename
string uri = args.load_arg;
if (uri.find(':') == string::npos) {
if (Glib::path_is_absolute(args.load_arg))
uri = Glib::filename_to_uri(args.load_arg);
else
uri = Glib::filename_to_uri(Glib::build_filename(
Glib::get_current_dir(), args.load_arg));
}
engine_interface->load_plugins();
parser->parse_document(world, engine_interface.get(), uri, data_path, parent, symbol);
} else {
cerr << "Unable to load serialisation module, aborting." << endl;
return -1;
}
}
/* Run GUI (if applicable) */
if (run_gui)
gui_run();
/* Run a script */
if (args.run_given) {
#ifdef WITH_BINDINGS
bool (*run_script)(Ingen::Shared::World*, const char*) = NULL;
SharedPtr<Glib::Module> bindings_module = Ingen::Shared::load_module("ingen_bindings");
if (bindings_module) {
bindings_module->make_resident();
bool found = bindings_module->get_symbol("run", (void*&)(run_script));
if (found) {
setenv("PYTHONPATH", "../../bindings", 1);
run_script(world, args.run_arg);
} else {
cerr << "FAILED: " << Glib::Module::get_last_error() << endl;
}
} else {
cerr << Glib::Module::get_last_error() << endl;
}
#else
cerr << "This build of ingen does not support scripting." << endl;
#endif
/* Listen to OSC and do our own main thing. */
} else if (engine && !run_gui) {
signal(SIGINT, catch_int);
signal(SIGTERM, catch_int);
engine->main();
}
if (engine) {
engine->deactivate();
engine.reset();
}
engine_interface.reset();
client_module.reset();
world->serialisation_module.reset();
gui_module.reset();
engine_module.reset();
Ingen::Shared::destroy_world();
return 0;
}
<|endoftext|> |
<commit_before>/* $Id$
Copyright (C) 2008 Werner Smekal
This file is part of PLplot.
PLplot is free software; you can redistribute it and/or modify
it under the terms of the GNU General Library Public License as published
by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
PLplot 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 PLplot; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* TODO:
* - text clipping
* - implement AddToClipRegion for text correctly
*/
#include "plDevs.h"
#ifdef PLD_wxwidgets
/* plplot headers */
#include "plplotP.h"
/* wxwidgets headers */
#include "wx/wx.h"
/* std and driver headers */
#include "wxwidgets.h"
/* only compile code if wxGraphicsContext available */
#if wxUSE_GRAPHICS_CONTEXT
#include "wx/graphics.h"
wxPLDevGC::wxPLDevGC( void ) : wxPLDevBase()
{
// Log_Verbose( "%s", __FUNCTION__ );
m_dc=NULL;
m_bitmap=NULL;
m_context=NULL;
m_font=NULL;
underlined=false;
}
wxPLDevGC::~wxPLDevGC()
{
// Log_Verbose( "%s", __FUNCTION__ );
if( ownGUI ) {
if( m_dc ) {
((wxMemoryDC*)m_dc)->SelectObject( wxNullBitmap );
delete m_dc;
}
if( m_bitmap )
delete m_bitmap;
}
if( m_font )
delete m_font;
}
void wxPLDevGC::DrawLine( short x1a, short y1a, short x2a, short y2a )
{
// Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1=x1a/scalex;
wxDouble y1=height-y1a/scaley;
wxDouble x2=x2a/scalex;
wxDouble y2=height-y2a/scaley;
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( x1, y1 );
path.AddLineToPoint( x2, y2 );
m_context->StrokePath( path );
AddtoClipRegion( (int)x1, (int)y1, (int)x2, (int)y2 );
}
void wxPLDevGC::DrawPolyline( short *xa, short *ya, PLINT npts )
{
// Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1a, y1a, x2a, y2a;
x1a=xa[0]/scalex;
y1a=height-ya[0]/scaley;
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( x1a, y1a );
for( PLINT i=1; i<npts; i++ ) {
x2a=xa[i]/scalex;
y2a=height-ya[i]/scaley;
path.AddLineToPoint( x2a, y2a );
x1a=x2a; y1a=y2a;
}
m_context->StrokePath( path );
wxDouble x, y, w, h;
path.GetBox( &x, &y, &w, &h );
AddtoClipRegion( (int)x, (int)y, (int)(x+w), (int)(y+h) );
}
void wxPLDevGC::ClearBackground( PLINT bgr, PLINT bgg, PLINT bgb, PLINT x1, PLINT y1, PLINT x2, PLINT y2 )
{
// Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1a, y1a, x2a, y2a;
if( x1<0 ) x1a=0; else x1a=x1/scalex;
if( y1<0 ) y1a=0; else y1a=height-y1/scaley;
if( x2<0 ) x2a=width; else x2a=x2/scalex;
if( y2<0 ) y2a=height; else y2a=height-y2/scaley;
const wxPen oldPen=m_dc->GetPen();
const wxBrush oldBrush=m_dc->GetBrush();
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(bgr, bgg, bgb), 1, wxSOLID)) );
m_context->SetBrush( wxBrush(wxColour(bgr, bgg, bgb)) );
m_context->DrawRectangle( x1a, y1a, x2a-x1a, y2a-y1a );
m_context->SetPen( oldPen );
m_context->SetBrush( oldBrush );
AddtoClipRegion( (int)x1a, (int)y1a, (int)x2a, (int)y2a );
}
void wxPLDevGC::FillPolygon( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( pls->dev_x[0]/scalex, height-pls->dev_y[0]/scaley );
for( int i=1; i < pls->dev_npts; i++ )
path.AddLineToPoint( pls->dev_x[i]/scalex, height-pls->dev_y[i]/scaley );
path.CloseSubpath();
m_context->DrawPath( path );
wxDouble x, y, w, h;
path.GetBox( &x, &y, &w, &h );
AddtoClipRegion( (int)x, (int)y, (int)(x+w), (int)(y+h) );
}
void wxPLDevGC::BlitRectangle( wxPaintDC* dc, int vX, int vY, int vW, int vH )
{
// Log_Verbose( "%s", __FUNCTION__ );
if( m_dc )
dc->Blit( vX, vY, vW, vH, m_dc, vX, vY );
}
void wxPLDevGC::CreateCanvas()
{
// Log_Verbose( "%s", __FUNCTION__ );
if( ownGUI ) {
if( !m_dc )
m_dc = new wxMemoryDC();
((wxMemoryDC*)m_dc)->SelectObject( wxNullBitmap ); /* deselect bitmap */
if( m_bitmap )
delete m_bitmap;
m_bitmap = new wxBitmap( bm_width, bm_height, 32 );
((wxMemoryDC*)m_dc)->SelectObject( *m_bitmap ); /* select new bitmap */
m_context = wxGraphicsContext::Create( *((wxMemoryDC*)m_dc) );
}
}
void wxPLDevGC::SetWidth( PLStream *pls )
{
// Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
pls->cmap0[pls->icol0].b, (unsigned char)(pls->cmap0[pls->icol0].a*255)),
pls->width>0 ? pls->width : 1, wxSOLID)) );
}
void wxPLDevGC::SetColor0( PLStream *pls )
{
// Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
pls->cmap0[pls->icol0].b, (unsigned char)(pls->cmap0[pls->icol0].a*255)),
pls->width>0 ? pls->width : 1, wxSOLID)) );
m_context->SetBrush( wxBrush(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g, pls->cmap0[pls->icol0].b,
(unsigned char)(pls->cmap0[pls->icol0].a*255))) );
}
void wxPLDevGC::SetColor1( PLStream *pls )
{
// Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->curcolor.r, pls->curcolor.g,
pls->curcolor.b, (unsigned char)(pls->curcolor.a*255)),
pls->width>0 ? pls->width : 1, wxSOLID)) );
m_context->SetBrush( wxBrush(wxColour(pls->curcolor.r, pls->curcolor.g, pls->curcolor.b,
(unsigned char)(pls->curcolor.a*255))) );
}
/*--------------------------------------------------------------------------*\
* void wx_set_dc( PLStream* pls, wxDC* dc )
*
* Adds a dc to the stream. The associated device is attached to the canvas
* as the property "dev".
\*--------------------------------------------------------------------------*/
void wxPLDevGC::SetExternalBuffer( void* dc )
{
// Log_Verbose( "%s", __FUNCTION__ );
m_dc=(wxDC*)dc; /* Add the dc to the device */
m_context = wxGraphicsContext::Create( *((wxMemoryDC*)m_dc) );
ready = true;
ownGUI = false;
}
void wxPLDevGC::PutPixel( short x, short y, PLINT color )
{
// Log_Verbose( "%s", __FUNCTION__ );
const wxPen oldpen=m_dc->GetPen();
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(GetRValue(color), GetGValue(color), GetBValue(color)),
1, wxSOLID)) );
//m_context->DrawPoint( x, y );
AddtoClipRegion( x, y, x, y );
m_context->SetPen( oldpen );
}
void wxPLDevGC::PutPixel( short x, short y )
{
// Log_Verbose( "%s", __FUNCTION__ );
//m_dc->DrawPoint( x, y );
AddtoClipRegion( x, y, x, y );
}
PLINT wxPLDevGC::GetPixel( short x, short y )
{
// Log_Verbose( "%s", __FUNCTION__ );
#ifdef __WXGTK__
// The GetPixel method is incredible slow for wxGTK. Therefore we set the colour
// always to the background color, since this is the case anyway 99% of the time.
PLINT bgr, bgg, bgb; /* red, green, blue */
plgcolbg( &bgr, &bgg, &bgb ); /* get background color information */
return RGB( bgr, bgg, bgb );
#else
wxColour col;
m_dc->GetPixel( x, y, &col );
return RGB( col.Red(), col.Green(), col.Blue());
#endif
}
void wxPLDevGC::PSDrawTextToDC( char* utf8_string, bool drawText )
{
// Log_Verbose( "%s", __FUNCTION__ );
wxDouble w, h, d, l;
wxString str(wxConvUTF8.cMB2WC(utf8_string), *wxConvCurrent);
m_context->GetTextExtent( str, &w, &h, &d, &l );
if( drawText ) {
m_context->DrawText( str, 0, -yOffset/scaley );
m_context->Translate( w, 0 );
}
textWidth += w;
textHeight = textHeight>(h+yOffset/scaley) ? textHeight : (h+yOffset/scaley);
memset( utf8_string, '\0', max_string_length );
}
void wxPLDevGC::PSSetFont( PLUNICODE fci )
{
// Log_Verbose( "%s", __FUNCTION__ );
unsigned char fontFamily, fontStyle, fontWeight;
plP_fci2hex( fci, &fontFamily, PL_FCI_FAMILY );
plP_fci2hex( fci, &fontStyle, PL_FCI_STYLE );
plP_fci2hex( fci, &fontWeight, PL_FCI_WEIGHT );
if( m_font )
delete m_font;
m_font=wxFont::New(fontSize*fontScale, fontFamilyLookup[fontFamily],
fontStyleLookup[fontStyle] & fontWeightLookup[fontWeight] );
m_font->SetUnderlined( underlined );
m_context->SetFont( *m_font, wxColour(textRed, textGreen, textBlue) );
}
void wxPLDevGC::ProcessString( PLStream* pls, EscText* args )
{
// Log_Verbose( "%s", __FUNCTION__ );
/* Check that we got unicode, warning message and return if not */
if( args->unicode_array_len == 0 ) {
printf( "Non unicode string passed to a cairo driver, ignoring\n" );
return;
}
/* Check that unicode string isn't longer then the max we allow */
if( args->unicode_array_len >= 500 ) {
printf( "Sorry, the wxWidgets drivers only handles strings of length < %d\n", 500 );
return;
}
/* Calculate the font size (in pixels) */
fontSize = pls->chrht * VIRTUAL_PIXELS_PER_MM/scaley * 1.3;
/* text color */
textRed=pls->cmap0[pls->icol0].r;
textGreen=pls->cmap0[pls->icol0].g;
textBlue=pls->cmap0[pls->icol0].b;
/* calculate rotation of text */
plRotationShear( args->xform, &rotation, &shear );
rotation -= pls->diorot * M_PI / 2.0;
cos_rot = cos( rotation );
sin_rot = sin( rotation );
cos_shear = cos(shear);
sin_shear = sin(shear);
/* determine extend of text */
PSDrawText( args->unicode_array, args->unicode_array_len, false );
/* actually draw text */
m_context->PushState();
wxGraphicsMatrix matrix=m_context->CreateMatrix( cos_rot, -sin_rot,
cos_rot * sin_shear + sin_rot * cos_shear,
-sin_rot * sin_shear + cos_rot * cos_shear,
args->x/scalex-args->just*textWidth,
height-args->y/scaley-0.5*textHeight );
m_context->SetTransform( matrix );
PSDrawText( args->unicode_array, args->unicode_array_len, true );
m_context->PopState();
AddtoClipRegion( 0, 0, width, height );
}
#endif
#endif /* PLD_wxwidgets */
<commit_msg>Fixed bug - context was not refreshed for resize event for external dc.<commit_after>/* $Id$
Copyright (C) 2008 Werner Smekal
This file is part of PLplot.
PLplot is free software; you can redistribute it and/or modify
it under the terms of the GNU General Library Public License as published
by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
PLplot 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 PLplot; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* TODO:
* - text clipping
* - implement AddToClipRegion for text correctly
*/
#include "plDevs.h"
#ifdef PLD_wxwidgets
/* plplot headers */
#include "plplotP.h"
/* wxwidgets headers */
#include "wx/wx.h"
/* std and driver headers */
#include "wxwidgets.h"
/* only compile code if wxGraphicsContext available */
#if wxUSE_GRAPHICS_CONTEXT
#include "wx/graphics.h"
wxPLDevGC::wxPLDevGC( void ) : wxPLDevBase()
{
// Log_Verbose( "%s", __FUNCTION__ );
m_dc=NULL;
m_bitmap=NULL;
m_context=NULL;
m_font=NULL;
underlined=false;
}
wxPLDevGC::~wxPLDevGC()
{
// Log_Verbose( "%s", __FUNCTION__ );
if( ownGUI ) {
if( m_dc ) {
((wxMemoryDC*)m_dc)->SelectObject( wxNullBitmap );
delete m_dc;
}
if( m_bitmap )
delete m_bitmap;
}
if( m_font )
delete m_font;
}
void wxPLDevGC::DrawLine( short x1a, short y1a, short x2a, short y2a )
{
// Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1=x1a/scalex;
wxDouble y1=height-y1a/scaley;
wxDouble x2=x2a/scalex;
wxDouble y2=height-y2a/scaley;
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( x1, y1 );
path.AddLineToPoint( x2, y2 );
m_context->StrokePath( path );
AddtoClipRegion( (int)x1, (int)y1, (int)x2, (int)y2 );
}
void wxPLDevGC::DrawPolyline( short *xa, short *ya, PLINT npts )
{
// Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1a, y1a, x2a, y2a;
x1a=xa[0]/scalex;
y1a=height-ya[0]/scaley;
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( x1a, y1a );
for( PLINT i=1; i<npts; i++ ) {
x2a=xa[i]/scalex;
y2a=height-ya[i]/scaley;
path.AddLineToPoint( x2a, y2a );
x1a=x2a; y1a=y2a;
}
m_context->StrokePath( path );
wxDouble x, y, w, h;
path.GetBox( &x, &y, &w, &h );
AddtoClipRegion( (int)x, (int)y, (int)(x+w), (int)(y+h) );
}
void wxPLDevGC::ClearBackground( PLINT bgr, PLINT bgg, PLINT bgb, PLINT x1, PLINT y1, PLINT x2, PLINT y2 )
{
// Log_Verbose( "%s", __FUNCTION__ );
wxDouble x1a, y1a, x2a, y2a;
if( x1<0 ) x1a=0; else x1a=x1/scalex;
if( y1<0 ) y1a=0; else y1a=height-y1/scaley;
if( x2<0 ) x2a=width; else x2a=x2/scalex;
if( y2<0 ) y2a=height; else y2a=height-y2/scaley;
const wxPen oldPen=m_dc->GetPen();
const wxBrush oldBrush=m_dc->GetBrush();
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(bgr, bgg, bgb), 1, wxSOLID)) );
m_context->SetBrush( wxBrush(wxColour(bgr, bgg, bgb)) );
m_context->DrawRectangle( x1a, y1a, x2a-x1a, y2a-y1a );
m_context->SetPen( oldPen );
m_context->SetBrush( oldBrush );
AddtoClipRegion( (int)x1a, (int)y1a, (int)x2a, (int)y2a );
}
void wxPLDevGC::FillPolygon( PLStream *pls )
{
Log_Verbose( "%s", __FUNCTION__ );
wxGraphicsPath path=m_context->CreatePath();
path.MoveToPoint( pls->dev_x[0]/scalex, height-pls->dev_y[0]/scaley );
for( int i=1; i < pls->dev_npts; i++ )
path.AddLineToPoint( pls->dev_x[i]/scalex, height-pls->dev_y[i]/scaley );
path.CloseSubpath();
m_context->DrawPath( path );
wxDouble x, y, w, h;
path.GetBox( &x, &y, &w, &h );
AddtoClipRegion( (int)x, (int)y, (int)(x+w), (int)(y+h) );
}
void wxPLDevGC::BlitRectangle( wxPaintDC* dc, int vX, int vY, int vW, int vH )
{
// Log_Verbose( "%s", __FUNCTION__ );
if( m_dc )
dc->Blit( vX, vY, vW, vH, m_dc, vX, vY );
}
void wxPLDevGC::CreateCanvas()
{
// Log_Verbose( "%s", __FUNCTION__ );
if( ownGUI ) {
if( !m_dc )
m_dc = new wxMemoryDC();
((wxMemoryDC*)m_dc)->SelectObject( wxNullBitmap ); /* deselect bitmap */
if( m_bitmap )
delete m_bitmap;
m_bitmap = new wxBitmap( bm_width, bm_height, 32 );
((wxMemoryDC*)m_dc)->SelectObject( *m_bitmap ); /* select new bitmap */
}
if( m_dc )
m_context = wxGraphicsContext::Create( *((wxMemoryDC*)m_dc) );
}
void wxPLDevGC::SetWidth( PLStream *pls )
{
// Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
pls->cmap0[pls->icol0].b, (unsigned char)(pls->cmap0[pls->icol0].a*255)),
pls->width>0 ? pls->width : 1, wxSOLID)) );
}
void wxPLDevGC::SetColor0( PLStream *pls )
{
// Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g,
pls->cmap0[pls->icol0].b, (unsigned char)(pls->cmap0[pls->icol0].a*255)),
pls->width>0 ? pls->width : 1, wxSOLID)) );
m_context->SetBrush( wxBrush(wxColour(pls->cmap0[pls->icol0].r, pls->cmap0[pls->icol0].g, pls->cmap0[pls->icol0].b,
(unsigned char)(pls->cmap0[pls->icol0].a*255))) );
}
void wxPLDevGC::SetColor1( PLStream *pls )
{
// Log_Verbose( "%s", __FUNCTION__ );
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(pls->curcolor.r, pls->curcolor.g,
pls->curcolor.b, (unsigned char)(pls->curcolor.a*255)),
pls->width>0 ? pls->width : 1, wxSOLID)) );
m_context->SetBrush( wxBrush(wxColour(pls->curcolor.r, pls->curcolor.g, pls->curcolor.b,
(unsigned char)(pls->curcolor.a*255))) );
}
/*--------------------------------------------------------------------------*\
* void wx_set_dc( PLStream* pls, wxDC* dc )
*
* Adds a dc to the stream. The associated device is attached to the canvas
* as the property "dev".
\*--------------------------------------------------------------------------*/
void wxPLDevGC::SetExternalBuffer( void* dc )
{
// Log_Verbose( "%s", __FUNCTION__ );
m_dc=(wxDC*)dc; /* Add the dc to the device */
m_context = wxGraphicsContext::Create( *((wxMemoryDC*)m_dc) );
ready = true;
ownGUI = false;
}
void wxPLDevGC::PutPixel( short x, short y, PLINT color )
{
// Log_Verbose( "%s", __FUNCTION__ );
const wxPen oldpen=m_dc->GetPen();
m_context->SetPen( *(wxThePenList->FindOrCreatePen(wxColour(GetRValue(color), GetGValue(color), GetBValue(color)),
1, wxSOLID)) );
//m_context->DrawPoint( x, y );
AddtoClipRegion( x, y, x, y );
m_context->SetPen( oldpen );
}
void wxPLDevGC::PutPixel( short x, short y )
{
// Log_Verbose( "%s", __FUNCTION__ );
//m_dc->DrawPoint( x, y );
AddtoClipRegion( x, y, x, y );
}
PLINT wxPLDevGC::GetPixel( short x, short y )
{
// Log_Verbose( "%s", __FUNCTION__ );
#ifdef __WXGTK__
// The GetPixel method is incredible slow for wxGTK. Therefore we set the colour
// always to the background color, since this is the case anyway 99% of the time.
PLINT bgr, bgg, bgb; /* red, green, blue */
plgcolbg( &bgr, &bgg, &bgb ); /* get background color information */
return RGB( bgr, bgg, bgb );
#else
wxColour col;
m_dc->GetPixel( x, y, &col );
return RGB( col.Red(), col.Green(), col.Blue());
#endif
}
void wxPLDevGC::PSDrawTextToDC( char* utf8_string, bool drawText )
{
// Log_Verbose( "%s", __FUNCTION__ );
wxDouble w, h, d, l;
wxString str(wxConvUTF8.cMB2WC(utf8_string), *wxConvCurrent);
m_context->GetTextExtent( str, &w, &h, &d, &l );
if( drawText ) {
m_context->DrawText( str, 0, -yOffset/scaley );
m_context->Translate( w, 0 );
}
textWidth += w;
textHeight = textHeight>(h+yOffset/scaley) ? textHeight : (h+yOffset/scaley);
memset( utf8_string, '\0', max_string_length );
}
void wxPLDevGC::PSSetFont( PLUNICODE fci )
{
// Log_Verbose( "%s", __FUNCTION__ );
unsigned char fontFamily, fontStyle, fontWeight;
plP_fci2hex( fci, &fontFamily, PL_FCI_FAMILY );
plP_fci2hex( fci, &fontStyle, PL_FCI_STYLE );
plP_fci2hex( fci, &fontWeight, PL_FCI_WEIGHT );
if( m_font )
delete m_font;
m_font=wxFont::New(fontSize*fontScale, fontFamilyLookup[fontFamily],
fontStyleLookup[fontStyle] & fontWeightLookup[fontWeight] );
m_font->SetUnderlined( underlined );
m_context->SetFont( *m_font, wxColour(textRed, textGreen, textBlue) );
}
void wxPLDevGC::ProcessString( PLStream* pls, EscText* args )
{
// Log_Verbose( "%s", __FUNCTION__ );
/* Check that we got unicode, warning message and return if not */
if( args->unicode_array_len == 0 ) {
printf( "Non unicode string passed to a cairo driver, ignoring\n" );
return;
}
/* Check that unicode string isn't longer then the max we allow */
if( args->unicode_array_len >= 500 ) {
printf( "Sorry, the wxWidgets drivers only handles strings of length < %d\n", 500 );
return;
}
/* Calculate the font size (in pixels) */
fontSize = pls->chrht * VIRTUAL_PIXELS_PER_MM/scaley * 1.3;
/* text color */
textRed=pls->cmap0[pls->icol0].r;
textGreen=pls->cmap0[pls->icol0].g;
textBlue=pls->cmap0[pls->icol0].b;
/* calculate rotation of text */
plRotationShear( args->xform, &rotation, &shear );
rotation -= pls->diorot * M_PI / 2.0;
cos_rot = cos( rotation );
sin_rot = sin( rotation );
cos_shear = cos(shear);
sin_shear = sin(shear);
/* determine extend of text */
PSDrawText( args->unicode_array, args->unicode_array_len, false );
/* actually draw text */
m_context->PushState();
wxGraphicsMatrix matrix=m_context->CreateMatrix( cos_rot, -sin_rot,
cos_rot * sin_shear + sin_rot * cos_shear,
-sin_rot * sin_shear + cos_rot * cos_shear,
args->x/scalex-args->just*textWidth,
height-args->y/scaley-0.5*textHeight );
m_context->SetTransform( matrix );
PSDrawText( args->unicode_array, args->unicode_array_len, true );
m_context->PopState();
AddtoClipRegion( 0, 0, width, height );
}
#endif
#endif /* PLD_wxwidgets */
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: vi.cpp
// Purpose: Implementation of class wxExSTC vi mode
// Author: Anton van Wezenbeek
// Created: 2009-11-21
// RCS-ID: $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/textdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/vi.h>
#include <wx/extension/stc.h>
#if wxUSE_GUI
wxExVi::wxExVi(wxExSTC* stc)
: m_STC(stc)
, m_InsertMode(false)
, m_SearchText(stc->GetSearchText())
{
}
void wxExVi::Delete(
const wxString& begin_address,
const wxString& end_address) const
{
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->Cut();
}
void wxExVi::DoCommand(const wxString& command) const
{
// [address] m destination
// [address] s [/pattern/replacement/] [options] [count]
wxStringTokenizer tkz(command, "dmsy");
const wxString address = tkz.GetNextToken();
const wxChar cmd = tkz.GetLastDelimiter();
wxString begin_address;
wxString end_address;
if (address == ".")
{
begin_address = address;
end_address = address;
}
else if (address == "%")
{
begin_address = "1";
end_address = "$";
}
else
{
begin_address = address.BeforeFirst(',');
end_address = address.AfterFirst(',');
}
switch (cmd)
{
case 'd':
Delete(begin_address, end_address);
break;
case 'm':
Move(begin_address, end_address, tkz.GetString());
break;
case 's':
{
wxStringTokenizer tkz(tkz.GetString(), "/");
tkz.GetNextToken(); // skip empty token
const wxString pattern = tkz.GetNextToken();
const wxString replacement = tkz.GetNextToken();
Substitute(begin_address, end_address, pattern, replacement);
}
break;
case 'y':
Yank(begin_address, end_address);
break;
}
}
void wxExVi::InsertMode()
{
m_InsertMode = true;
m_InsertText.clear();
}
void wxExVi::LineEditor(const wxString& command)
{
if (command.empty())
{
// Do nothing.
}
else if (command == "$")
{
m_STC->DocumentEnd();
}
else if (command == ".=")
{
m_STC->CallTipShow(
m_STC->GetCurrentPos(),
wxString::Format("%d", m_STC->GetCurrentLine() + 1));
}
else if (command.IsNumber())
{
m_STC->GotoLine(atoi(command.c_str()) - 1);
}
else if (command == "w")
{
m_STC->FileSave();
}
else if (command == "x")
{
if (m_STC->GetContentsChanged())
{
m_STC->FileSave();
}
wxCloseEvent event(wxEVT_CLOSE_WINDOW);
wxPostEvent(wxTheApp->GetTopWindow(), event);
}
else if (command == "q")
{
wxCloseEvent event(wxEVT_CLOSE_WINDOW);
wxPostEvent(wxTheApp->GetTopWindow(), event);
}
else if (command == "q!")
{
wxCloseEvent event(wxEVT_CLOSE_WINDOW);
event.SetCanVeto(false);
wxPostEvent(wxTheApp->GetTopWindow(), event);
}
else
{
m_LastCommand = command;
m_InsertText.clear();
DoCommand(command);
}
}
void wxExVi::Move(
const wxString& begin_address,
const wxString& end_address,
const wxString& destination) const
{
const int dest_line = ToLineNumber(destination);
if (dest_line == 0)
{
return;
}
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->BeginUndoAction();
m_STC->Cut();
m_STC->GotoLine(dest_line - 1);
m_STC->Paste();
m_STC->EndUndoAction();
}
bool wxExVi::OnKey(wxKeyEvent& event)
{
if (m_InsertMode)
{
if (event.GetKeyCode() == WXK_ESCAPE)
{
m_InsertMode = false;
}
if (wxIsalnum(event.GetKeyCode()))
{
m_InsertText +=
(!event.ShiftDown() ? wxTolower(event.GetUnicodeKey()): event.GetUnicodeKey());
}
return true;
}
if(
!event.ShiftDown() &&
!event.ControlDown())
{
m_Command += event.GetUnicodeKey();
}
int repeat = atoi(m_Command.c_str());
if (repeat == 0)
{
repeat++;
}
bool handled_command = true;
// Handle multichar commands.
if (m_Command.EndsWith("CW"))
{
for (int i = 0; i < repeat; i++) m_STC->WordRightExtend();
InsertMode();
}
else if (m_Command.EndsWith("DD"))
{
const int line = m_STC->LineFromPosition(m_STC->GetCurrentPos());
const int start = m_STC->PositionFromLine(line);
const int end = m_STC->PositionFromLine(line + repeat);
m_STC->SetSelectionStart(start);
m_STC->SetSelectionEnd(end);
m_STC->Cut();
}
else if (m_Command.EndsWith("DW"))
{
m_STC->BeginUndoAction();
for (int i = 0; i < repeat; i++) m_STC->DelWordRight();
m_STC->EndUndoAction();
}
else if (m_Command.Matches("*F?"))
{
for (int i = 0; i < repeat; i++) m_STC->FindNext(m_Command.Last(), wxSTC_FIND_REGEXP);
}
else if (m_Command.EndsWith("YY"))
{
const int line = m_STC->LineFromPosition(m_STC->GetCurrentPos());
const int start = m_STC->PositionFromLine(line);
const int end = m_STC->PositionFromLine(line + repeat);
m_STC->CopyRange(start, end);
}
else
{
if (!event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case '0':
if (m_Command.length() == 1)
{
m_STC->Home();
}
else
{
handled_command = false;
}
break;
case 'A': InsertMode(); m_STC->CharRight(); break;
case 'B': for (int i = 0; i < repeat; i++) m_STC->WordLeft(); break;
case 'G': m_STC->DocumentStart(); break;
case 'H':
case WXK_LEFT:
for (int i = 0; i < repeat; i++) m_STC->CharLeft();
break;
case 'I': InsertMode(); break;
case 'J':
case WXK_DOWN:
for (int i = 0; i < repeat; i++) m_STC->LineDown();
break;
case 'K':
case WXK_UP:
for (int i = 0; i < repeat; i++) m_STC->LineUp();
break;
case 'L':
case ' ':
case WXK_RIGHT:
for (int i = 0; i < repeat; i++) m_STC->CharRight();
break;
case 'N':
for (int i = 0; i < repeat; i++)
m_STC->FindNext(m_SearchText, wxSTC_FIND_REGEXP);
break;
case 'P':
{
const int pos = m_STC->GetCurrentPos();
m_STC->LineDown();
m_STC->Home();
m_STC->Paste();
m_STC->GotoPos(pos);
}
break;
case 'W': for (int i = 0; i < repeat; i++) m_STC->WordRight(); break;
case 'U': m_STC->Undo(); break;
case 'X': m_STC->DeleteBack(); break;
case '/':
{
wxTextEntryDialog dlg(
m_STC,
"/",
"vi",
m_SearchText);
if (dlg.ShowModal() == wxID_OK)
{
m_SearchText = dlg.GetValue();
m_STC->FindNext(m_SearchText, wxSTC_FIND_REGEXP);
}
}
break;
// Repeat last text changing command.
case '.':
if (!m_InsertText.empty())
{
m_STC->AddText(m_InsertText);
}
else
{
DoCommand(m_LastCommand);
}
break;
case '[':
case ']':
{
const int brace_match = m_STC->BraceMatch(m_STC->GetCurrentPos());
if (brace_match != wxSTC_INVALID_POSITION)
{
m_STC->GotoPos(brace_match);
}
}
break;
case WXK_RETURN:
m_STC->LineDown();
break;
default:
handled_command = false;
}
}
else if (event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'A': InsertMode(); m_STC->LineEnd(); break;
case 'D': m_STC->DelLineRight(); break;
case 'G':
if (repeat > 1)
{
m_STC->GotoLine(repeat - 1);
}
else
{
m_STC->DocumentEnd();
}
break;
case 'N':
for (int i = 0; i < repeat; i++)
m_STC->FindNext(m_SearchText, wxSTC_FIND_REGEXP, false);
break;
case 'P':
{
m_STC->LineUp();
m_STC->Home();
m_STC->Paste();
}
break;
// Reverse case current char.
case '1': // TODO: Should be ~, that does not work
{
wxString text(m_STC->GetTextRange(
m_STC->GetCurrentPos(),
m_STC->GetCurrentPos() + 1));
wxIslower(text[0]) ? text.UpperCase(): text.LowerCase();
m_STC->wxStyledTextCtrl::Replace(
m_STC->GetCurrentPos(),
m_STC->GetCurrentPos() + 1,
text);
m_STC->CharRight();
}
break;
case '4': m_STC->LineEnd(); break; // $
case '[': m_STC->ParaUp(); break; // {
case ']': m_STC->ParaDown(); break; // }
case ';': // :
{
wxTextEntryDialog dlg(m_STC, ":", "vi");
if (dlg.ShowModal() == wxID_OK)
{
LineEditor(dlg.GetValue());
}
}
break;
case '/':
{
wxTextEntryDialog dlg(
m_STC,
"?",
"vi",
m_SearchText);
if (dlg.ShowModal() == wxID_OK)
{
m_SearchText = dlg.GetValue();
m_STC->FindNext(m_SearchText, wxSTC_FIND_REGEXP, false);
}
}
break;
default:
handled_command = false;
}
}
else if (event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'B': for (int i = 0; i < repeat; i++) m_STC->PageUp(); break;
case 'E': for (int i = 0; i < repeat; i++) m_STC->LineScrollUp(); break;
case 'F': for (int i = 0; i < repeat; i++) m_STC->PageDown(); break;
case 'Y': for (int i = 0; i < repeat; i++) m_STC->LineScrollDown(); break;
default:
handled_command = false;
}
}
else
{
wxFAIL;
}
}
if (handled_command)
{
m_Command.clear();
}
return false;
}
bool wxExVi::SetSelection(
const wxString& begin_address,
const wxString& end_address) const
{
const int begin_line = ToLineNumber(begin_address);
const int end_line = ToLineNumber(end_address);
if (begin_line == 0 || end_line == 0)
{
return false;
}
m_STC->SetSelectionStart(m_STC->PositionFromLine(begin_line - 1));
m_STC->SetSelectionEnd(m_STC->PositionFromLine(end_line));
return true;
}
void wxExVi::Substitute(
const wxString& begin_address,
const wxString& end_address,
const wxString& pattern,
const wxString& replacement) const
{
m_STC->SetSearchFlags(wxSTC_FIND_REGEXP);
const int begin_line = ToLineNumber(begin_address);
const int end_line = ToLineNumber(end_address);
if (begin_line == 0 || end_line == 0)
{
return;
}
m_STC->BeginUndoAction();
m_STC->SetTargetStart(m_STC->PositionFromLine(begin_line - 1));
m_STC->SetTargetEnd(m_STC->PositionFromLine(end_line));
while (m_STC->SearchInTarget(pattern) > 0)
{
const int start = m_STC->GetTargetStart();
const int length = m_STC->ReplaceTarget(replacement);
m_STC->SetTargetStart(start + length);
m_STC->SetTargetEnd(m_STC->PositionFromLine(end_line));
}
m_STC->EndUndoAction();
}
int wxExVi::ToLineNumber(const wxString& address) const
{
if (address == "$")
{
return m_STC->GetLineCount() + 1;
}
wxString filtered_address(address);
int dot = 0;
if (filtered_address.Contains("."))
{
dot = m_STC->GetCurrentLine() + 1;
filtered_address.Replace(".", "");
if (!filtered_address.IsNumber()) return 0;
}
const int line_no = dot + atoi(filtered_address.c_str());
if (line_no < 0)
{
return 1;
}
else if (line_no > m_STC->GetLineCount())
{
return m_STC->GetLineCount() + 1;
}
else
{
return line_no;
}
}
void wxExVi::Yank(
const wxString& begin_address,
const wxString& end_address) const
{
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->Copy();
}
#endif // wxUSE_GUI
<commit_msg>more general implementation of command .=<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: vi.cpp
// Purpose: Implementation of class wxExSTC vi mode
// Author: Anton van Wezenbeek
// Created: 2009-11-21
// RCS-ID: $Id$
// Copyright: (c) 2009 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/textdlg.h>
#include <wx/tokenzr.h>
#include <wx/extension/vi.h>
#include <wx/extension/stc.h>
#if wxUSE_GUI
wxExVi::wxExVi(wxExSTC* stc)
: m_STC(stc)
, m_InsertMode(false)
, m_SearchText(stc->GetSearchText())
{
}
void wxExVi::Delete(
const wxString& begin_address,
const wxString& end_address) const
{
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->Cut();
}
void wxExVi::DoCommand(const wxString& command) const
{
// [address] m destination
// [address] s [/pattern/replacement/] [options] [count]
wxStringTokenizer tkz(command, "dmsy");
const wxString address = tkz.GetNextToken();
const wxChar cmd = tkz.GetLastDelimiter();
wxString begin_address;
wxString end_address;
if (address == ".")
{
begin_address = address;
end_address = address;
}
else if (address == "%")
{
begin_address = "1";
end_address = "$";
}
else
{
begin_address = address.BeforeFirst(',');
end_address = address.AfterFirst(',');
}
switch (cmd)
{
case 'd':
Delete(begin_address, end_address);
break;
case 'm':
Move(begin_address, end_address, tkz.GetString());
break;
case 's':
{
wxStringTokenizer tkz(tkz.GetString(), "/");
tkz.GetNextToken(); // skip empty token
const wxString pattern = tkz.GetNextToken();
const wxString replacement = tkz.GetNextToken();
Substitute(begin_address, end_address, pattern, replacement);
}
break;
case 'y':
Yank(begin_address, end_address);
break;
}
}
void wxExVi::InsertMode()
{
m_InsertMode = true;
m_InsertText.clear();
}
void wxExVi::LineEditor(const wxString& command)
{
if (command.empty())
{
// Do nothing.
}
else if (command == "$")
{
m_STC->DocumentEnd();
}
else if (command.Last() == '=')
{
m_STC->CallTipShow(
m_STC->GetCurrentPos(),
wxString::Format("%d", ToLineNumber(command.BeforeLast('='))));
}
else if (command.IsNumber())
{
m_STC->GotoLine(atoi(command.c_str()) - 1);
}
else if (command == "w")
{
m_STC->FileSave();
}
else if (command == "x")
{
if (m_STC->GetContentsChanged())
{
m_STC->FileSave();
}
wxCloseEvent event(wxEVT_CLOSE_WINDOW);
wxPostEvent(wxTheApp->GetTopWindow(), event);
}
else if (command == "q")
{
wxCloseEvent event(wxEVT_CLOSE_WINDOW);
wxPostEvent(wxTheApp->GetTopWindow(), event);
}
else if (command == "q!")
{
wxCloseEvent event(wxEVT_CLOSE_WINDOW);
event.SetCanVeto(false);
wxPostEvent(wxTheApp->GetTopWindow(), event);
}
else
{
m_LastCommand = command;
m_InsertText.clear();
DoCommand(command);
}
}
void wxExVi::Move(
const wxString& begin_address,
const wxString& end_address,
const wxString& destination) const
{
const int dest_line = ToLineNumber(destination);
if (dest_line == 0)
{
return;
}
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->BeginUndoAction();
m_STC->Cut();
m_STC->GotoLine(dest_line - 1);
m_STC->Paste();
m_STC->EndUndoAction();
}
bool wxExVi::OnKey(wxKeyEvent& event)
{
if (m_InsertMode)
{
if (event.GetKeyCode() == WXK_ESCAPE)
{
m_InsertMode = false;
}
if (wxIsalnum(event.GetKeyCode()))
{
m_InsertText +=
(!event.ShiftDown() ? wxTolower(event.GetUnicodeKey()): event.GetUnicodeKey());
}
return true;
}
if(
!event.ShiftDown() &&
!event.ControlDown())
{
m_Command += event.GetUnicodeKey();
}
int repeat = atoi(m_Command.c_str());
if (repeat == 0)
{
repeat++;
}
bool handled_command = true;
// Handle multichar commands.
if (m_Command.EndsWith("CW"))
{
for (int i = 0; i < repeat; i++) m_STC->WordRightExtend();
InsertMode();
}
else if (m_Command.EndsWith("DD"))
{
const int line = m_STC->LineFromPosition(m_STC->GetCurrentPos());
const int start = m_STC->PositionFromLine(line);
const int end = m_STC->PositionFromLine(line + repeat);
m_STC->SetSelectionStart(start);
m_STC->SetSelectionEnd(end);
m_STC->Cut();
}
else if (m_Command.EndsWith("DW"))
{
m_STC->BeginUndoAction();
for (int i = 0; i < repeat; i++) m_STC->DelWordRight();
m_STC->EndUndoAction();
}
else if (m_Command.Matches("*F?"))
{
for (int i = 0; i < repeat; i++) m_STC->FindNext(m_Command.Last(), wxSTC_FIND_REGEXP);
}
else if (m_Command.EndsWith("YY"))
{
const int line = m_STC->LineFromPosition(m_STC->GetCurrentPos());
const int start = m_STC->PositionFromLine(line);
const int end = m_STC->PositionFromLine(line + repeat);
m_STC->CopyRange(start, end);
}
else
{
if (!event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case '0':
if (m_Command.length() == 1)
{
m_STC->Home();
}
else
{
handled_command = false;
}
break;
case 'A': InsertMode(); m_STC->CharRight(); break;
case 'B': for (int i = 0; i < repeat; i++) m_STC->WordLeft(); break;
case 'G': m_STC->DocumentStart(); break;
case 'H':
case WXK_LEFT:
for (int i = 0; i < repeat; i++) m_STC->CharLeft();
break;
case 'I': InsertMode(); break;
case 'J':
case WXK_DOWN:
for (int i = 0; i < repeat; i++) m_STC->LineDown();
break;
case 'K':
case WXK_UP:
for (int i = 0; i < repeat; i++) m_STC->LineUp();
break;
case 'L':
case ' ':
case WXK_RIGHT:
for (int i = 0; i < repeat; i++) m_STC->CharRight();
break;
case 'N':
for (int i = 0; i < repeat; i++)
m_STC->FindNext(m_SearchText, wxSTC_FIND_REGEXP);
break;
case 'P':
{
const int pos = m_STC->GetCurrentPos();
m_STC->LineDown();
m_STC->Home();
m_STC->Paste();
m_STC->GotoPos(pos);
}
break;
case 'W': for (int i = 0; i < repeat; i++) m_STC->WordRight(); break;
case 'U': m_STC->Undo(); break;
case 'X': m_STC->DeleteBack(); break;
case '/':
{
wxTextEntryDialog dlg(
m_STC,
"/",
"vi",
m_SearchText);
if (dlg.ShowModal() == wxID_OK)
{
m_SearchText = dlg.GetValue();
m_STC->FindNext(m_SearchText, wxSTC_FIND_REGEXP);
}
}
break;
// Repeat last text changing command.
case '.':
if (!m_InsertText.empty())
{
m_STC->AddText(m_InsertText);
}
else
{
DoCommand(m_LastCommand);
}
break;
case '[':
case ']':
{
const int brace_match = m_STC->BraceMatch(m_STC->GetCurrentPos());
if (brace_match != wxSTC_INVALID_POSITION)
{
m_STC->GotoPos(brace_match);
}
}
break;
case WXK_RETURN:
m_STC->LineDown();
break;
default:
handled_command = false;
}
}
else if (event.ShiftDown() && !event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'A': InsertMode(); m_STC->LineEnd(); break;
case 'D': m_STC->DelLineRight(); break;
case 'G':
if (repeat > 1)
{
m_STC->GotoLine(repeat - 1);
}
else
{
m_STC->DocumentEnd();
}
break;
case 'N':
for (int i = 0; i < repeat; i++)
m_STC->FindNext(m_SearchText, wxSTC_FIND_REGEXP, false);
break;
case 'P':
{
m_STC->LineUp();
m_STC->Home();
m_STC->Paste();
}
break;
// Reverse case current char.
case '1': // TODO: Should be ~, that does not work
{
wxString text(m_STC->GetTextRange(
m_STC->GetCurrentPos(),
m_STC->GetCurrentPos() + 1));
wxIslower(text[0]) ? text.UpperCase(): text.LowerCase();
m_STC->wxStyledTextCtrl::Replace(
m_STC->GetCurrentPos(),
m_STC->GetCurrentPos() + 1,
text);
m_STC->CharRight();
}
break;
case '4': m_STC->LineEnd(); break; // $
case '[': m_STC->ParaUp(); break; // {
case ']': m_STC->ParaDown(); break; // }
case ';': // :
{
wxTextEntryDialog dlg(m_STC, ":", "vi");
if (dlg.ShowModal() == wxID_OK)
{
LineEditor(dlg.GetValue());
}
}
break;
case '/':
{
wxTextEntryDialog dlg(
m_STC,
"?",
"vi",
m_SearchText);
if (dlg.ShowModal() == wxID_OK)
{
m_SearchText = dlg.GetValue();
m_STC->FindNext(m_SearchText, wxSTC_FIND_REGEXP, false);
}
}
break;
default:
handled_command = false;
}
}
else if (event.ControlDown())
{
switch (event.GetKeyCode())
{
case 'B': for (int i = 0; i < repeat; i++) m_STC->PageUp(); break;
case 'E': for (int i = 0; i < repeat; i++) m_STC->LineScrollUp(); break;
case 'F': for (int i = 0; i < repeat; i++) m_STC->PageDown(); break;
case 'Y': for (int i = 0; i < repeat; i++) m_STC->LineScrollDown(); break;
default:
handled_command = false;
}
}
else
{
wxFAIL;
}
}
if (handled_command)
{
m_Command.clear();
}
return false;
}
bool wxExVi::SetSelection(
const wxString& begin_address,
const wxString& end_address) const
{
const int begin_line = ToLineNumber(begin_address);
const int end_line = ToLineNumber(end_address);
if (begin_line == 0 || end_line == 0)
{
return false;
}
m_STC->SetSelectionStart(m_STC->PositionFromLine(begin_line - 1));
m_STC->SetSelectionEnd(m_STC->PositionFromLine(end_line));
return true;
}
void wxExVi::Substitute(
const wxString& begin_address,
const wxString& end_address,
const wxString& pattern,
const wxString& replacement) const
{
m_STC->SetSearchFlags(wxSTC_FIND_REGEXP);
const int begin_line = ToLineNumber(begin_address);
const int end_line = ToLineNumber(end_address);
if (begin_line == 0 || end_line == 0)
{
return;
}
m_STC->BeginUndoAction();
m_STC->SetTargetStart(m_STC->PositionFromLine(begin_line - 1));
m_STC->SetTargetEnd(m_STC->PositionFromLine(end_line));
while (m_STC->SearchInTarget(pattern) > 0)
{
const int start = m_STC->GetTargetStart();
const int length = m_STC->ReplaceTarget(replacement);
m_STC->SetTargetStart(start + length);
m_STC->SetTargetEnd(m_STC->PositionFromLine(end_line));
}
m_STC->EndUndoAction();
}
int wxExVi::ToLineNumber(const wxString& address) const
{
if (address == "$")
{
return m_STC->GetLineCount() + 1;
}
wxString filtered_address(address);
int dot = 0;
if (filtered_address.Contains("."))
{
dot = m_STC->GetCurrentLine() + 1;
filtered_address.Replace(".", "");
if (!filtered_address.IsNumber()) return 0;
}
const int line_no = dot + atoi(filtered_address.c_str());
if (line_no < 0)
{
return 1;
}
else if (line_no > m_STC->GetLineCount())
{
return m_STC->GetLineCount() + 1;
}
else
{
return line_no;
}
}
void wxExVi::Yank(
const wxString& begin_address,
const wxString& end_address) const
{
if (!SetSelection(begin_address, end_address))
{
return;
}
m_STC->Copy();
}
#endif // wxUSE_GUI
<|endoftext|> |
<commit_before>#include "./label_node.h"
#include <QPainter>
#include <QImage>
#include <QPoint>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "./importer.h"
#include "./mesh.h"
#include "./quad.h"
#include "./texture.h"
LabelNode::LabelNode(Label label) : label(label)
{
Importer importer;
anchorMesh = importer.import("../assets/anchor.dae", 0);
quad = std::make_shared<Quad>();
}
LabelNode::~LabelNode()
{
}
void LabelNode::render(Gl *gl, RenderData renderData)
{
if (!texture.get())
{
renderLabelTextToTexture(gl);
texture->initialize(gl);
}
Eigen::Affine3f transform(Eigen::Translation3f(label.anchorPosition) *
Eigen::Scaling(0.005f));
renderData.modelMatrix = transform.matrix();
anchorMesh->render(gl, renderData);
auto labelPosition = label.anchorPosition * 1.3f;
Eigen::Affine3f labelTransform(Eigen::Translation3f(labelPosition) *
Eigen::Scaling(2.0f, 0.5f, 1.0f) * Eigen::Scaling(0.07f));
renderData.modelMatrix = labelTransform.matrix();
Eigen::Affine3f viewTransform(Eigen::Translation3f(
renderData.viewMatrix.col(3).head(3)));
renderData.viewMatrix = viewTransform.matrix();
quad->render(gl, renderData, texture);
}
void LabelNode::renderLabelTextToTexture(Gl *gl)
{
QImage *image = new QImage(512, 128, QImage::Format_ARGB32);
image->fill(Qt::GlobalColor::transparent);
QPainter painter;
painter.begin(image);
painter.setPen(Qt::blue);
painter.setFont(QFont("Arial", 72));
painter.drawText(QRectF(0, 0, 512, 128), Qt::AlignCenter, label.text.c_str());
painter.end();
texture = std::make_shared<Texture>(image);
}
<commit_msg>Rounded rectangle as background for label.<commit_after>#include "./label_node.h"
#include <QPainter>
#include <QImage>
#include <QPoint>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "./importer.h"
#include "./mesh.h"
#include "./quad.h"
#include "./texture.h"
LabelNode::LabelNode(Label label) : label(label)
{
Importer importer;
anchorMesh = importer.import("../assets/anchor.dae", 0);
quad = std::make_shared<Quad>();
}
LabelNode::~LabelNode()
{
}
void LabelNode::render(Gl *gl, RenderData renderData)
{
if (!texture.get())
{
renderLabelTextToTexture(gl);
texture->initialize(gl);
}
Eigen::Affine3f transform(Eigen::Translation3f(label.anchorPosition) *
Eigen::Scaling(0.005f));
renderData.modelMatrix = transform.matrix();
anchorMesh->render(gl, renderData);
auto labelPosition = label.anchorPosition * 1.3f;
Eigen::Affine3f labelTransform(Eigen::Translation3f(labelPosition) *
Eigen::Scaling(2.0f, 0.5f, 1.0f) * Eigen::Scaling(0.07f));
renderData.modelMatrix = labelTransform.matrix();
Eigen::Affine3f viewTransform(Eigen::Translation3f(
renderData.viewMatrix.col(3).head(3)));
renderData.viewMatrix = viewTransform.matrix();
quad->render(gl, renderData, texture);
}
void LabelNode::renderLabelTextToTexture(Gl *gl)
{
QImage *image = new QImage(512, 128, QImage::Format_ARGB32);
image->fill(Qt::GlobalColor::transparent);
QPainter painter;
painter.begin(image);
painter.setBrush(QBrush(Qt::GlobalColor::lightGray));
painter.setPen(Qt::GlobalColor::lightGray);
painter.drawRoundRect(QRectF(0, 0, 512, 128), 15, 60);
painter.setPen(Qt::black);
painter.setFont(QFont("Arial", 72));
painter.drawText(QRectF(0, 0, 512, 128), Qt::AlignCenter, label.text.c_str());
painter.end();
texture = std::make_shared<Texture>(image);
}
<|endoftext|> |
<commit_before><commit_msg>3rdParty: nodejs: v8.0.0: v8: add missing return statement<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 Ivan Cukic <ivan.cukic(at)kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* or (at your option) any later version, as published by the Free
* Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "LocationManager.h"
#include "LocationManager_p.h"
#include <QHash>
#include <QUuid>
#include <KConfig>
#include <KConfigGroup>
#include <KDebug>
#include "network-engines/NetworkNotifier.h"
#include "locationmanageradaptor.h"
namespace Contour {
LocationManager::LocationManager(QObject * parent)
: QObject(parent), d(new Private(this))
{
kDebug() << "Starting the location manager";
(void) new LocationManagerAdaptor(this);
QDBusConnection::sessionBus().registerObject(
QLatin1String("/LocationManager"), this);
QDBusConnection::sessionBus().registerService("org.kde.LocationManager");
foreach (const QString & id, d->locationNames.keyList()) {
const QString & name = d->locationNames.readEntry(id, QString());
d->knownLocationIds[name] = id;
d->knownLocationInfos[id].name = name;
d->knownLocationInfos[id].networks = d->locationNetworks.readEntry(id, QStringList()).toSet();
d->knownLocationInfos[id].networkRoots = d->locationNetworkRoots.readEntry(id, QStringList()).toSet();
}
connect(NetworkNotifierLoader::self(), SIGNAL(activeAccessPointChanged(QString,QString)),
this, SLOT(setActiveAccessPoint(QString,QString)));
NetworkNotifierLoader::self()->init();
}
LocationManager::~LocationManager()
{
delete d;
}
QString LocationManager::addLocation(const QString & name)
{
if (name.isEmpty()) {
return QString();
}
QString id = d->knownLocationIds.value(name);
if (id.isEmpty()) {
// We don't have a location with that name
// Checking whether the name is an UUID. It shouldn't be
if (!QUuid(name).isNull()) {
return QString();
}
id = QUuid::createUuid();
d->knownLocationIds[name] = id;
d->knownLocationInfos[id].name = name;
d->locationNames.writeEntry(id, name);
d->scheduleConfigSync();
}
return id;
}
QString LocationManager::currentLocationId() const
{
return d->currentLocationId;
}
QString LocationManager::currentLocationName() const
{
if (d->currentLocationId.isEmpty())
return QString();
return d->knownLocationInfos[d->currentLocationId].name;
}
void LocationManager::setCurrentLocation(const QString & location)
{
QMetaObject::invokeMethod(
d,
"setCurrentLocation",
Qt::QueuedConnection,
Q_ARG(QString, location)
);
}
void LocationManager::Private::setCurrentLocation(const QString & location)
{
if (location.isEmpty()) {
currentLocationId.clear();
emit q->currentLocationChanged(currentLocationId, currentLocationId);
return;
}
kDebug() << "Setting the current location to" << location;
if (QUuid(location).isNull()) {
// We got passed a name for the location, not an id
// addLocation will not create a new location if already exists:
currentLocationId = q->addLocation(location);
} else {
// We got an UUID
if (knownLocationInfos.contains(location)) {
currentLocationId = location;
} else {
currentLocationId.clear();
}
}
if (!currentNetworkName.isEmpty()) {
kDebug() << "Current network name is" << currentNetworkName;
addNetworkToLocation(currentLocationId, currentNetworkName);
}
emit q->currentLocationChanged(currentLocationId, knownLocationInfos[currentLocationId].name);
}
QStringList LocationManager::knownLocations() const
{
return d->knownLocationInfos.keys();
}
void LocationManager::resetCurrentLocation()
{
setCurrentLocation(QString());
}
void LocationManager::setActiveAccessPoint(const QString & accessPoint, const QString & backend)
{
kDebug() << accessPoint << backend;
d->currentNetworkName = accessPoint;
// TODO: do stuff :)
// Checking whether we already have this access point
// tied to a location
kDebug() << "Checking whether we already have this access point tied to a location";
QHashIterator <QString, Private::LocationInfo> item(d->knownLocationInfos);
while (item.hasNext()) {
item.next();
kDebug() << item.key() << "has networks" << item.value().networks;
if (item.value().networks.contains(accessPoint)) {
setCurrentLocation(item.key());
return;
}
}
// Checking whether we have a location that was tied
// to a similarly named access point
const QString & accessPointRoot = d->networkRoot(accessPoint);
item.toFront();
while (item.hasNext()) {
item.next();
if (item.value().networkRoots.contains(accessPointRoot)) {
setCurrentLocation(item.key());
return;
}
}
// Nothing found
resetCurrentLocation();
}
LocationManager::Private::Private(LocationManager * parent)
: config("locationmanagerrc"),
locationNames(&config, "LocationManager-Location-Names"),
locationNetworks(&config, "LocationManager-Location-Networks"),
locationNetworkRoots(&config, "LocationManager-Location-NetworkRoots"),
currentLocationId(),
q(parent)
{
// Config syncing
connect(&configSyncTimer, SIGNAL(timeout()),
this, SLOT(configSync()));
configSyncTimer.setSingleShot(true);
configSyncTimer.setInterval(2 * /*60 **/ 1000);
}
LocationManager::Private::~Private()
{
configSync();
}
void LocationManager::Private::scheduleConfigSync()
{
if (!configSyncTimer.isActive()) {
configSyncTimer.start();
}
}
void LocationManager::Private::configSync()
{
configSyncTimer.stop();
config.sync();
}
void LocationManager::Private::addNetworkToLocation(const QString & location, const QString & network)
{
if (!knownLocationInfos.contains(location) || network.isEmpty()) return;
knownLocationInfos[location].networks << network;
knownLocationInfos[location].networkRoots << networkRoot(network);
kDebug()
<< "Setting networks for"
<< location
<< knownLocationInfos[location].name
<< knownLocationInfos[location].networks
<< knownLocationInfos[location].networkRoots
;
locationNetworks.writeEntry(location, knownLocationInfos[location].networks.toList());
locationNetworkRoots.writeEntry(location, knownLocationInfos[location].networkRoots.toList());
scheduleConfigSync();
}
QString LocationManager::Private::networkRoot(const QString & name)
{
// We are going to try to strip all the suffix data from
// the network name
QString result = name.toLower();
int lastDash = -1;
int lastLetter = -1;
for (int i = 0; i < name.size(); i++) {
if (name[i] == '-' || name[i] == '_') {
lastDash = i;
} else if (name[i] > '9') {
lastLetter = i;
}
}
lastLetter++;
if (lastLetter == name.size()) {
// Letters are till the end of the name
if (lastDash > name.size() / 2 || lastDash > 5) {
// The last dash is in the second half of the name, or the
// main name is longer than 5 characters
// considering it and the rest of the name as a suffix
kDebug() << "Returning (1) " << result.left(lastDash);
return result.left(lastDash);
} else {
// The letters are going to the end of the name, and
// there are no dashes or we are ignoring them
kDebug() << "Returning (2) " << result;
return result;
}
} else {
// We want to remove the end of the name
int last = lastDash;
if (last <= 0) {
last = lastLetter;
}
if (last >= name.size() / 2) {
kDebug() << "Returning (3) " << result.left(last);
return result.left(last);
}
kDebug() << "Returning (4) " << result;
return result;
}
}
} // namespace Contour
<commit_msg>On wrong location guess, don't use the same reasoning the next time<commit_after>/*
* Copyright (C) 2011 Ivan Cukic <ivan.cukic(at)kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* or (at your option) any later version, as published by the Free
* Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "LocationManager.h"
#include "LocationManager_p.h"
#include <QHash>
#include <QUuid>
#include <KConfig>
#include <KConfigGroup>
#include <KDebug>
#include "network-engines/NetworkNotifier.h"
#include "locationmanageradaptor.h"
namespace Contour {
LocationManager::LocationManager(QObject * parent)
: QObject(parent), d(new Private(this))
{
kDebug() << "Starting the location manager";
(void) new LocationManagerAdaptor(this);
QDBusConnection::sessionBus().registerObject(
QLatin1String("/LocationManager"), this);
QDBusConnection::sessionBus().registerService("org.kde.LocationManager");
foreach (const QString & id, d->locationNames.keyList()) {
const QString & name = d->locationNames.readEntry(id, QString());
d->knownLocationIds[name] = id;
d->knownLocationInfos[id].name = name;
d->knownLocationInfos[id].networks = d->locationNetworks.readEntry(id, QStringList()).toSet();
d->knownLocationInfos[id].networkRoots = d->locationNetworkRoots.readEntry(id, QStringList()).toSet();
}
d->knownLocationInfos[QString()] = d->knownLocationInfos["unknown"];
d->knownLocationInfos.remove("unknown");
d->knownLocationIds.remove(d->knownLocationInfos[QString()].name);
connect(NetworkNotifierLoader::self(), SIGNAL(activeAccessPointChanged(QString,QString)),
this, SLOT(setActiveAccessPoint(QString,QString)));
NetworkNotifierLoader::self()->init();
}
LocationManager::~LocationManager()
{
delete d;
}
QString LocationManager::addLocation(const QString & name)
{
if (name.isEmpty()) {
return QString();
}
QString id = d->knownLocationIds.value(name);
if (id.isEmpty()) {
// We don't have a location with that name
// Checking whether the name is an UUID. It shouldn't be
if (!QUuid(name).isNull()) {
return QString();
}
id = QUuid::createUuid();
d->knownLocationIds[name] = id;
d->knownLocationInfos[id].name = name;
d->locationNames.writeEntry(id, name);
d->scheduleConfigSync();
}
return id;
}
QString LocationManager::currentLocationId() const
{
return d->currentLocationId;
}
QString LocationManager::currentLocationName() const
{
if (d->currentLocationId.isEmpty())
return QString();
return d->knownLocationInfos[d->currentLocationId].name;
}
void LocationManager::setCurrentLocation(const QString & location)
{
QMetaObject::invokeMethod(
d,
"setCurrentLocation",
Qt::QueuedConnection,
Q_ARG(QString, location)
);
}
void LocationManager::Private::setCurrentLocation(const QString & location)
{
if (location.isEmpty()) {
currentLocationId.clear();
emit q->currentLocationChanged(currentLocationId, currentLocationId);
return;
}
kDebug() << "Setting the current location to" << location;
if (QUuid(location).isNull()) {
// We got passed a name for the location, not an id
// addLocation will not create a new location if already exists:
currentLocationId = q->addLocation(location);
} else {
// We got an UUID
if (knownLocationInfos.contains(location)) {
currentLocationId = location;
} else {
currentLocationId.clear();
}
}
if (!currentNetworkName.isEmpty()) {
kDebug() << "Current network name is" << currentNetworkName;
addNetworkToLocation(currentLocationId, currentNetworkName);
}
emit q->currentLocationChanged(currentLocationId, knownLocationInfos[currentLocationId].name);
}
QStringList LocationManager::knownLocations() const
{
return d->knownLocationInfos.keys();
}
void LocationManager::resetCurrentLocation()
{
setCurrentLocation(QString());
}
void LocationManager::setActiveAccessPoint(const QString & accessPoint, const QString & backend)
{
kDebug() << accessPoint << backend;
d->currentNetworkName = accessPoint;
// TODO: do stuff :)
// Checking whether we already have this access point
// tied to a location
kDebug() << "Checking whether we already have this access point tied to a location";
QHashIterator <QString, Private::LocationInfo> item(d->knownLocationInfos);
while (item.hasNext()) {
item.next();
kDebug() << item.key() << "has networks" << item.value().networks;
if (item.value().networks.contains(accessPoint)) {
setCurrentLocation(item.key());
return;
}
}
// Checking whether we have a location that was tied
// to a similarly named access point
const QString & accessPointRoot = d->networkRoot(accessPoint);
item.toFront();
while (item.hasNext()) {
item.next();
if (item.value().networkRoots.contains(accessPointRoot)) {
setCurrentLocation(item.key());
return;
}
}
// Nothing found
resetCurrentLocation();
}
LocationManager::Private::Private(LocationManager * parent)
: config("locationmanagerrc"),
locationNames(&config, "Names"),
locationNetworks(&config, "Networks"),
locationNetworkRoots(&config, "NetworkRoots"),
currentLocationId(),
q(parent)
{
// Config syncing
connect(&configSyncTimer, SIGNAL(timeout()),
this, SLOT(configSync()));
configSyncTimer.setSingleShot(true);
configSyncTimer.setInterval(2 * /*60 **/ 1000);
}
LocationManager::Private::~Private()
{
configSync();
}
void LocationManager::Private::scheduleConfigSync()
{
if (!configSyncTimer.isActive()) {
configSyncTimer.start();
}
}
void LocationManager::Private::configSync()
{
configSyncTimer.stop();
config.sync();
}
void LocationManager::Private::addNetworkToLocation(const QString & location, const QString & network)
{
if (!knownLocationInfos.contains(location) || network.isEmpty()) return;
// we first need to test whether there is already a network
// with the same root/name. If yes, we need to remove it and set
// the root/name as unknown location (aka empty)
const QString & root = networkRoot(network);
bool nameAlreadyRegistered = false;
bool rootAlreadyRegistered = false;
QMutableHashIterator <QString, Private::LocationInfo> item(knownLocationInfos);
while (item.hasNext()) {
item.next();
const QString & testLocation = item.key();
if (testLocation == location) continue;
Private::LocationInfo & info = item.value();
kDebug() << testLocation << "has networks" << info.networks << info.networkRoots;
if (info.networks.contains(network)) {
info.networks.remove(network);
locationNetworks.writeEntry(testLocation, info.networks.toList());
nameAlreadyRegistered = true;
}
if (info.networkRoots.contains(root)) {
info.networkRoots.remove(root);
locationNetworkRoots.writeEntry(testLocation, info.networkRoots.toList());
rootAlreadyRegistered = true;
}
}
if (!nameAlreadyRegistered) {
knownLocationInfos[location].networks << network;
} else {
knownLocationInfos[QString()].networks << network;
locationNetworks.writeEntry("unknown", knownLocationInfos[QString()].networks.toList());
}
if (!rootAlreadyRegistered) {
knownLocationInfos[location].networkRoots << root;
} else {
knownLocationInfos[QString()].networkRoots << root;
locationNetworkRoots.writeEntry("unknown", knownLocationInfos[QString()].networks.toList());
}
kDebug()
<< "Setting networks for"
<< location
<< knownLocationInfos[location].name
<< knownLocationInfos[location].networks
<< knownLocationInfos[location].networkRoots
;
locationNetworks.writeEntry(location, knownLocationInfos[location].networks.toList());
locationNetworkRoots.writeEntry(location, knownLocationInfos[location].networkRoots.toList());
scheduleConfigSync();
}
QString LocationManager::Private::networkRoot(const QString & name)
{
// We are going to try to strip all the suffix data from
// the network name
QString result = name.toLower();
int lastDash = -1;
int lastLetter = -1;
for (int i = 0; i < name.size(); i++) {
if (name[i] == '-' || name[i] == '_') {
lastDash = i;
} else if (name[i] > '9') {
lastLetter = i;
}
}
lastLetter++;
if (lastLetter == name.size()) {
// Letters are till the end of the name
if (lastDash > name.size() / 2 || lastDash > 5) {
// The last dash is in the second half of the name, or the
// main name is longer than 5 characters
// considering it and the rest of the name as a suffix
kDebug() << "Returning (1) " << result.left(lastDash);
return result.left(lastDash);
} else {
// The letters are going to the end of the name, and
// there are no dashes or we are ignoring them
kDebug() << "Returning (2) " << result;
return result;
}
} else {
// We want to remove the end of the name
int last = lastDash;
if (last <= 0) {
last = lastLetter;
}
if (last >= name.size() / 2) {
kDebug() << "Returning (3) " << result.left(last);
return result.left(last);
}
kDebug() << "Returning (4) " << result;
return result;
}
}
} // namespace Contour
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 Ivan Cukic <ivan.cukic(at)kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* or (at your option) any later version, as published by the Free
* Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "LocationManager.h"
#include "LocationManager_p.h"
#include <QHash>
#include <QUuid>
#include <KConfig>
#include <KConfigGroup>
#include <KDebug>
#include "network-engines/NetworkNotifier.h"
#include "locationmanageradaptor.h"
namespace Contour {
LocationManager::LocationManager(QObject * parent)
: QObject(parent), d(new Private(this))
{
kDebug() << "Starting the location manager";
(void) new LocationManagerAdaptor(this);
QDBusConnection::sessionBus().registerObject(
QLatin1String("/LocationManager"), this);
QDBusConnection::sessionBus().registerService("org.kde.LocationManager");
foreach (const QString & id, d->locationNames.keyList()) {
const QString & name = d->locationNames.readEntry(id, QString());
d->knownLocationIds[name] = id;
d->knownLocationInfos[id].name = name;
d->knownLocationInfos[id].networks = d->locationNetworks.readEntry(id, QStringList()).toSet();
d->knownLocationInfos[id].networkRoots = d->locationNetworkRoots.readEntry(id, QStringList()).toSet();
}
connect(NetworkNotifierLoader::self(), SIGNAL(activeAccessPointChanged(QString,QString)),
this, SLOT(setActiveAccessPoint(QString,QString)));
NetworkNotifierLoader::self()->init();
}
LocationManager::~LocationManager()
{
delete d;
}
QString LocationManager::addLocation(const QString & name)
{
if (name.isEmpty()) {
return QString();
}
QString id = d->knownLocationIds.value(name);
if (id.isEmpty()) {
// We don't have a location with that name
// Checking whether the name is an UUID. It shouldn't be
if (!QUuid(name).isNull()) {
return QString();
}
id = QUuid::createUuid();
d->knownLocationIds[name] = id;
d->knownLocationInfos[id].name = name;
d->locationNames.writeEntry(id, name);
d->scheduleConfigSync();
}
return id;
}
QString LocationManager::currentLocationId() const
{
return d->currentLocationId;
}
QString LocationManager::currentLocationName() const
{
if (d->currentLocationId.isEmpty())
return QString();
return d->knownLocationInfos[d->currentLocationId].name;
}
void LocationManager::setCurrentLocation(const QString & location)
{
QMetaObject::invokeMethod(
d,
"setCurrentLocation",
Qt::QueuedConnection,
Q_ARG(QString, location)
);
}
void LocationManager::Private::setCurrentLocation(const QString & location)
{
if (location.isEmpty()) {
currentLocationId.clear();
emit q->currentLocationChanged(currentLocationId, currentLocationId);
return;
}
kDebug() << "Setting the current location to" << location;
if (QUuid(location).isNull()) {
// We got passed a name for the location, not an id
// addLocation will not create a new location if already exists:
currentLocationId = q->addLocation(location);
} else {
// We got an UUID
if (knownLocationInfos.contains(location)) {
currentLocationId = location;
} else {
currentLocationId.clear();
}
}
if (!currentNetworkName.isEmpty()) {
kDebug() << "Current network name is" << currentNetworkName;
addNetworkToLocation(currentLocationId, currentNetworkName);
}
emit q->currentLocationChanged(currentLocationId, knownLocationInfos[currentLocationId].name);
}
QStringList LocationManager::knownLocations() const
{
return d->knownLocationInfos.keys();
}
void LocationManager::resetCurrentLocation()
{
setCurrentLocation(QString());
}
void LocationManager::setActiveAccessPoint(const QString & accessPoint, const QString & backend)
{
kDebug() << accessPoint << backend;
d->currentNetworkName = accessPoint;
// TODO: do stuff :)
// Checking whether we already have this access point
// tied to a location
kDebug() << "Checking whether we already have this access point tied to a location";
QHashIterator <QString, Private::LocationInfo> item(d->knownLocationInfos);
while (item.hasNext()) {
item.next();
kDebug() << item.key() << "has networks" << item.value().networks;
if (item.value().networks.contains(accessPoint)) {
setCurrentLocation(item.key());
return;
}
}
// Checking whether we have a location that was tied
// to a similarly named access point
const QString & accessPointRoot = d->networkRoot(accessPoint);
item.toFront();
while (item.hasNext()) {
item.next();
if (item.value().networkRoots.contains(accessPointRoot)) {
setCurrentLocation(item.key());
return;
}
}
// Nothing found
resetCurrentLocation();
}
LocationManager::Private::Private(LocationManager * parent)
: config("locationmanagerrc"),
locationNames(&config, "LocationManager-Location-Names"),
locationNetworks(&config, "LocationManager-Location-Networks"),
locationNetworkRoots(&config, "LocationManager-Location-NetworkRoots"),
currentLocationId(),
q(parent)
{
// Config syncing
connect(&configSyncTimer, SIGNAL(timeout()),
this, SLOT(configSync()));
configSyncTimer.setSingleShot(true);
configSyncTimer.setInterval(2 * /*60 **/ 1000);
}
LocationManager::Private::~Private()
{
configSync();
}
void LocationManager::Private::scheduleConfigSync()
{
if (!configSyncTimer.isActive()) {
configSyncTimer.start();
}
}
void LocationManager::Private::configSync()
{
configSyncTimer.stop();
config.sync();
}
void LocationManager::Private::addNetworkToLocation(const QString & location, const QString & network)
{
if (!knownLocationInfos.contains(location) || network.isEmpty()) return;
knownLocationInfos[location].networks << network;
knownLocationInfos[location].networkRoots << networkRoot(network);
kDebug()
<< "Setting networks for"
<< location
<< knownLocationInfos[location].name
<< knownLocationInfos[location].networks
<< knownLocationInfos[location].networkRoots
;
locationNetworks.writeEntry(location, knownLocationInfos[location].networks.toList());
locationNetworkRoots.writeEntry(location, knownLocationInfos[location].networkRoots.toList());
scheduleConfigSync();
}
QString LocationManager::Private::networkRoot(const QString & name)
{
// We are going to try to strip all the suffix data from
// the network name
QString result = name.toLower();
int lastDash = -1;
int lastLetter = -1;
for (int i = 0; i < name.size(); i++) {
if (name[i] == '-' || name[i] == '_') {
lastDash = i;
} else if (name[i] > '9') {
lastLetter = i;
}
}
if (lastLetter == name.size() - 1) {
// Letters are till the end of the name
if (lastDash > name.size() / 2) {
// The last dash is in the second half of the name,
// considering it and the rest of the name as a suffix
return result.left(lastDash);
} else {
// The letters are going to the end of the name, and
// there are no dashes or we are ignoring them
return result;
}
} else {
// We want to remove the end of the name
int last = qMin(lastDash, lastLetter);
if (last <= name.size()) {
last = qMax(lastDash, lastLetter);
}
if (last > name.size() / 2) {
return result.left(last);
}
return result;
}
}
} // namespace Contour
<commit_msg>Fixed the smart location deduction from wifi names<commit_after>/*
* Copyright (C) 2011 Ivan Cukic <ivan.cukic(at)kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* or (at your option) any later version, as published by the Free
* Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "LocationManager.h"
#include "LocationManager_p.h"
#include <QHash>
#include <QUuid>
#include <KConfig>
#include <KConfigGroup>
#include <KDebug>
#include "network-engines/NetworkNotifier.h"
#include "locationmanageradaptor.h"
namespace Contour {
LocationManager::LocationManager(QObject * parent)
: QObject(parent), d(new Private(this))
{
kDebug() << "Starting the location manager";
(void) new LocationManagerAdaptor(this);
QDBusConnection::sessionBus().registerObject(
QLatin1String("/LocationManager"), this);
QDBusConnection::sessionBus().registerService("org.kde.LocationManager");
foreach (const QString & id, d->locationNames.keyList()) {
const QString & name = d->locationNames.readEntry(id, QString());
d->knownLocationIds[name] = id;
d->knownLocationInfos[id].name = name;
d->knownLocationInfos[id].networks = d->locationNetworks.readEntry(id, QStringList()).toSet();
d->knownLocationInfos[id].networkRoots = d->locationNetworkRoots.readEntry(id, QStringList()).toSet();
}
connect(NetworkNotifierLoader::self(), SIGNAL(activeAccessPointChanged(QString,QString)),
this, SLOT(setActiveAccessPoint(QString,QString)));
NetworkNotifierLoader::self()->init();
}
LocationManager::~LocationManager()
{
delete d;
}
QString LocationManager::addLocation(const QString & name)
{
if (name.isEmpty()) {
return QString();
}
QString id = d->knownLocationIds.value(name);
if (id.isEmpty()) {
// We don't have a location with that name
// Checking whether the name is an UUID. It shouldn't be
if (!QUuid(name).isNull()) {
return QString();
}
id = QUuid::createUuid();
d->knownLocationIds[name] = id;
d->knownLocationInfos[id].name = name;
d->locationNames.writeEntry(id, name);
d->scheduleConfigSync();
}
return id;
}
QString LocationManager::currentLocationId() const
{
return d->currentLocationId;
}
QString LocationManager::currentLocationName() const
{
if (d->currentLocationId.isEmpty())
return QString();
return d->knownLocationInfos[d->currentLocationId].name;
}
void LocationManager::setCurrentLocation(const QString & location)
{
QMetaObject::invokeMethod(
d,
"setCurrentLocation",
Qt::QueuedConnection,
Q_ARG(QString, location)
);
}
void LocationManager::Private::setCurrentLocation(const QString & location)
{
if (location.isEmpty()) {
currentLocationId.clear();
emit q->currentLocationChanged(currentLocationId, currentLocationId);
return;
}
kDebug() << "Setting the current location to" << location;
if (QUuid(location).isNull()) {
// We got passed a name for the location, not an id
// addLocation will not create a new location if already exists:
currentLocationId = q->addLocation(location);
} else {
// We got an UUID
if (knownLocationInfos.contains(location)) {
currentLocationId = location;
} else {
currentLocationId.clear();
}
}
if (!currentNetworkName.isEmpty()) {
kDebug() << "Current network name is" << currentNetworkName;
addNetworkToLocation(currentLocationId, currentNetworkName);
}
emit q->currentLocationChanged(currentLocationId, knownLocationInfos[currentLocationId].name);
}
QStringList LocationManager::knownLocations() const
{
return d->knownLocationInfos.keys();
}
void LocationManager::resetCurrentLocation()
{
setCurrentLocation(QString());
}
void LocationManager::setActiveAccessPoint(const QString & accessPoint, const QString & backend)
{
kDebug() << accessPoint << backend;
d->currentNetworkName = accessPoint;
// TODO: do stuff :)
// Checking whether we already have this access point
// tied to a location
kDebug() << "Checking whether we already have this access point tied to a location";
QHashIterator <QString, Private::LocationInfo> item(d->knownLocationInfos);
while (item.hasNext()) {
item.next();
kDebug() << item.key() << "has networks" << item.value().networks;
if (item.value().networks.contains(accessPoint)) {
setCurrentLocation(item.key());
return;
}
}
// Checking whether we have a location that was tied
// to a similarly named access point
const QString & accessPointRoot = d->networkRoot(accessPoint);
item.toFront();
while (item.hasNext()) {
item.next();
if (item.value().networkRoots.contains(accessPointRoot)) {
setCurrentLocation(item.key());
return;
}
}
// Nothing found
resetCurrentLocation();
}
LocationManager::Private::Private(LocationManager * parent)
: config("locationmanagerrc"),
locationNames(&config, "LocationManager-Location-Names"),
locationNetworks(&config, "LocationManager-Location-Networks"),
locationNetworkRoots(&config, "LocationManager-Location-NetworkRoots"),
currentLocationId(),
q(parent)
{
// Config syncing
connect(&configSyncTimer, SIGNAL(timeout()),
this, SLOT(configSync()));
configSyncTimer.setSingleShot(true);
configSyncTimer.setInterval(2 * /*60 **/ 1000);
}
LocationManager::Private::~Private()
{
configSync();
}
void LocationManager::Private::scheduleConfigSync()
{
if (!configSyncTimer.isActive()) {
configSyncTimer.start();
}
}
void LocationManager::Private::configSync()
{
configSyncTimer.stop();
config.sync();
}
void LocationManager::Private::addNetworkToLocation(const QString & location, const QString & network)
{
if (!knownLocationInfos.contains(location) || network.isEmpty()) return;
knownLocationInfos[location].networks << network;
knownLocationInfos[location].networkRoots << networkRoot(network);
kDebug()
<< "Setting networks for"
<< location
<< knownLocationInfos[location].name
<< knownLocationInfos[location].networks
<< knownLocationInfos[location].networkRoots
;
locationNetworks.writeEntry(location, knownLocationInfos[location].networks.toList());
locationNetworkRoots.writeEntry(location, knownLocationInfos[location].networkRoots.toList());
scheduleConfigSync();
}
QString LocationManager::Private::networkRoot(const QString & name)
{
// We are going to try to strip all the suffix data from
// the network name
QString result = name.toLower();
int lastDash = -1;
int lastLetter = -1;
for (int i = 0; i < name.size(); i++) {
if (name[i] == '-' || name[i] == '_') {
lastDash = i;
} else if (name[i] > '9') {
lastLetter = i;
}
}
lastLetter++;
if (lastLetter == name.size()) {
// Letters are till the end of the name
if (lastDash > name.size() / 2 || lastDash > 5) {
// The last dash is in the second half of the name, or the
// main name is longer than 5 characters
// considering it and the rest of the name as a suffix
kDebug() << "Returning (1) " << result.left(lastDash);
return result.left(lastDash);
} else {
// The letters are going to the end of the name, and
// there are no dashes or we are ignoring them
kDebug() << "Returning (2) " << result;
return result;
}
} else {
// We want to remove the end of the name
int last = lastDash;
if (last <= 0) {
last = lastLetter;
}
if (last >= name.size() / 2) {
kDebug() << "Returning (3) " << result.left(last);
return result.left(last);
}
kDebug() << "Returning (4) " << result;
return result;
}
}
} // namespace Contour
<|endoftext|> |
<commit_before>#ifndef _INPUSTREAM_HXX_
#define _INPUSTREAM_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_
#include <com/sun/star/ucb/XContentProvider.hpp>
#endif
namespace chelp {
// forward declaration
class XInputStream_impl
: public cppu::OWeakObject,
public com::sun::star::io::XInputStream,
public com::sun::star::io::XSeekable
{
public:
XInputStream_impl( const rtl::OUString& aUncPath );
virtual ~XInputStream_impl();
/**
* Returns an error code as given by filerror.hxx
*/
bool SAL_CALL CtorSuccess();
virtual com::sun::star::uno::Any SAL_CALL
queryInterface(
const com::sun::star::uno::Type& rType )
throw( com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
acquire(
void )
throw();
virtual void SAL_CALL
release(
void )
throw();
virtual sal_Int32 SAL_CALL
readBytes(
com::sun::star::uno::Sequence< sal_Int8 >& aData,
sal_Int32 nBytesToRead )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL
readSomeBytes(
com::sun::star::uno::Sequence< sal_Int8 >& aData,
sal_Int32 nMaxBytesToRead )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
skipBytes(
sal_Int32 nBytesToSkip )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual sal_Int32 SAL_CALL
available(
void )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual void SAL_CALL
closeInput(
void )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual void SAL_CALL
seek(
sal_Int64 location )
throw( com::sun::star::lang::IllegalArgumentException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual sal_Int64 SAL_CALL
getPosition(
void )
throw( com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual sal_Int64 SAL_CALL
getLength(
void )
throw( com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
private:
bool m_bIsOpen;
osl::File m_aFile;
};
} // end namespace XInputStream_impl
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.304); FILE MERGED 2008/04/01 16:07:43 thb 1.2.304.3: #i85898# Stripping all external header guards 2008/04/01 13:02:57 thb 1.2.304.2: #i85898# Stripping all external header guards 2008/03/31 13:04:25 rt 1.2.304.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: inputstream.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _INPUSTREAM_HXX_
#define _INPUSTREAM_HXX_
#include <rtl/ustring.hxx>
#include <osl/file.hxx>
#include <cppuhelper/weak.hxx>
#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/ucb/XContentProvider.hpp>
namespace chelp {
// forward declaration
class XInputStream_impl
: public cppu::OWeakObject,
public com::sun::star::io::XInputStream,
public com::sun::star::io::XSeekable
{
public:
XInputStream_impl( const rtl::OUString& aUncPath );
virtual ~XInputStream_impl();
/**
* Returns an error code as given by filerror.hxx
*/
bool SAL_CALL CtorSuccess();
virtual com::sun::star::uno::Any SAL_CALL
queryInterface(
const com::sun::star::uno::Type& rType )
throw( com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
acquire(
void )
throw();
virtual void SAL_CALL
release(
void )
throw();
virtual sal_Int32 SAL_CALL
readBytes(
com::sun::star::uno::Sequence< sal_Int8 >& aData,
sal_Int32 nBytesToRead )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL
readSomeBytes(
com::sun::star::uno::Sequence< sal_Int8 >& aData,
sal_Int32 nMaxBytesToRead )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
skipBytes(
sal_Int32 nBytesToSkip )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::BufferSizeExceededException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual sal_Int32 SAL_CALL
available(
void )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual void SAL_CALL
closeInput(
void )
throw( com::sun::star::io::NotConnectedException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual void SAL_CALL
seek(
sal_Int64 location )
throw( com::sun::star::lang::IllegalArgumentException,
com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual sal_Int64 SAL_CALL
getPosition(
void )
throw( com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
virtual sal_Int64 SAL_CALL
getLength(
void )
throw( com::sun::star::io::IOException,
com::sun::star::uno::RuntimeException );
private:
bool m_bIsOpen;
osl::File m_aFile;
};
} // end namespace XInputStream_impl
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: XMLTextShapeImportHelper.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mib $ $Date: 2001-04-23 07:37:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLTEXTSHAPEIMPORTHELPER_HXX
#define _XMLTEXTSHAPEIMPORTHELPER_HXX
#ifndef _XMLOFF_SHAPEIMPORT_HXX_
#include "shapeimport.hxx"
#endif
class XMLTextShapeImportHelper : public XMLShapeImportHelper
{
SvXMLImport& rImport;
const ::rtl::OUString sAnchorType;
const ::rtl::OUString sAnchorPageNo;
const ::rtl::OUString sVertOrientPosition;
public:
XMLTextShapeImportHelper( SvXMLImport& rImp );
~XMLTextShapeImportHelper();
virtual void addShape(
::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList >& xAttrList,
::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShapes >& rShapes );
};
#endif
<commit_msg>INTEGRATION: CWS sb25 (1.2.438); FILE MERGED 2004/11/15 16:46:24 sb 1.2.438.1: #i37077# Reduce number of exported symbols of xmloff dynamic library.<commit_after>/*************************************************************************
*
* $RCSfile: XMLTextShapeImportHelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-01-11 14:29:07 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLTEXTSHAPEIMPORTHELPER_HXX
#define _XMLTEXTSHAPEIMPORTHELPER_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef INCLUDED_XMLOFF_DLLAPI_H
#include "xmloff/dllapi.h"
#endif
#ifndef _XMLOFF_SHAPEIMPORT_HXX_
#include "shapeimport.hxx"
#endif
class XMLOFF_DLLPUBLIC XMLTextShapeImportHelper : public XMLShapeImportHelper
{
SvXMLImport& rImport;
const ::rtl::OUString sAnchorType;
const ::rtl::OUString sAnchorPageNo;
const ::rtl::OUString sVertOrientPosition;
public:
XMLTextShapeImportHelper( SvXMLImport& rImp );
~XMLTextShapeImportHelper();
virtual void addShape(
::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShape >& rShape,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList >& xAttrList,
::com::sun::star::uno::Reference<
::com::sun::star::drawing::XShapes >& rShapes );
};
#endif
<|endoftext|> |
<commit_before>//===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include "AArch64.h"
#include "AArch64TargetMachine.h"
#include "AArch64TargetObjectFile.h"
#include "AArch64TargetTransformInfo.h"
#ifdef LLVM_BUILD_GLOBAL_ISEL
# include "llvm/CodeGen/GlobalISel/IRTranslator.h"
#endif
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
static cl::opt<bool>
EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"),
cl::init(true), cl::Hidden);
static cl::opt<bool> EnableMCR("aarch64-mcr",
cl::desc("Enable the machine combiner pass"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar"
" integer instructions"), cl::init(false), cl::Hidden);
static cl::opt<bool>
EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote "
"constant pass"), cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the"
" linker optimization hints (LOH)"), cl::init(true),
cl::Hidden);
static cl::opt<bool>
EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden,
cl::desc("Enable the pass that removes dead"
" definitons and replaces stores to"
" them with stores to the zero"
" register"),
cl::init(true));
static cl::opt<bool>
EnableRedundantCopyElimination("aarch64-redundant-copy-elim",
cl::desc("Enable the redundant copy elimination pass"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair"
" optimization pass"), cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden,
cl::desc("Run SimplifyCFG after expanding atomic operations"
" to make use of cmpxchg flow-based information"),
cl::init(true));
static cl::opt<bool>
EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
cl::desc("Run early if-conversion"),
cl::init(true));
static cl::opt<bool>
EnableCondOpt("aarch64-condopt",
cl::desc("Enable the condition optimizer pass"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
cl::desc("Work around Cortex-A53 erratum 835769"),
cl::init(false));
static cl::opt<bool>
EnableGEPOpt("aarch64-gep-opt", cl::Hidden,
cl::desc("Enable optimizations on complex GEPs"),
cl::init(false));
// FIXME: Unify control over GlobalMerge.
static cl::opt<cl::boolOrDefault>
EnableGlobalMerge("aarch64-global-merge", cl::Hidden,
cl::desc("Enable the global merge pass"));
extern "C" void LLVMInitializeAArch64Target() {
// Register the target.
RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget);
RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget);
RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64Target);
}
//===----------------------------------------------------------------------===//
// AArch64 Lowering public interface.
//===----------------------------------------------------------------------===//
static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
if (TT.isOSBinFormatMachO())
return make_unique<AArch64_MachoTargetObjectFile>();
return make_unique<AArch64_ELFTargetObjectFile>();
}
// Helper function to build a DataLayout string
static std::string computeDataLayout(const Triple &TT, bool LittleEndian) {
if (TT.isOSBinFormatMachO())
return "e-m:o-i64:64-i128:128-n32:64-S128";
if (LittleEndian)
return "e-m:e-i64:64-i128:128-n32:64-S128";
return "E-m:e-i64:64-i128:128-n32:64-S128";
}
/// TargetMachine ctor - Create an AArch64 architecture model.
///
AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
StringRef CPU, StringRef FS,
const TargetOptions &Options,
Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL,
bool LittleEndian)
// This nested ternary is horrible, but DL needs to be properly
// initialized before TLInfo is constructed.
: LLVMTargetMachine(T, computeDataLayout(TT, LittleEndian), TT, CPU, FS,
Options, RM, CM, OL),
TLOF(createTLOF(getTargetTriple())),
isLittle(LittleEndian) {
initAsmInfo();
}
AArch64TargetMachine::~AArch64TargetMachine() {}
const AArch64Subtarget *
AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
Attribute CPUAttr = F.getFnAttribute("target-cpu");
Attribute FSAttr = F.getFnAttribute("target-features");
std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
? CPUAttr.getValueAsString().str()
: TargetCPU;
std::string FS = !FSAttr.hasAttribute(Attribute::None)
? FSAttr.getValueAsString().str()
: TargetFS;
auto &I = SubtargetMap[CPU + FS];
if (!I) {
// This needs to be done before we create a new subtarget since any
// creation will depend on the TM and the code generation flags on the
// function that reside in TargetOptions.
resetTargetOptions(F);
I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
isLittle);
}
return I.get();
}
void AArch64leTargetMachine::anchor() { }
AArch64leTargetMachine::AArch64leTargetMachine(
const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL)
: AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
void AArch64beTargetMachine::anchor() { }
AArch64beTargetMachine::AArch64beTargetMachine(
const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL)
: AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
namespace {
/// AArch64 Code Generator Pass Configuration Options.
class AArch64PassConfig : public TargetPassConfig {
public:
AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
: TargetPassConfig(TM, PM) {
if (TM->getOptLevel() != CodeGenOpt::None)
substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
}
AArch64TargetMachine &getAArch64TargetMachine() const {
return getTM<AArch64TargetMachine>();
}
void addIRPasses() override;
bool addPreISel() override;
bool addInstSelector() override;
#ifdef LLVM_BUILD_GLOBAL_ISEL
bool addIRTranslator() override;
#endif
bool addILPOpts() override;
void addPreRegAlloc() override;
void addPostRegAlloc() override;
void addPreSched2() override;
void addPreEmitPass() override;
};
} // namespace
TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
return TargetIRAnalysis([this](const Function &F) {
return TargetTransformInfo(AArch64TTIImpl(this, F));
});
}
TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
return new AArch64PassConfig(this, PM);
}
void AArch64PassConfig::addIRPasses() {
// Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
// ourselves.
addPass(createAtomicExpandPass(TM));
// Cmpxchg instructions are often used with a subsequent comparison to
// determine whether it succeeded. We can exploit existing control-flow in
// ldrex/strex loops to simplify this, but it needs tidying up.
if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
addPass(createCFGSimplificationPass());
TargetPassConfig::addIRPasses();
// Match interleaved memory accesses to ldN/stN intrinsics.
if (TM->getOptLevel() != CodeGenOpt::None)
addPass(createInterleavedAccessPass(TM));
if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
// Call SeparateConstOffsetFromGEP pass to extract constants within indices
// and lower a GEP with multiple indices to either arithmetic operations or
// multiple GEPs with single index.
addPass(createSeparateConstOffsetFromGEPPass(TM, true));
// Call EarlyCSE pass to find and remove subexpressions in the lowered
// result.
addPass(createEarlyCSEPass());
// Do loop invariant code motion in case part of the lowered result is
// invariant.
addPass(createLICMPass());
}
}
// Pass Pipeline Configuration
bool AArch64PassConfig::addPreISel() {
// Run promote constant before global merge, so that the promoted constants
// get a chance to be merged
if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
addPass(createAArch64PromoteConstantPass());
// FIXME: On AArch64, this depends on the type.
// Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
// and the offset has to be a multiple of the related size in bytes.
if ((TM->getOptLevel() != CodeGenOpt::None &&
EnableGlobalMerge == cl::BOU_UNSET) ||
EnableGlobalMerge == cl::BOU_TRUE) {
bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
(EnableGlobalMerge == cl::BOU_UNSET);
addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
}
if (TM->getOptLevel() != CodeGenOpt::None)
addPass(createAArch64AddressTypePromotionPass());
return false;
}
bool AArch64PassConfig::addInstSelector() {
addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
// For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
// references to _TLS_MODULE_BASE_ as possible.
if (TM->getTargetTriple().isOSBinFormatELF() &&
getOptLevel() != CodeGenOpt::None)
addPass(createAArch64CleanupLocalDynamicTLSPass());
return false;
}
#ifdef LLVM_BUILD_GLOBAL_ISEL
bool AArch64PassConfig::addIRTranslator() {
addPass(new IRTranslator());
return false;
}
#endif
bool AArch64PassConfig::addILPOpts() {
if (EnableCondOpt)
addPass(createAArch64ConditionOptimizerPass());
if (EnableCCMP)
addPass(createAArch64ConditionalCompares());
if (EnableMCR)
addPass(&MachineCombinerID);
if (EnableEarlyIfConversion)
addPass(&EarlyIfConverterID);
if (EnableStPairSuppress)
addPass(createAArch64StorePairSuppressPass());
return true;
}
void AArch64PassConfig::addPreRegAlloc() {
// Use AdvSIMD scalar instructions whenever profitable.
if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
addPass(createAArch64AdvSIMDScalar());
// The AdvSIMD pass may produce copies that can be rewritten to
// be register coaleascer friendly.
addPass(&PeepholeOptimizerID);
}
}
void AArch64PassConfig::addPostRegAlloc() {
// Remove redundant copy instructions.
if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
addPass(createAArch64RedundantCopyEliminationPass());
// Change dead register definitions to refer to the zero register.
if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
addPass(createAArch64DeadRegisterDefinitions());
if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
// Improve performance for some FP/SIMD code for A57.
addPass(createAArch64A57FPLoadBalancing());
}
void AArch64PassConfig::addPreSched2() {
// Expand some pseudo instructions to allow proper scheduling.
addPass(createAArch64ExpandPseudoPass());
// Use load/store pair instructions when possible.
if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
addPass(createAArch64LoadStoreOptimizationPass());
}
void AArch64PassConfig::addPreEmitPass() {
if (EnableA53Fix835769)
addPass(createAArch64A53Fix835769());
// Relax conditional branch instructions if they're otherwise out of
// range of their destination.
addPass(createAArch64BranchRelaxation());
if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
TM->getTargetTriple().isOSBinFormatMachO())
addPass(createAArch64CollectLOHPass());
}
<commit_msg>[AArch64] Initialize GlobalISel as part of the target initialization.<commit_after>//===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
//===----------------------------------------------------------------------===//
#include "AArch64.h"
#include "AArch64TargetMachine.h"
#include "AArch64TargetObjectFile.h"
#include "AArch64TargetTransformInfo.h"
#ifdef LLVM_BUILD_GLOBAL_ISEL
# include "llvm/CodeGen/GlobalISel/IRTranslator.h"
#endif
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
using namespace llvm;
static cl::opt<bool>
EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"),
cl::init(true), cl::Hidden);
static cl::opt<bool> EnableMCR("aarch64-mcr",
cl::desc("Enable the machine combiner pass"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar"
" integer instructions"), cl::init(false), cl::Hidden);
static cl::opt<bool>
EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote "
"constant pass"), cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the"
" linker optimization hints (LOH)"), cl::init(true),
cl::Hidden);
static cl::opt<bool>
EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden,
cl::desc("Enable the pass that removes dead"
" definitons and replaces stores to"
" them with stores to the zero"
" register"),
cl::init(true));
static cl::opt<bool>
EnableRedundantCopyElimination("aarch64-redundant-copy-elim",
cl::desc("Enable the redundant copy elimination pass"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair"
" optimization pass"), cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden,
cl::desc("Run SimplifyCFG after expanding atomic operations"
" to make use of cmpxchg flow-based information"),
cl::init(true));
static cl::opt<bool>
EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
cl::desc("Run early if-conversion"),
cl::init(true));
static cl::opt<bool>
EnableCondOpt("aarch64-condopt",
cl::desc("Enable the condition optimizer pass"),
cl::init(true), cl::Hidden);
static cl::opt<bool>
EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
cl::desc("Work around Cortex-A53 erratum 835769"),
cl::init(false));
static cl::opt<bool>
EnableGEPOpt("aarch64-gep-opt", cl::Hidden,
cl::desc("Enable optimizations on complex GEPs"),
cl::init(false));
// FIXME: Unify control over GlobalMerge.
static cl::opt<cl::boolOrDefault>
EnableGlobalMerge("aarch64-global-merge", cl::Hidden,
cl::desc("Enable the global merge pass"));
extern "C" void LLVMInitializeAArch64Target() {
// Register the target.
RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget);
RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget);
RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64Target);
initializeGlobalISel(*PassRegistry::getPassRegistry());
}
//===----------------------------------------------------------------------===//
// AArch64 Lowering public interface.
//===----------------------------------------------------------------------===//
static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
if (TT.isOSBinFormatMachO())
return make_unique<AArch64_MachoTargetObjectFile>();
return make_unique<AArch64_ELFTargetObjectFile>();
}
// Helper function to build a DataLayout string
static std::string computeDataLayout(const Triple &TT, bool LittleEndian) {
if (TT.isOSBinFormatMachO())
return "e-m:o-i64:64-i128:128-n32:64-S128";
if (LittleEndian)
return "e-m:e-i64:64-i128:128-n32:64-S128";
return "E-m:e-i64:64-i128:128-n32:64-S128";
}
/// TargetMachine ctor - Create an AArch64 architecture model.
///
AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
StringRef CPU, StringRef FS,
const TargetOptions &Options,
Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL,
bool LittleEndian)
// This nested ternary is horrible, but DL needs to be properly
// initialized before TLInfo is constructed.
: LLVMTargetMachine(T, computeDataLayout(TT, LittleEndian), TT, CPU, FS,
Options, RM, CM, OL),
TLOF(createTLOF(getTargetTriple())),
isLittle(LittleEndian) {
initAsmInfo();
}
AArch64TargetMachine::~AArch64TargetMachine() {}
const AArch64Subtarget *
AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
Attribute CPUAttr = F.getFnAttribute("target-cpu");
Attribute FSAttr = F.getFnAttribute("target-features");
std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
? CPUAttr.getValueAsString().str()
: TargetCPU;
std::string FS = !FSAttr.hasAttribute(Attribute::None)
? FSAttr.getValueAsString().str()
: TargetFS;
auto &I = SubtargetMap[CPU + FS];
if (!I) {
// This needs to be done before we create a new subtarget since any
// creation will depend on the TM and the code generation flags on the
// function that reside in TargetOptions.
resetTargetOptions(F);
I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
isLittle);
}
return I.get();
}
void AArch64leTargetMachine::anchor() { }
AArch64leTargetMachine::AArch64leTargetMachine(
const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL)
: AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
void AArch64beTargetMachine::anchor() { }
AArch64beTargetMachine::AArch64beTargetMachine(
const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM,
CodeGenOpt::Level OL)
: AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
namespace {
/// AArch64 Code Generator Pass Configuration Options.
class AArch64PassConfig : public TargetPassConfig {
public:
AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
: TargetPassConfig(TM, PM) {
if (TM->getOptLevel() != CodeGenOpt::None)
substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
}
AArch64TargetMachine &getAArch64TargetMachine() const {
return getTM<AArch64TargetMachine>();
}
void addIRPasses() override;
bool addPreISel() override;
bool addInstSelector() override;
#ifdef LLVM_BUILD_GLOBAL_ISEL
bool addIRTranslator() override;
#endif
bool addILPOpts() override;
void addPreRegAlloc() override;
void addPostRegAlloc() override;
void addPreSched2() override;
void addPreEmitPass() override;
};
} // namespace
TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
return TargetIRAnalysis([this](const Function &F) {
return TargetTransformInfo(AArch64TTIImpl(this, F));
});
}
TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
return new AArch64PassConfig(this, PM);
}
void AArch64PassConfig::addIRPasses() {
// Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
// ourselves.
addPass(createAtomicExpandPass(TM));
// Cmpxchg instructions are often used with a subsequent comparison to
// determine whether it succeeded. We can exploit existing control-flow in
// ldrex/strex loops to simplify this, but it needs tidying up.
if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
addPass(createCFGSimplificationPass());
TargetPassConfig::addIRPasses();
// Match interleaved memory accesses to ldN/stN intrinsics.
if (TM->getOptLevel() != CodeGenOpt::None)
addPass(createInterleavedAccessPass(TM));
if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
// Call SeparateConstOffsetFromGEP pass to extract constants within indices
// and lower a GEP with multiple indices to either arithmetic operations or
// multiple GEPs with single index.
addPass(createSeparateConstOffsetFromGEPPass(TM, true));
// Call EarlyCSE pass to find and remove subexpressions in the lowered
// result.
addPass(createEarlyCSEPass());
// Do loop invariant code motion in case part of the lowered result is
// invariant.
addPass(createLICMPass());
}
}
// Pass Pipeline Configuration
bool AArch64PassConfig::addPreISel() {
// Run promote constant before global merge, so that the promoted constants
// get a chance to be merged
if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
addPass(createAArch64PromoteConstantPass());
// FIXME: On AArch64, this depends on the type.
// Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
// and the offset has to be a multiple of the related size in bytes.
if ((TM->getOptLevel() != CodeGenOpt::None &&
EnableGlobalMerge == cl::BOU_UNSET) ||
EnableGlobalMerge == cl::BOU_TRUE) {
bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
(EnableGlobalMerge == cl::BOU_UNSET);
addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
}
if (TM->getOptLevel() != CodeGenOpt::None)
addPass(createAArch64AddressTypePromotionPass());
return false;
}
bool AArch64PassConfig::addInstSelector() {
addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
// For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
// references to _TLS_MODULE_BASE_ as possible.
if (TM->getTargetTriple().isOSBinFormatELF() &&
getOptLevel() != CodeGenOpt::None)
addPass(createAArch64CleanupLocalDynamicTLSPass());
return false;
}
#ifdef LLVM_BUILD_GLOBAL_ISEL
bool AArch64PassConfig::addIRTranslator() {
addPass(new IRTranslator());
return false;
}
#endif
bool AArch64PassConfig::addILPOpts() {
if (EnableCondOpt)
addPass(createAArch64ConditionOptimizerPass());
if (EnableCCMP)
addPass(createAArch64ConditionalCompares());
if (EnableMCR)
addPass(&MachineCombinerID);
if (EnableEarlyIfConversion)
addPass(&EarlyIfConverterID);
if (EnableStPairSuppress)
addPass(createAArch64StorePairSuppressPass());
return true;
}
void AArch64PassConfig::addPreRegAlloc() {
// Use AdvSIMD scalar instructions whenever profitable.
if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
addPass(createAArch64AdvSIMDScalar());
// The AdvSIMD pass may produce copies that can be rewritten to
// be register coaleascer friendly.
addPass(&PeepholeOptimizerID);
}
}
void AArch64PassConfig::addPostRegAlloc() {
// Remove redundant copy instructions.
if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
addPass(createAArch64RedundantCopyEliminationPass());
// Change dead register definitions to refer to the zero register.
if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
addPass(createAArch64DeadRegisterDefinitions());
if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
// Improve performance for some FP/SIMD code for A57.
addPass(createAArch64A57FPLoadBalancing());
}
void AArch64PassConfig::addPreSched2() {
// Expand some pseudo instructions to allow proper scheduling.
addPass(createAArch64ExpandPseudoPass());
// Use load/store pair instructions when possible.
if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
addPass(createAArch64LoadStoreOptimizationPass());
}
void AArch64PassConfig::addPreEmitPass() {
if (EnableA53Fix835769)
addPass(createAArch64A53Fix835769());
// Relax conditional branch instructions if they're otherwise out of
// range of their destination.
addPass(createAArch64BranchRelaxation());
if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
TM->getTargetTriple().isOSBinFormatMachO())
addPass(createAArch64CollectLOHPass());
}
<|endoftext|> |
<commit_before>//===-- SparcV9.cpp - General implementation file for the SparcV9 Target ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Primary interface to machine description for the UltraSPARC. Primarily just
// initializes machine-dependent parameters in class TargetMachine, and creates
// machine-dependent subclasses for classes such as TargetInstrInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/IntrinsicLowering.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Transforms/Scalar.h"
#include "MappingInfo.h"
#include "SparcV9Internals.h"
#include "SparcV9TargetMachine.h"
#include "Support/CommandLine.h"
using namespace llvm;
static const unsigned ImplicitRegUseList[] = { 0 }; /* not used yet */
// Build the MachineInstruction Description Array...
const TargetInstrDescriptor llvm::SparcV9MachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \
ImplicitRegUseList, ImplicitRegUseList },
#include "SparcV9Instr.def"
};
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
namespace {
cl::opt<bool> DisableSched("disable-sched",
cl::desc("Disable local scheduling pass"));
cl::opt<bool> DisablePeephole("disable-peephole",
cl::desc("Disable peephole optimization pass"));
cl::opt<bool> EmitMappingInfo("enable-maps",
cl::desc("Emit LLVM-to-MachineCode mapping info to assembly"));
cl::opt<bool> DisableStrip("disable-strip",
cl::desc("Do not strip the LLVM bytecode in executable"));
}
//===---------------------------------------------------------------------===//
// Code generation/destruction passes
//===---------------------------------------------------------------------===//
namespace {
class ConstructMachineFunction : public FunctionPass {
TargetMachine &Target;
public:
ConstructMachineFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineFunction";
}
bool runOnFunction(Function &F) {
MachineFunction::construct(&F, Target).getInfo()->CalculateArgSize();
return false;
}
};
struct DestroyMachineFunction : public FunctionPass {
const char *getPassName() const { return "DestroyMachineFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
MachineFunction::destruct(&F);
return false;
}
};
FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {
return new ConstructMachineFunction(Target);
}
}
FunctionPass *llvm::createSparcV9MachineCodeDestructionPass() {
return new DestroyMachineFunction();
}
SparcV9TargetMachine::SparcV9TargetMachine(IntrinsicLowering *il)
: TargetMachine("UltraSparcV9-Native", il, false),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
jitInfo(*this) {
}
/// addPassesToEmitAssembly - This method controls the entire code generation
/// process for the ultra sparc.
///
bool
SparcV9TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// The following 3 passes used to be inserted specially by llc.
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// Strip all of the symbols from the bytecode so that it will be smaller...
if (!DisableStrip)
PM.add(createSymbolStrippingPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
//Insert empty stackslots in the stack frame of each function
//so %fp+offset-8 and %fp+offset-16 are empty slots now!
PM.add(createStackSlotsPass(*this));
// Specialize LLVM code for this target machine and then
// run basic dataflow optimizations on LLVM code.
PM.add(createPreSelectionPass(*this));
PM.add(createReassociatePass());
PM.add(createLICMPass());
PM.add(createGCSEPass());
PM.add(createInstructionSelectionPass(*this));
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
PM.add(getRegisterAllocator(*this));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
if (EmitMappingInfo)
PM.add(getMappingInfoAsmPrinterPass(Out));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
PM.add(createAsmPrinterPass(Out, *this));
// FIXME: this pass crashes if added; there is a double deletion going on
// somewhere inside it. This is caught when running the SparcV9 code generator
// on X86, but is typically ignored when running natively.
// Free machine-code IR which is no longer needed:
// PM.add(createSparcV9MachineCodeDestructionPass());
// Emit bytecode to the assembly file into its special section next
if (EmitMappingInfo)
PM.add(createBytecodeAsmPrinterPass(Out));
return false;
}
/// addPassesToJITCompile - This method controls the JIT method of code
/// generation for the UltraSparcV9.
///
void SparcV9JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {
const TargetData &TD = TM.getTargetData();
PM.add(new TargetData("lli", TD.isLittleEndian(), TD.getPointerSize(),
TD.getPointerAlignment(), TD.getDoubleAlignment()));
// Replace malloc and free instructions with library calls.
// Do this after tracing until lli implements these lib calls.
// For now, it will emulate malloc and free internally.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(TM));
// Specialize LLVM code for this target machine and then
// run basic dataflow optimizations on LLVM code.
PM.add(createPreSelectionPass(TM));
PM.add(createReassociatePass());
// FIXME: these passes crash the FunctionPassManager when being added...
//PM.add(createLICMPass());
//PM.add(createGCSEPass());
PM.add(createInstructionSelectionPass(TM));
PM.add(getRegisterAllocator(TM));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(TM));
}
/// allocateSparcV9TargetMachine - Allocate and return a subclass of TargetMachine
/// that implements the SparcV9 backend. (the llvm/CodeGen/SparcV9.h interface)
///
TargetMachine *llvm::allocateSparcV9TargetMachine(const Module &M,
IntrinsicLowering *IL) {
return new SparcV9TargetMachine(IL);
}
<commit_msg>Add this back, as its absence introduces assertions, and it seems to work now that Instructions are annotable again<commit_after>//===-- SparcV9.cpp - General implementation file for the SparcV9 Target ------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Primary interface to machine description for the UltraSPARC. Primarily just
// initializes machine-dependent parameters in class TargetMachine, and creates
// machine-dependent subclasses for classes such as TargetInstrInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/IntrinsicLowering.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Transforms/Scalar.h"
#include "MappingInfo.h"
#include "SparcV9Internals.h"
#include "SparcV9TargetMachine.h"
#include "Support/CommandLine.h"
using namespace llvm;
static const unsigned ImplicitRegUseList[] = { 0 }; /* not used yet */
// Build the MachineInstruction Description Array...
const TargetInstrDescriptor llvm::SparcV9MachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \
ImplicitRegUseList, ImplicitRegUseList },
#include "SparcV9Instr.def"
};
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
namespace {
cl::opt<bool> DisableSched("disable-sched",
cl::desc("Disable local scheduling pass"));
cl::opt<bool> DisablePeephole("disable-peephole",
cl::desc("Disable peephole optimization pass"));
cl::opt<bool> EmitMappingInfo("enable-maps",
cl::desc("Emit LLVM-to-MachineCode mapping info to assembly"));
cl::opt<bool> DisableStrip("disable-strip",
cl::desc("Do not strip the LLVM bytecode in executable"));
}
//===---------------------------------------------------------------------===//
// Code generation/destruction passes
//===---------------------------------------------------------------------===//
namespace {
class ConstructMachineFunction : public FunctionPass {
TargetMachine &Target;
public:
ConstructMachineFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineFunction";
}
bool runOnFunction(Function &F) {
MachineFunction::construct(&F, Target).getInfo()->CalculateArgSize();
return false;
}
};
struct DestroyMachineFunction : public FunctionPass {
const char *getPassName() const { return "DestroyMachineFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
MachineFunction::destruct(&F);
return false;
}
};
FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {
return new ConstructMachineFunction(Target);
}
}
FunctionPass *llvm::createSparcV9MachineCodeDestructionPass() {
return new DestroyMachineFunction();
}
SparcV9TargetMachine::SparcV9TargetMachine(IntrinsicLowering *il)
: TargetMachine("UltraSparcV9-Native", il, false),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
jitInfo(*this) {
}
/// addPassesToEmitAssembly - This method controls the entire code generation
/// process for the ultra sparc.
///
bool
SparcV9TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// The following 3 passes used to be inserted specially by llc.
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// Strip all of the symbols from the bytecode so that it will be smaller...
if (!DisableStrip)
PM.add(createSymbolStrippingPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
//Insert empty stackslots in the stack frame of each function
//so %fp+offset-8 and %fp+offset-16 are empty slots now!
PM.add(createStackSlotsPass(*this));
// Specialize LLVM code for this target machine and then
// run basic dataflow optimizations on LLVM code.
PM.add(createPreSelectionPass(*this));
PM.add(createReassociatePass());
PM.add(createLICMPass());
PM.add(createGCSEPass());
PM.add(createInstructionSelectionPass(*this));
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
PM.add(getRegisterAllocator(*this));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
if (EmitMappingInfo)
PM.add(getMappingInfoAsmPrinterPass(Out));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
PM.add(createAsmPrinterPass(Out, *this));
// Free machine-code IR which is no longer needed:
PM.add(createSparcV9MachineCodeDestructionPass());
// Emit bytecode to the assembly file into its special section next
if (EmitMappingInfo)
PM.add(createBytecodeAsmPrinterPass(Out));
return false;
}
/// addPassesToJITCompile - This method controls the JIT method of code
/// generation for the UltraSparcV9.
///
void SparcV9JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {
const TargetData &TD = TM.getTargetData();
PM.add(new TargetData("lli", TD.isLittleEndian(), TD.getPointerSize(),
TD.getPointerAlignment(), TD.getDoubleAlignment()));
// Replace malloc and free instructions with library calls.
// Do this after tracing until lli implements these lib calls.
// For now, it will emulate malloc and free internally.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(TM));
// Specialize LLVM code for this target machine and then
// run basic dataflow optimizations on LLVM code.
PM.add(createPreSelectionPass(TM));
PM.add(createReassociatePass());
// FIXME: these passes crash the FunctionPassManager when being added...
//PM.add(createLICMPass());
//PM.add(createGCSEPass());
PM.add(createInstructionSelectionPass(TM));
PM.add(getRegisterAllocator(TM));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(TM));
}
/// allocateSparcV9TargetMachine - Allocate and return a subclass of TargetMachine
/// that implements the SparcV9 backend. (the llvm/CodeGen/SparcV9.h interface)
///
TargetMachine *llvm::allocateSparcV9TargetMachine(const Module &M,
IntrinsicLowering *IL) {
return new SparcV9TargetMachine(IL);
}
<|endoftext|> |
<commit_before>// $Id$
//***************************************************************************
// File:
// Sparc.cpp
//
// Purpose:
//
// History:
// 7/15/01 - Vikram Adve - Created
//**************************************************************************/
#include "SparcInternals.h"
#include "llvm/Target/Sparc.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/MachineCodeForMethod.h"
#include "llvm/CodeGen/RegisterAllocation.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
#include "llvm/PassManager.h"
#include <iostream>
using std::cerr;
// Build the MachineInstruction Description Array...
const MachineInstrDescriptor SparcMachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS },
#include "SparcInstr.def"
};
//----------------------------------------------------------------------------
// allocateSparcTargetMachine - Allocate and return a subclass of TargetMachine
// that implements the Sparc backend. (the llvm/CodeGen/Sparc.h interface)
//----------------------------------------------------------------------------
//
TargetMachine *allocateSparcTargetMachine() { return new UltraSparc(); }
//---------------------------------------------------------------------------
// class InsertPrologEpilogCode
//
// Insert SAVE/RESTORE instructions for the method
//
// Insert prolog code at the unique method entry point.
// Insert epilog code at each method exit point.
// InsertPrologEpilog invokes these only if the method is not compiled
// with the leaf method optimization.
//
//---------------------------------------------------------------------------
static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
class InsertPrologEpilogCode : public MethodPass {
TargetMachine &Target;
public:
inline InsertPrologEpilogCode(TargetMachine &T) : Target(T) {}
bool runOnMethod(Method *M) {
MachineCodeForMethod &mcodeInfo = MachineCodeForMethod::get(M);
if (!mcodeInfo.isCompiledAsLeafMethod()) {
InsertPrologCode(M);
InsertEpilogCode(M);
}
return false;
}
void InsertPrologCode(Method *M);
void InsertEpilogCode(Method *M);
};
void InsertPrologEpilogCode::InsertPrologCode(Method* method)
{
BasicBlock* entryBB = method->getEntryNode();
unsigned N = GetInstructionsForProlog(entryBB, Target, minstrVec);
assert(N <= MAX_INSTR_PER_VMINSTR);
MachineCodeForBasicBlock& bbMvec = entryBB->getMachineInstrVec();
bbMvec.insert(bbMvec.begin(), minstrVec, minstrVec+N);
}
void InsertPrologEpilogCode::InsertEpilogCode(Method* method)
{
for (Method::iterator I=method->begin(), E=method->end(); I != E; ++I) {
Instruction *TermInst = (Instruction*)(*I)->getTerminator();
if (TermInst->getOpcode() == Instruction::Ret)
{
BasicBlock* exitBB = *I;
unsigned N = GetInstructionsForEpilog(exitBB, Target, minstrVec);
MachineCodeForBasicBlock& bbMvec = exitBB->getMachineInstrVec();
MachineCodeForInstruction &termMvec =
MachineCodeForInstruction::get(TermInst);
// Remove the NOPs in the delay slots of the return instruction
const MachineInstrInfo &mii = Target.getInstrInfo();
unsigned numNOPs = 0;
while (termMvec.back()->getOpCode() == NOP)
{
assert( termMvec.back() == bbMvec.back());
termMvec.pop_back();
bbMvec.pop_back();
++numNOPs;
}
assert(termMvec.back() == bbMvec.back());
// Check that we found the right number of NOPs and have the right
// number of instructions to replace them.
unsigned ndelays = mii.getNumDelaySlots(termMvec.back()->getOpCode());
assert(numNOPs == ndelays && "Missing NOPs in delay slots?");
assert(N == ndelays && "Cannot use epilog code for delay slots?");
// Append the epilog code to the end of the basic block.
bbMvec.insert(bbMvec.end(), minstrVec, minstrVec+N);
}
}
}
//---------------------------------------------------------------------------
// class UltraSparcFrameInfo
//
// Purpose:
// Interface to stack frame layout info for the UltraSPARC.
// Starting offsets for each area of the stack frame are aligned at
// a multiple of getStackFrameSizeAlignment().
//---------------------------------------------------------------------------
int
UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineCodeForMethod& ,
bool& pos) const
{
pos = false; // static stack area grows downwards
return StaticAreaOffsetFromFP;
}
int
UltraSparcFrameInfo::getRegSpillAreaOffset(MachineCodeForMethod& mcInfo,
bool& pos) const
{
pos = false; // static stack area grows downwards
unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
if (int mod = autoVarsSize % getStackFrameSizeAlignment())
autoVarsSize += (getStackFrameSizeAlignment() - mod);
return StaticAreaOffsetFromFP - autoVarsSize;
}
int
UltraSparcFrameInfo::getTmpAreaOffset(MachineCodeForMethod& mcInfo,
bool& pos) const
{
pos = false; // static stack area grows downwards
unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
unsigned int spillAreaSize = mcInfo.getRegSpillsSize();
int offset = autoVarsSize + spillAreaSize;
if (int mod = offset % getStackFrameSizeAlignment())
offset += (getStackFrameSizeAlignment() - mod);
return StaticAreaOffsetFromFP - offset;
}
int
UltraSparcFrameInfo::getDynamicAreaOffset(MachineCodeForMethod& mcInfo,
bool& pos) const
{
// Dynamic stack area grows downwards starting at top of opt-args area.
// The opt-args, required-args, and register-save areas are empty except
// during calls and traps, so they are shifted downwards on each
// dynamic-size alloca.
pos = false;
unsigned int optArgsSize = mcInfo.getMaxOptionalArgsSize();
int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP;
assert((offset - OFFSET) % getStackFrameSizeAlignment() == 0);
return offset;
}
//---------------------------------------------------------------------------
// class UltraSparcMachine
//
// Purpose:
// Primary interface to machine description for the UltraSPARC.
// Primarily just initializes machine-dependent parameters in
// class TargetMachine, and creates machine-dependent subclasses
// for classes such as MachineInstrInfo.
//
//---------------------------------------------------------------------------
UltraSparc::UltraSparc()
: TargetMachine("UltraSparc-Native"),
instrInfo(*this),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
cacheInfo(*this)
{
optSizeForSubWordData = 4;
minMemOpWordSize = 8;
maxAtomicMemOpWordSize = 8;
}
//===---------------------------------------------------------------------===//
// GenerateCodeForTarget Pass
//
// Native code generation for a specified target.
//===---------------------------------------------------------------------===//
class ConstructMachineCodeForMethod : public MethodPass {
TargetMachine &Target;
public:
inline ConstructMachineCodeForMethod(TargetMachine &T) : Target(T) {}
bool runOnMethod(Method *M) {
MachineCodeForMethod::construct(M, Target);
return false;
}
};
class InstructionSelection : public MethodPass {
TargetMachine &Target;
public:
inline InstructionSelection(TargetMachine &T) : Target(T) {}
bool runOnMethod(Method *M) {
if (SelectInstructionsForMethod(M, Target))
cerr << "Instr selection failed for method " << M->getName() << "\n";
return false;
}
};
struct FreeMachineCodeForMethod : public MethodPass {
static void freeMachineCode(Instruction *I) {
MachineCodeForInstruction::destroy(I);
}
bool runOnMethod(Method *M) {
for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
for (BasicBlock::iterator I = (*MI)->begin(), E = (*MI)->end();
I != E; ++I)
freeMachineCode(*I);
// Don't destruct MachineCodeForMethod - The global printer needs it
//MachineCodeForMethod::destruct(M);
return false;
}
};
// addPassesToEmitAssembly - This method controls the entire code generation
// process for the ultra sparc.
//
void UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) {
// Construct and initialize the MachineCodeForMethod object for this method.
PM.add(new ConstructMachineCodeForMethod(*this));
PM.add(new InstructionSelection(*this));
//PM.add(createInstructionSchedulingWithSSAPass(*this));
PM.add(getRegisterAllocator(*this));
//PM.add(new OptimizeLeafProcedures());
//PM.add(new DeleteFallThroughBranches());
//PM.add(new RemoveChainedBranches()); // should be folded with previous
//PM.add(new RemoveRedundantOps()); // operations with %g0, NOP, etc.
PM.add(new InsertPrologEpilogCode(*this));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Method output and Global value output. This is because method
// output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for methods to be free'd after the
// method has been emitted.
//
PM.add(getMethodAsmPrinterPass(PM, Out));
PM.add(new FreeMachineCodeForMethod()); // Free stuff no longer needed
// Emit Module level assembly after all of the methods have been processed.
PM.add(getModuleAsmPrinterPass(PM, Out));
// Emit bytecode to the sparc assembly file into its special section next
PM.add(getEmitBytecodeToAsmPass(Out));
}
<commit_msg>Bug re-fix: put back MachineCodeForInstruction::get(*I).dropAllReferences(). Also re-enable instr. scheduling pass.<commit_after>// $Id$
//***************************************************************************
// File:
// Sparc.cpp
//
// Purpose:
//
// History:
// 7/15/01 - Vikram Adve - Created
//**************************************************************************/
#include "SparcInternals.h"
#include "llvm/Target/Sparc.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/InstrSelection.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/MachineCodeForMethod.h"
#include "llvm/CodeGen/RegisterAllocation.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
#include "llvm/PassManager.h"
#include <iostream>
using std::cerr;
// Build the MachineInstruction Description Array...
const MachineInstrDescriptor SparcMachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS },
#include "SparcInstr.def"
};
//----------------------------------------------------------------------------
// allocateSparcTargetMachine - Allocate and return a subclass of TargetMachine
// that implements the Sparc backend. (the llvm/CodeGen/Sparc.h interface)
//----------------------------------------------------------------------------
//
TargetMachine *allocateSparcTargetMachine() { return new UltraSparc(); }
//---------------------------------------------------------------------------
// class InsertPrologEpilogCode
//
// Insert SAVE/RESTORE instructions for the method
//
// Insert prolog code at the unique method entry point.
// Insert epilog code at each method exit point.
// InsertPrologEpilog invokes these only if the method is not compiled
// with the leaf method optimization.
//
//---------------------------------------------------------------------------
static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
class InsertPrologEpilogCode : public MethodPass {
TargetMachine &Target;
public:
inline InsertPrologEpilogCode(TargetMachine &T) : Target(T) {}
bool runOnMethod(Method *M) {
MachineCodeForMethod &mcodeInfo = MachineCodeForMethod::get(M);
if (!mcodeInfo.isCompiledAsLeafMethod()) {
InsertPrologCode(M);
InsertEpilogCode(M);
}
return false;
}
void InsertPrologCode(Method *M);
void InsertEpilogCode(Method *M);
};
void InsertPrologEpilogCode::InsertPrologCode(Method* method)
{
BasicBlock* entryBB = method->getEntryNode();
unsigned N = GetInstructionsForProlog(entryBB, Target, minstrVec);
assert(N <= MAX_INSTR_PER_VMINSTR);
MachineCodeForBasicBlock& bbMvec = entryBB->getMachineInstrVec();
bbMvec.insert(bbMvec.begin(), minstrVec, minstrVec+N);
}
void InsertPrologEpilogCode::InsertEpilogCode(Method* method)
{
for (Method::iterator I=method->begin(), E=method->end(); I != E; ++I) {
Instruction *TermInst = (Instruction*)(*I)->getTerminator();
if (TermInst->getOpcode() == Instruction::Ret)
{
BasicBlock* exitBB = *I;
unsigned N = GetInstructionsForEpilog(exitBB, Target, minstrVec);
MachineCodeForBasicBlock& bbMvec = exitBB->getMachineInstrVec();
MachineCodeForInstruction &termMvec =
MachineCodeForInstruction::get(TermInst);
// Remove the NOPs in the delay slots of the return instruction
const MachineInstrInfo &mii = Target.getInstrInfo();
unsigned numNOPs = 0;
while (termMvec.back()->getOpCode() == NOP)
{
assert( termMvec.back() == bbMvec.back());
termMvec.pop_back();
bbMvec.pop_back();
++numNOPs;
}
assert(termMvec.back() == bbMvec.back());
// Check that we found the right number of NOPs and have the right
// number of instructions to replace them.
unsigned ndelays = mii.getNumDelaySlots(termMvec.back()->getOpCode());
assert(numNOPs == ndelays && "Missing NOPs in delay slots?");
assert(N == ndelays && "Cannot use epilog code for delay slots?");
// Append the epilog code to the end of the basic block.
bbMvec.insert(bbMvec.end(), minstrVec, minstrVec+N);
}
}
}
//---------------------------------------------------------------------------
// class UltraSparcFrameInfo
//
// Purpose:
// Interface to stack frame layout info for the UltraSPARC.
// Starting offsets for each area of the stack frame are aligned at
// a multiple of getStackFrameSizeAlignment().
//---------------------------------------------------------------------------
int
UltraSparcFrameInfo::getFirstAutomaticVarOffset(MachineCodeForMethod& ,
bool& pos) const
{
pos = false; // static stack area grows downwards
return StaticAreaOffsetFromFP;
}
int
UltraSparcFrameInfo::getRegSpillAreaOffset(MachineCodeForMethod& mcInfo,
bool& pos) const
{
pos = false; // static stack area grows downwards
unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
if (int mod = autoVarsSize % getStackFrameSizeAlignment())
autoVarsSize += (getStackFrameSizeAlignment() - mod);
return StaticAreaOffsetFromFP - autoVarsSize;
}
int
UltraSparcFrameInfo::getTmpAreaOffset(MachineCodeForMethod& mcInfo,
bool& pos) const
{
pos = false; // static stack area grows downwards
unsigned int autoVarsSize = mcInfo.getAutomaticVarsSize();
unsigned int spillAreaSize = mcInfo.getRegSpillsSize();
int offset = autoVarsSize + spillAreaSize;
if (int mod = offset % getStackFrameSizeAlignment())
offset += (getStackFrameSizeAlignment() - mod);
return StaticAreaOffsetFromFP - offset;
}
int
UltraSparcFrameInfo::getDynamicAreaOffset(MachineCodeForMethod& mcInfo,
bool& pos) const
{
// Dynamic stack area grows downwards starting at top of opt-args area.
// The opt-args, required-args, and register-save areas are empty except
// during calls and traps, so they are shifted downwards on each
// dynamic-size alloca.
pos = false;
unsigned int optArgsSize = mcInfo.getMaxOptionalArgsSize();
int offset = optArgsSize + FirstOptionalOutgoingArgOffsetFromSP;
assert((offset - OFFSET) % getStackFrameSizeAlignment() == 0);
return offset;
}
//---------------------------------------------------------------------------
// class UltraSparcMachine
//
// Purpose:
// Primary interface to machine description for the UltraSPARC.
// Primarily just initializes machine-dependent parameters in
// class TargetMachine, and creates machine-dependent subclasses
// for classes such as MachineInstrInfo.
//
//---------------------------------------------------------------------------
UltraSparc::UltraSparc()
: TargetMachine("UltraSparc-Native"),
instrInfo(*this),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
cacheInfo(*this)
{
optSizeForSubWordData = 4;
minMemOpWordSize = 8;
maxAtomicMemOpWordSize = 8;
}
//===---------------------------------------------------------------------===//
// GenerateCodeForTarget Pass
//
// Native code generation for a specified target.
//===---------------------------------------------------------------------===//
class ConstructMachineCodeForMethod : public MethodPass {
TargetMachine &Target;
public:
inline ConstructMachineCodeForMethod(TargetMachine &T) : Target(T) {}
bool runOnMethod(Method *M) {
MachineCodeForMethod::construct(M, Target);
return false;
}
};
class InstructionSelection : public MethodPass {
TargetMachine &Target;
public:
inline InstructionSelection(TargetMachine &T) : Target(T) {}
bool runOnMethod(Method *M) {
if (SelectInstructionsForMethod(M, Target))
cerr << "Instr selection failed for method " << M->getName() << "\n";
return false;
}
};
struct FreeMachineCodeForMethod : public MethodPass {
static void freeMachineCode(Instruction *I) {
MachineCodeForInstruction::destroy(I);
}
bool runOnMethod(Method *M) {
for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
for (BasicBlock::iterator I = (*MI)->begin(), E = (*MI)->end();
I != E; ++I)
MachineCodeForInstruction::get(*I).dropAllReferences();
for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
for (BasicBlock::iterator I = (*MI)->begin(), E = (*MI)->end();
I != E; ++I)
freeMachineCode(*I);
return false;
}
};
// addPassesToEmitAssembly - This method controls the entire code generation
// process for the ultra sparc.
//
void UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) {
// Construct and initialize the MachineCodeForMethod object for this method.
PM.add(new ConstructMachineCodeForMethod(*this));
PM.add(new InstructionSelection(*this));
PM.add(createInstructionSchedulingWithSSAPass(*this));
PM.add(getRegisterAllocator(*this));
//PM.add(new OptimizeLeafProcedures());
//PM.add(new DeleteFallThroughBranches());
//PM.add(new RemoveChainedBranches()); // should be folded with previous
//PM.add(new RemoveRedundantOps()); // operations with %g0, NOP, etc.
PM.add(new InsertPrologEpilogCode(*this));
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Method output and Global value output. This is because method
// output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for methods to be free'd after the
// method has been emitted.
//
PM.add(getMethodAsmPrinterPass(PM, Out));
PM.add(new FreeMachineCodeForMethod()); // Free stuff no longer needed
// Emit Module level assembly after all of the methods have been processed.
PM.add(getModuleAsmPrinterPass(PM, Out));
// Emit bytecode to the sparc assembly file into its special section next
PM.add(getEmitBytecodeToAsmPass(Out));
}
<|endoftext|> |
<commit_before>//===- NodeImpl.cpp - Implement the data structure analysis nodes ---------===//
//
// Implement the LLVM data structure analysis library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/BasicBlock.h"
#include "llvm/iMemory.h"
#include "llvm/iOther.h"
#include "llvm/Assembly/Writer.h"
#include "Support/STLExtras.h"
#include <algorithm>
#include <sstream>
//===----------------------------------------------------------------------===//
// DSNode Class Implementation
//
static void MapPVS(PointerValSet &PVSOut, const PointerValSet &PVSIn,
map<const DSNode*, DSNode*> &NodeMap) {
assert(PVSOut.empty() && "Value set already initialized!");
for (unsigned i = 0, e = PVSIn.size(); i != e; ++i)
PVSOut.add(PointerVal(NodeMap[PVSIn[i].Node], PVSIn[i].Index));
}
unsigned countPointerFields(const Type *Ty) {
switch (Ty->getPrimitiveID()) {
case Type::StructTyID: {
const StructType *ST = cast<StructType>(Ty);
unsigned Sum = 0;
for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i)
Sum += countPointerFields(ST->getContainedType(i));
return Sum;
}
case Type::ArrayTyID:
// All array elements are folded together...
return countPointerFields(cast<ArrayType>(Ty)->getElementType());
case Type::PointerTyID:
return 1;
default: // Some other type, just treat it like a scalar
return 0;
}
}
DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
// Create field entries for all of the values in this type...
FieldLinks.resize(countPointerFields(getType()));
}
void DSNode::removeReferrer(PointerValSet *PVS) {
vector<PointerValSet*>::iterator I = std::find(Referrers.begin(),
Referrers.end(), PVS);
assert(I != Referrers.end() && "PVS not pointing to node!");
Referrers.erase(I);
}
static void replaceIn(std::string &S, char From, const std::string &To) {
for (unsigned i = 0; i < S.size(); )
if (S[i] == From) {
S.replace(S.begin()+i, S.begin()+i+1,
To.begin(), To.end());
i += To.size();
} else {
++i;
}
}
static void writeEdges(std::ostream &O, const void *SrcNode,
const char *SrcNodePortName, int SrcNodeIdx,
const PointerValSet &VS, const string &EdgeAttr = "") {
for (unsigned j = 0, je = VS.size(); j != je; ++j) {
O << "\t\tNode" << SrcNode << SrcNodePortName;
if (SrcNodeIdx != -1) O << SrcNodeIdx;
O << " -> Node" << VS[j].Node;
if (VS[j].Index)
O << ":g" << VS[j].Index;
if (!EdgeAttr.empty())
O << "[" << EdgeAttr << "]";
O << ";\n";
}
}
static string escapeLabel(const string &In) {
string Label(In);
replaceIn(Label, '\\', "\\\\\\\\"); // Escape caption...
replaceIn(Label, ' ', "\\ ");
replaceIn(Label, '{', "\\{");
replaceIn(Label, '}', "\\}");
return Label;
}
void DSNode::print(std::ostream &O) const {
string Caption = escapeLabel(getCaption());
O << "\t\tNode" << (void*)this << " [ label =\"{" << Caption;
const vector<PointerValSet> *Links = getAuxLinks();
if (Links && !Links->empty()) {
O << "|{";
for (unsigned i = 0; i < Links->size(); ++i) {
if (i) O << "|";
O << "<f" << i << ">";
}
O << "}";
}
if (!FieldLinks.empty()) {
O << "|{";
for (unsigned i = 0; i < FieldLinks.size(); ++i) {
if (i) O << "|";
O << "<g" << i << ">";
}
O << "}";
}
O << "}\"];\n";
if (Links)
for (unsigned i = 0; i < Links->size(); ++i)
writeEdges(O, this, ":f", i, (*Links)[i]);
for (unsigned i = 0; i < FieldLinks.size(); ++i)
writeEdges(O, this, ":g", i, FieldLinks[i]);
}
void DSNode::mapNode(map<const DSNode*, DSNode*> &NodeMap, const DSNode *Old) {
assert(FieldLinks.size() == Old->FieldLinks.size() &&
"Cloned nodes do not have the same number of links!");
for (unsigned j = 0, je = FieldLinks.size(); j != je; ++j)
MapPVS(FieldLinks[j], Old->FieldLinks[j], NodeMap);
}
NewDSNode::NewDSNode(AllocationInst *V)
: DSNode(NewNode, V->getType()->getElementType()), Allocation(V) {
}
string NewDSNode::getCaption() const {
stringstream OS;
if (isa<MallocInst>(Allocation))
OS << "new ";
else
OS << "alloca ";
WriteTypeSymbolic(OS, getType(),
Allocation->getParent()->getParent()->getParent());
if (Allocation->isArrayAllocation())
OS << "[ ]";
return OS.str();
}
GlobalDSNode::GlobalDSNode(GlobalValue *V)
: DSNode(GlobalNode, V->getType()->getElementType()), Val(V) {
}
string GlobalDSNode::getCaption() const {
stringstream OS;
WriteTypeSymbolic(OS, getType(), Val->getParent());
return "global " + OS.str();
}
ShadowDSNode::ShadowDSNode(DSNode *P, Module *M)
: DSNode(ShadowNode, cast<PointerType>(P->getType())->getElementType()) {
Parent = P;
Mod = M;
ShadowParent = 0;
}
ShadowDSNode::ShadowDSNode(const Type *Ty, Module *M, ShadowDSNode *ShadParent)
: DSNode(ShadowNode, Ty) {
Parent = 0;
Mod = M;
ShadowParent = ShadParent;
}
std::string ShadowDSNode::getCaption() const {
stringstream OS;
WriteTypeSymbolic(OS, getType(), Mod);
return "shadow " + OS.str();
}
void ShadowDSNode::mapNode(map<const DSNode*, DSNode*> &NodeMap,
const DSNode *O) {
const ShadowDSNode *Old = (ShadowDSNode*)O;
DSNode::mapNode(NodeMap, Old); // Map base portions first...
// Map our SynthNodes...
assert(SynthNodes.empty() && "Synthnodes already mapped?");
SynthNodes.reserve(Old->SynthNodes.size());
for (unsigned i = 0, e = Old->SynthNodes.size(); i != e; ++i)
SynthNodes.push_back(std::make_pair(Old->SynthNodes[i].first,
(ShadowDSNode*)NodeMap[Old->SynthNodes[i].second]));
}
CallDSNode::CallDSNode(CallInst *ci) : DSNode(CallNode, ci->getType()), CI(ci) {
unsigned NumPtrs = 0;
if (!isa<Function>(ci->getOperand(0)))
NumPtrs++; // Include the method pointer...
for (unsigned i = 1, e = ci->getNumOperands(); i != e; ++i)
if (isa<PointerType>(ci->getOperand(i)->getType()))
NumPtrs++;
ArgLinks.resize(NumPtrs);
}
string CallDSNode::getCaption() const {
stringstream OS;
if (const Function *CM = CI->getCalledFunction())
OS << "call " << CM->getName();
else
OS << "call <indirect>";
OS << "|Ret: ";
WriteTypeSymbolic(OS, getType(),
CI->getParent()->getParent()->getParent());
return OS.str();
}
void CallDSNode::mapNode(map<const DSNode*, DSNode*> &NodeMap,
const DSNode *O) {
const CallDSNode *Old = (CallDSNode*)O;
DSNode::mapNode(NodeMap, Old); // Map base portions first...
assert(ArgLinks.size() == Old->ArgLinks.size() && "# Arguments changed!?");
for (unsigned i = 0, e = Old->ArgLinks.size(); i != e; ++i)
MapPVS(ArgLinks[i], Old->ArgLinks[i], NodeMap);
}
ArgDSNode::ArgDSNode(FunctionArgument *FA)
: DSNode(ArgNode, FA->getType()), FuncArg(FA) {
}
string ArgDSNode::getCaption() const {
stringstream OS;
OS << "arg %" << FuncArg->getName() << "|Ty: ";
WriteTypeSymbolic(OS, getType(), FuncArg->getParent()->getParent());
return OS.str();
}
void FunctionDSGraph::printFunction(std::ostream &O,
const char *Label) const {
O << "\tsubgraph cluster_" << Label << "_Function" << (void*)this << " {\n";
O << "\t\tlabel=\"" << Label << " Function\\ " << Func->getName() << "\";\n";
for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Nodes[i]->print(O);
for (unsigned i = 0, e = ShadowNodes.size(); i != e; ++i)
ShadowNodes[i]->print(O);
if (RetNode.size()) {
O << "\t\tNode" << (void*)this << Label
<< " [shape=\"ellipse\", label=\"Returns\"];\n";
writeEdges(O, this, Label, -1, RetNode);
}
O << "\n";
for (std::map<Value*, PointerValSet>::const_iterator I = ValueMap.begin(),
E = ValueMap.end(); I != E; ++I) {
if (I->second.size()) { // Only output nodes with edges...
stringstream OS;
WriteTypeSymbolic(OS, I->first->getType(), Func->getParent());
// Create node for I->first
O << "\t\tNode" << (void*)I->first << Label << " [shape=\"box\", label=\""
<< escapeLabel(OS.str()) << "\\n%" << escapeLabel(I->first->getName())
<< "\",fontsize=\"12.0\",color=\"gray70\"];\n";
// add edges from I->first to all pointers in I->second
writeEdges(O, I->first, Label, -1, I->second,
"weight=\"0.9\",color=\"gray70\"");
}
}
O << "\t}\n";
}
// Copy constructor - Since we copy the nodes over, we have to be sure to go
// through and fix pointers to point into the new graph instead of into the old
// graph...
//
FunctionDSGraph::FunctionDSGraph(const FunctionDSGraph &DSG) : Func(DSG.Func) {
RetNode = cloneFunctionIntoSelf(DSG, true);
}
// cloneFunctionIntoSelf - Clone the specified method graph into the current
// method graph, returning the Return's set of the graph. If ValueMap is set
// to true, the ValueMap of the function is cloned into this function as well
// as the data structure graph itself.
//
PointerValSet FunctionDSGraph::cloneFunctionIntoSelf(const FunctionDSGraph &DSG,
bool CloneValueMap) {
map<const DSNode*, DSNode*> NodeMap; // Map from old graph to new graph...
unsigned StartSize = Nodes.size(); // We probably already have nodes...
Nodes.reserve(StartSize+DSG.Nodes.size());
unsigned StartShadowSize = ShadowNodes.size();
ShadowNodes.reserve(StartShadowSize+DSG.ShadowNodes.size());
// Clone all of the nodes, keeping track of the mapping...
for (unsigned i = 0, e = DSG.Nodes.size(); i != e; ++i)
Nodes.push_back(NodeMap[DSG.Nodes[i]] = DSG.Nodes[i]->clone());
// Clone all of the shadow nodes similarly...
for (unsigned i = 0, e = DSG.ShadowNodes.size(); i != e; ++i)
ShadowNodes.push_back(cast<ShadowDSNode>(NodeMap[DSG.ShadowNodes[i]] = DSG.ShadowNodes[i]->clone()));
// Convert all of the links over in the nodes now that the map has been filled
// in all the way...
//
for (unsigned i = 0, e = DSG.Nodes.size(); i != e; ++i)
Nodes[i+StartSize]->mapNode(NodeMap, DSG.Nodes[i]);
for (unsigned i = 0, e = DSG.ShadowNodes.size(); i != e; ++i)
ShadowNodes[i+StartShadowSize]->mapNode(NodeMap, DSG.ShadowNodes[i]);
if (CloneValueMap) {
// Convert value map... the values themselves stay the same, just the nodes
// have to change...
//
for (std::map<Value*,PointerValSet>::const_iterator I =DSG.ValueMap.begin(),
E = DSG.ValueMap.end(); I != E; ++I)
MapPVS(ValueMap[I->first], I->second, NodeMap);
}
// Convert over return node...
PointerValSet RetVals;
MapPVS(RetVals, DSG.RetNode, NodeMap);
return RetVals;
}
FunctionDSGraph::~FunctionDSGraph() {
RetNode.clear();
ValueMap.clear();
for_each(Nodes.begin(), Nodes.end(), mem_fun(&DSNode::dropAllReferences));
for_each(ShadowNodes.begin(), ShadowNodes.end(),
mem_fun(&DSNode::dropAllReferences));
for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
for_each(ShadowNodes.begin(), ShadowNodes.end(), deleter<DSNode>);
}
<commit_msg>Fix long line<commit_after>//===- NodeImpl.cpp - Implement the data structure analysis nodes ---------===//
//
// Implement the LLVM data structure analysis library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/DataStructure.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/BasicBlock.h"
#include "llvm/iMemory.h"
#include "llvm/iOther.h"
#include "llvm/Assembly/Writer.h"
#include "Support/STLExtras.h"
#include <algorithm>
#include <sstream>
//===----------------------------------------------------------------------===//
// DSNode Class Implementation
//
static void MapPVS(PointerValSet &PVSOut, const PointerValSet &PVSIn,
map<const DSNode*, DSNode*> &NodeMap) {
assert(PVSOut.empty() && "Value set already initialized!");
for (unsigned i = 0, e = PVSIn.size(); i != e; ++i)
PVSOut.add(PointerVal(NodeMap[PVSIn[i].Node], PVSIn[i].Index));
}
unsigned countPointerFields(const Type *Ty) {
switch (Ty->getPrimitiveID()) {
case Type::StructTyID: {
const StructType *ST = cast<StructType>(Ty);
unsigned Sum = 0;
for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i)
Sum += countPointerFields(ST->getContainedType(i));
return Sum;
}
case Type::ArrayTyID:
// All array elements are folded together...
return countPointerFields(cast<ArrayType>(Ty)->getElementType());
case Type::PointerTyID:
return 1;
default: // Some other type, just treat it like a scalar
return 0;
}
}
DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
// Create field entries for all of the values in this type...
FieldLinks.resize(countPointerFields(getType()));
}
void DSNode::removeReferrer(PointerValSet *PVS) {
vector<PointerValSet*>::iterator I = std::find(Referrers.begin(),
Referrers.end(), PVS);
assert(I != Referrers.end() && "PVS not pointing to node!");
Referrers.erase(I);
}
static void replaceIn(std::string &S, char From, const std::string &To) {
for (unsigned i = 0; i < S.size(); )
if (S[i] == From) {
S.replace(S.begin()+i, S.begin()+i+1,
To.begin(), To.end());
i += To.size();
} else {
++i;
}
}
static void writeEdges(std::ostream &O, const void *SrcNode,
const char *SrcNodePortName, int SrcNodeIdx,
const PointerValSet &VS, const string &EdgeAttr = "") {
for (unsigned j = 0, je = VS.size(); j != je; ++j) {
O << "\t\tNode" << SrcNode << SrcNodePortName;
if (SrcNodeIdx != -1) O << SrcNodeIdx;
O << " -> Node" << VS[j].Node;
if (VS[j].Index)
O << ":g" << VS[j].Index;
if (!EdgeAttr.empty())
O << "[" << EdgeAttr << "]";
O << ";\n";
}
}
static string escapeLabel(const string &In) {
string Label(In);
replaceIn(Label, '\\', "\\\\\\\\"); // Escape caption...
replaceIn(Label, ' ', "\\ ");
replaceIn(Label, '{', "\\{");
replaceIn(Label, '}', "\\}");
return Label;
}
void DSNode::print(std::ostream &O) const {
string Caption = escapeLabel(getCaption());
O << "\t\tNode" << (void*)this << " [ label =\"{" << Caption;
const vector<PointerValSet> *Links = getAuxLinks();
if (Links && !Links->empty()) {
O << "|{";
for (unsigned i = 0; i < Links->size(); ++i) {
if (i) O << "|";
O << "<f" << i << ">";
}
O << "}";
}
if (!FieldLinks.empty()) {
O << "|{";
for (unsigned i = 0; i < FieldLinks.size(); ++i) {
if (i) O << "|";
O << "<g" << i << ">";
}
O << "}";
}
O << "}\"];\n";
if (Links)
for (unsigned i = 0; i < Links->size(); ++i)
writeEdges(O, this, ":f", i, (*Links)[i]);
for (unsigned i = 0; i < FieldLinks.size(); ++i)
writeEdges(O, this, ":g", i, FieldLinks[i]);
}
void DSNode::mapNode(map<const DSNode*, DSNode*> &NodeMap, const DSNode *Old) {
assert(FieldLinks.size() == Old->FieldLinks.size() &&
"Cloned nodes do not have the same number of links!");
for (unsigned j = 0, je = FieldLinks.size(); j != je; ++j)
MapPVS(FieldLinks[j], Old->FieldLinks[j], NodeMap);
}
NewDSNode::NewDSNode(AllocationInst *V)
: DSNode(NewNode, V->getType()->getElementType()), Allocation(V) {
}
string NewDSNode::getCaption() const {
stringstream OS;
if (isa<MallocInst>(Allocation))
OS << "new ";
else
OS << "alloca ";
WriteTypeSymbolic(OS, getType(),
Allocation->getParent()->getParent()->getParent());
if (Allocation->isArrayAllocation())
OS << "[ ]";
return OS.str();
}
GlobalDSNode::GlobalDSNode(GlobalValue *V)
: DSNode(GlobalNode, V->getType()->getElementType()), Val(V) {
}
string GlobalDSNode::getCaption() const {
stringstream OS;
WriteTypeSymbolic(OS, getType(), Val->getParent());
return "global " + OS.str();
}
ShadowDSNode::ShadowDSNode(DSNode *P, Module *M)
: DSNode(ShadowNode, cast<PointerType>(P->getType())->getElementType()) {
Parent = P;
Mod = M;
ShadowParent = 0;
}
ShadowDSNode::ShadowDSNode(const Type *Ty, Module *M, ShadowDSNode *ShadParent)
: DSNode(ShadowNode, Ty) {
Parent = 0;
Mod = M;
ShadowParent = ShadParent;
}
std::string ShadowDSNode::getCaption() const {
stringstream OS;
WriteTypeSymbolic(OS, getType(), Mod);
return "shadow " + OS.str();
}
void ShadowDSNode::mapNode(map<const DSNode*, DSNode*> &NodeMap,
const DSNode *O) {
const ShadowDSNode *Old = (ShadowDSNode*)O;
DSNode::mapNode(NodeMap, Old); // Map base portions first...
// Map our SynthNodes...
assert(SynthNodes.empty() && "Synthnodes already mapped?");
SynthNodes.reserve(Old->SynthNodes.size());
for (unsigned i = 0, e = Old->SynthNodes.size(); i != e; ++i)
SynthNodes.push_back(std::make_pair(Old->SynthNodes[i].first,
(ShadowDSNode*)NodeMap[Old->SynthNodes[i].second]));
}
CallDSNode::CallDSNode(CallInst *ci) : DSNode(CallNode, ci->getType()), CI(ci) {
unsigned NumPtrs = 0;
if (!isa<Function>(ci->getOperand(0)))
NumPtrs++; // Include the method pointer...
for (unsigned i = 1, e = ci->getNumOperands(); i != e; ++i)
if (isa<PointerType>(ci->getOperand(i)->getType()))
NumPtrs++;
ArgLinks.resize(NumPtrs);
}
string CallDSNode::getCaption() const {
stringstream OS;
if (const Function *CM = CI->getCalledFunction())
OS << "call " << CM->getName();
else
OS << "call <indirect>";
OS << "|Ret: ";
WriteTypeSymbolic(OS, getType(),
CI->getParent()->getParent()->getParent());
return OS.str();
}
void CallDSNode::mapNode(map<const DSNode*, DSNode*> &NodeMap,
const DSNode *O) {
const CallDSNode *Old = (CallDSNode*)O;
DSNode::mapNode(NodeMap, Old); // Map base portions first...
assert(ArgLinks.size() == Old->ArgLinks.size() && "# Arguments changed!?");
for (unsigned i = 0, e = Old->ArgLinks.size(); i != e; ++i)
MapPVS(ArgLinks[i], Old->ArgLinks[i], NodeMap);
}
ArgDSNode::ArgDSNode(FunctionArgument *FA)
: DSNode(ArgNode, FA->getType()), FuncArg(FA) {
}
string ArgDSNode::getCaption() const {
stringstream OS;
OS << "arg %" << FuncArg->getName() << "|Ty: ";
WriteTypeSymbolic(OS, getType(), FuncArg->getParent()->getParent());
return OS.str();
}
void FunctionDSGraph::printFunction(std::ostream &O,
const char *Label) const {
O << "\tsubgraph cluster_" << Label << "_Function" << (void*)this << " {\n";
O << "\t\tlabel=\"" << Label << " Function\\ " << Func->getName() << "\";\n";
for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Nodes[i]->print(O);
for (unsigned i = 0, e = ShadowNodes.size(); i != e; ++i)
ShadowNodes[i]->print(O);
if (RetNode.size()) {
O << "\t\tNode" << (void*)this << Label
<< " [shape=\"ellipse\", label=\"Returns\"];\n";
writeEdges(O, this, Label, -1, RetNode);
}
O << "\n";
for (std::map<Value*, PointerValSet>::const_iterator I = ValueMap.begin(),
E = ValueMap.end(); I != E; ++I) {
if (I->second.size()) { // Only output nodes with edges...
stringstream OS;
WriteTypeSymbolic(OS, I->first->getType(), Func->getParent());
// Create node for I->first
O << "\t\tNode" << (void*)I->first << Label << " [shape=\"box\", label=\""
<< escapeLabel(OS.str()) << "\\n%" << escapeLabel(I->first->getName())
<< "\",fontsize=\"12.0\",color=\"gray70\"];\n";
// add edges from I->first to all pointers in I->second
writeEdges(O, I->first, Label, -1, I->second,
"weight=\"0.9\",color=\"gray70\"");
}
}
O << "\t}\n";
}
// Copy constructor - Since we copy the nodes over, we have to be sure to go
// through and fix pointers to point into the new graph instead of into the old
// graph...
//
FunctionDSGraph::FunctionDSGraph(const FunctionDSGraph &DSG) : Func(DSG.Func) {
RetNode = cloneFunctionIntoSelf(DSG, true);
}
// cloneFunctionIntoSelf - Clone the specified method graph into the current
// method graph, returning the Return's set of the graph. If ValueMap is set
// to true, the ValueMap of the function is cloned into this function as well
// as the data structure graph itself.
//
PointerValSet FunctionDSGraph::cloneFunctionIntoSelf(const FunctionDSGraph &DSG,
bool CloneValueMap) {
map<const DSNode*, DSNode*> NodeMap; // Map from old graph to new graph...
unsigned StartSize = Nodes.size(); // We probably already have nodes...
Nodes.reserve(StartSize+DSG.Nodes.size());
unsigned StartShadowSize = ShadowNodes.size();
ShadowNodes.reserve(StartShadowSize+DSG.ShadowNodes.size());
// Clone all of the nodes, keeping track of the mapping...
for (unsigned i = 0, e = DSG.Nodes.size(); i != e; ++i)
Nodes.push_back(NodeMap[DSG.Nodes[i]] = DSG.Nodes[i]->clone());
// Clone all of the shadow nodes similarly...
for (unsigned i = 0, e = DSG.ShadowNodes.size(); i != e; ++i) {
ShadowDSNode *New = cast<ShadowDSNode>(DSG.ShadowNodes[i]->clone());
NodeMap[DSG.ShadowNodes[i]] = New;
ShadowNodes.push_back(New);
}
// Convert all of the links over in the nodes now that the map has been filled
// in all the way...
//
for (unsigned i = 0, e = DSG.Nodes.size(); i != e; ++i)
Nodes[i+StartSize]->mapNode(NodeMap, DSG.Nodes[i]);
for (unsigned i = 0, e = DSG.ShadowNodes.size(); i != e; ++i)
ShadowNodes[i+StartShadowSize]->mapNode(NodeMap, DSG.ShadowNodes[i]);
if (CloneValueMap) {
// Convert value map... the values themselves stay the same, just the nodes
// have to change...
//
for (std::map<Value*,PointerValSet>::const_iterator I =DSG.ValueMap.begin(),
E = DSG.ValueMap.end(); I != E; ++I)
MapPVS(ValueMap[I->first], I->second, NodeMap);
}
// Convert over return node...
PointerValSet RetVals;
MapPVS(RetVals, DSG.RetNode, NodeMap);
return RetVals;
}
FunctionDSGraph::~FunctionDSGraph() {
RetNode.clear();
ValueMap.clear();
for_each(Nodes.begin(), Nodes.end(), mem_fun(&DSNode::dropAllReferences));
for_each(ShadowNodes.begin(), ShadowNodes.end(),
mem_fun(&DSNode::dropAllReferences));
for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
for_each(ShadowNodes.begin(), ShadowNodes.end(), deleter<DSNode>);
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef Method_Solver_H
#define Method_Solver_H
#include "Spirit_Defines.h"
#include <Spirit/Simulation.h>
#include <data/Parameters_Method.hpp>
#include <data/Spin_System_Chain.hpp>
#include <data/Parameters_Method.hpp>
#include <engine/Method.hpp>
#include <engine/Vectormath.hpp>
#include <engine/Manifoldmath.hpp>
#include <engine/Solver_Kernels.hpp>
#include <utility/Timing.hpp>
#include <utility/Logging.hpp>
#include <utility/Constants.hpp>
#include <deque>
#include <fstream>
#include <map>
#include <sstream>
#include <iomanip>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <fmt/format.h>
namespace Engine
{
enum class Solver
{
None = -1,
SIB = Solver_SIB,
Heun = Solver_Heun,
Depondt = Solver_Depondt,
RungeKutta4 = Solver_RungeKutta4,
LBFGS_OSO = Solver_LBFGS_OSO,
LBFGS_Atlas = Solver_LBFGS_Atlas,
VP = Solver_VP,
VP_OSO = Solver_VP_OSO
};
/*
Base Class for Solver-based Simulation/Calculation Methods.
It is templated to allow a flexible choice of Solver to iterate the systems.
*/
template<Solver solver>
class Method_Solver : public Method
{
public:
// Constructor to be used in derived classes
Method_Solver(std::shared_ptr<Data::Parameters_Method> parameters, int idx_img, int idx_chain) :
Method(parameters, idx_img, idx_chain)
{
}
// // `Iterate` uses the `Solver_Iteration` function to evolve given systems according to the
// // `Calculate_Force` implementation of the Method-Subclass.
// // It iterates until: the maximum number of iterations is reached or the maximum
// // walltime is reaches or the force has converged or a file called `STOP` is found
// // or the calculation is stopped externally (via the API).
// virtual void Iterate() override;
// Solver name as string
virtual std::string SolverName() override;
virtual std::string SolverFullName() override;
// Iteration represents one iteration of a certain Solver
virtual void Iteration() override;
protected:
// Prepare random numbers for thermal fields, if needed
virtual void Prepare_Thermal_Field() {}
// Calculate Forces onto Systems
// This is currently overridden by methods to specify how the forces on a set of configurations should be
// calculated. This function is used in `the Solver_...` functions.
// TODO: maybe rename to separate from deterministic and stochastic force functions
virtual void Calculate_Force(const std::vector<std::shared_ptr<vectorfield>> & configurations, std::vector<vectorfield> & forces)
{
Log(Utility::Log_Level::Error, Utility::Log_Sender::All, "Tried to use Method_Solver::Calculate_Force() of the Method_Solver class!", this->idx_image, this->idx_chain);
}
// Calculate virtual Forces onto Systems (can be precession and damping forces, correctly scaled)
// Calculate the effective force on a configuration. It is a combination of
// precession and damping terms for the Hamiltonian, spin currents and
// temperature. This function is used in `the Solver_...` functions.
// Default implementation: direct minimization
virtual void Calculate_Force_Virtual(
const std::vector<std::shared_ptr<vectorfield>> & configurations,
const std::vector<vectorfield> & forces,
std::vector<vectorfield> & forces_virtual)
{
// Not Implemented!
Log(Utility::Log_Level::Error, Utility::Log_Sender::All, "Tried to use Method_Solver::Calculate_Force_Virtual() of the Method_Solver class!", this->idx_image, this->idx_chain);
}
// Calculate maximum of absolute values of force components for a spin configuration
virtual scalar Force_on_Image_MaxAbsComponent(const vectorfield & image, vectorfield & force) final;
// Calculate maximum torque for a spin configuration
virtual scalar MaxTorque_on_Image(const vectorfield & image, vectorfield & force) final;
// ...
// virtual bool Iterations_Allowed() override;
// Check if the forces are converged
virtual bool Converged();
// Check if any stop criteria were encountered
bool ContinueIterating() override
{
return Method::ContinueIterating() && !this->Converged();
}
// Initialise contains the initialisations of arrays etc. for a certain solver
virtual void Initialize() override;
virtual void Finalize() override;
// Log message blocks
virtual void Message_Start() override;
virtual void Message_Step() override;
virtual void Message_End() override;
//////////// DEPONDT ////////////////////////////////////////////////////////////
// Temporaries for virtual forces
std::vector<vectorfield> rotationaxis;
std::vector<scalarfield> forces_virtual_norm;
// Preccession angle
scalarfield angle;
//////////// LBFGS ////////////////////////////////////////////////////////////
// General
int n_lbfgs_memory;
int local_iter;
scalar maxmove;
scalarfield rho;
scalarfield alpha;
// Atlas coords
std::vector<field<vector2field>> atlas_updates;
std::vector<field<vector2field>> grad_atlas_updates;
std::vector<scalarfield> atlas_coords3;
std::vector<vector2field> atlas_directions;
std::vector<vector2field> atlas_residuals;
std::vector<vector2field> atlas_residuals_last;
std::vector<vector2field> atlas_q_vec;
// OSO
std::vector<field<vectorfield>> delta_a;
std::vector<field<vectorfield>> delta_grad;
std::vector<vectorfield> searchdir;
std::vector<vectorfield> grad;
std::vector<vectorfield> grad_pr;
std::vector<vectorfield> q_vec;
// buffer variables for checking convergence for solver and Newton-Raphson
// std::vector<scalarfield> r_dot_d, dda2;
//////////// VP ///////////////////////////////////////////////////////////////
// "Mass of our particle" which we accelerate
scalar m = 1.0;
// Force in previous step [noi][nos]
std::vector<vectorfield> forces_previous;
// Velocity in previous step [noi][nos]
std::vector<vectorfield> velocities_previous;
// Velocity used in the Steps [noi][nos]
std::vector<vectorfield> velocities;
// Projection of velocities onto the forces [noi]
std::vector<scalar> projection;
// |force|^2
std::vector<scalar> force_norm2;
// Temporary Spins arrays
vectorfield temp1, temp2;
// Actual Forces on the configurations
std::vector<vectorfield> forces;
std::vector<vectorfield> forces_predictor;
// Virtual Forces used in the Steps
std::vector<vectorfield> forces_virtual;
std::vector<vectorfield> forces_virtual_predictor;
// RK 4
std::vector<std::shared_ptr<vectorfield>> configurations_k1;
std::vector<std::shared_ptr<vectorfield>> configurations_k2;
std::vector<std::shared_ptr<vectorfield>> configurations_k3;
std::vector<std::shared_ptr<vectorfield>> configurations_k4;
// Random vector array
vectorfield xi;
// Pointers to Configurations (for Solver methods)
std::vector<std::shared_ptr<vectorfield>> configurations;
std::vector<std::shared_ptr<vectorfield>> configurations_predictor;
std::vector<std::shared_ptr<vectorfield>> configurations_temp;
};
// Return the maximum of absolute values of force components for an image
template<Solver solver>
scalar Method_Solver<solver>::Force_on_Image_MaxAbsComponent(const vectorfield & image, vectorfield & force)
{
// Take out component in direction of v2
Manifoldmath::project_tangential(force, image);
// We want the Maximum of Absolute Values of all force components on all images
return Vectormath::max_abs_component(force);
}
// Return the maximum norm of the torque for an image
template<Solver solver>
scalar Method_Solver<solver>::MaxTorque_on_Image(const vectorfield & image, vectorfield & force)
{
// Take out component in direction of v2
Manifoldmath::project_tangential(force, image);
return Vectormath::max_norm(force);
}
template<Solver solver>
bool Method_Solver<solver>::Converged()
{
bool converged = false;
if( this->max_torque < this->parameters->force_convergence ) converged = true;
return converged;
}
// Default implementation: do nothing
template<Solver solver>
void Method_Solver<solver>::Initialize()
{
};
// Default implementation: do nothing
template<Solver solver>
void Method_Solver<solver>::Finalize()
{
};
// Default implementation: do nothing
template<Solver solver>
void Method_Solver<solver>::Iteration()
{
};
template<Solver solver>
void Method_Solver<solver>::Message_Start()
{
using namespace Utility;
//---- Log messages
std::vector<std::string> block;
block.push_back( fmt::format("------------ Started {} Calculation ------------", this->Name()) );
block.push_back( fmt::format(" Going to iterate {} step(s)", this->n_log) );
block.push_back( fmt::format(" with {} iterations per step", this->n_iterations_log) );
block.push_back( fmt::format(" Force convergence parameter: {:." + fmt::format("{}", this->print_precision) + "f}", this->parameters->force_convergence) );
block.push_back( fmt::format(" Maximum torque: {:." + fmt::format("{}", this->print_precision) + "f}", this->max_torque) );
block.push_back( fmt::format(" Solver: {}", this->SolverFullName()) );
if( this->Name() == "GNEB" )
{
scalar length = Manifoldmath::dist_geodesic(*this->configurations[0], *this->configurations[this->noi-1]);
block.push_back( fmt::format(" Total path length: {}", length) );
}
block.push_back( "-----------------------------------------------------" );
Log.SendBlock(Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain);
}
template<Solver solver>
void Method_Solver<solver>::Message_Step()
{
using namespace Utility;
std::string percentage = fmt::format("{:.2f}%:", 100*double(this->iteration)/double(this->n_iterations));
bool llg_dynamics = this->Name() == "LLG"
&& !( this->systems[this->idx_image]->llg_parameters->direct_minimization
|| solver == Solver::VP || solver == Solver::VP_OSO
|| solver == Solver::LBFGS_OSO || solver == Solver::LBFGS_Atlas );
// Update time of current step
auto t_current = system_clock::now();
// Send log message
std::vector<std::string> block;
block.push_back( fmt::format("----- {} Calculation ({} Solver): {}", this->Name(), this->SolverName(), Timing::DateTimePassed(t_current - this->t_start)) );
block.push_back( fmt::format(" Time since last step: {}", Timing::DateTimePassed(t_current - this->t_last)) );
block.push_back( fmt::format(" Completed {:>8} {} / {} iterations", percentage, this->iteration, this->n_iterations) );
block.push_back( fmt::format(" Iterations / sec: {:.2f}", this->n_iterations_log / Timing::SecondsPassed(t_current - this->t_last)) );
if( llg_dynamics )
block.push_back( fmt::format(" Simulated time: {} ps", this->get_simulated_time()) );
if( this->Name() == "GNEB" )
{
scalar length = Manifoldmath::dist_geodesic(*this->configurations[0], *this->configurations[this->noi-1]);
block.push_back( fmt::format(" Total path length: {}", length) );
}
block.push_back( fmt::format(" Force convergence parameter: {:." + fmt::format("{}", this->print_precision) + "f}", this->parameters->force_convergence) );
block.push_back( fmt::format(" Maximum torque: {:." + fmt::format("{}", this->print_precision) + "f}", this->max_torque) );
Log.SendBlock(Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain);
// Update time of last step
this->t_last = t_current;
}
template<Solver solver>
void Method_Solver<solver>::Message_End()
{
using namespace Utility;
std::string percentage = fmt::format("{:.2f}%:", 100*double(this->iteration)/double(this->n_iterations));
bool llg_dynamics = this->Name() == "LLG"
&& !( this->systems[this->idx_image]->llg_parameters->direct_minimization
|| solver == Solver::VP || solver == Solver::VP_OSO
|| solver == Solver::LBFGS_OSO || solver == Solver::LBFGS_Atlas );
//---- End timings
auto t_end = system_clock::now();
//---- Termination reason
std::string reason = "";
if( this->StopFile_Present() )
reason = "A STOP file has been found";
else if( this->Converged() )
reason = "The force converged";
else if( this->Walltime_Expired(t_end - this->t_start) )
reason = "The maximum walltime has been reached";
//---- Log messages
std::vector<std::string> block;
block.push_back( fmt::format("------------ Terminated {} Calculation ------------", this->Name()) );
if( reason.length() > 0 )
block.push_back( fmt::format("------- Reason: {}", reason) );
block.push_back( fmt::format(" Total duration: {}", Timing::DateTimePassed(t_end - this->t_start)) );
block.push_back( fmt::format(" Completed {:>8} {} / {} iterations", percentage, this->iteration, this->n_iterations) );
block.push_back( fmt::format(" Iterations / sec: {:.2f}", this->iteration / Timing::SecondsPassed(t_end - this->t_start)) );
if( llg_dynamics )
block.push_back( fmt::format(" Simulated time: {} ps", this->get_simulated_time()) );
if( this->Name() == "GNEB" )
{
scalar length = Manifoldmath::dist_geodesic(*this->configurations[0], *this->configurations[this->noi-1]);
block.push_back( fmt::format(" Total path length: {}", length) );
}
block.push_back( fmt::format(" Force convergence parameter: {:."+fmt::format("{}",this->print_precision)+"f}", this->parameters->force_convergence) );
block.push_back( fmt::format(" Maximum torque: {:."+fmt::format("{}",this->print_precision)+"f}", this->max_torque) );
block.push_back( fmt::format(" Solver: {}", this->SolverFullName()) );
block.push_back( "-----------------------------------------------------" );
Log.SendBlock(Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain);
}
template <> inline
std::string Method_Solver<Solver::None>::SolverName()
{
return "None";
};
template <> inline
std::string Method_Solver<Solver::None>::SolverFullName()
{
return "None";
};
// Include headers which specialize the Solver functions
#include <engine/Solver_SIB.hpp>
#include <engine/Solver_Heun.hpp>
#include <engine/Solver_Depondt.hpp>
#include <engine/Solver_RK4.hpp>
#include <engine/Solver_VP.hpp>
#include <engine/Solver_VP_OSO.hpp>
#include <engine/Solver_LBFGS_OSO.hpp>
#include <engine/Solver_LBFGS_Atlas.hpp>
}
#endif<commit_msg>Method_Solver.hpp: Formatted with clang format<commit_after>#pragma once
#ifndef Method_Solver_H
#define Method_Solver_H
#include "Spirit_Defines.h"
#include <Spirit/Simulation.h>
#include <data/Parameters_Method.hpp>
#include <data/Spin_System_Chain.hpp>
#include <engine/Manifoldmath.hpp>
#include <engine/Method.hpp>
#include <engine/Solver_Kernels.hpp>
#include <engine/Vectormath.hpp>
#include <utility/Constants.hpp>
#include <utility/Logging.hpp>
#include <utility/Timing.hpp>
#include <deque>
#include <fstream>
#include <iomanip>
#include <map>
#include <sstream>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <fmt/format.h>
namespace Engine
{
enum class Solver
{
None = -1,
SIB = Solver_SIB,
Heun = Solver_Heun,
Depondt = Solver_Depondt,
RungeKutta4 = Solver_RungeKutta4,
LBFGS_OSO = Solver_LBFGS_OSO,
LBFGS_Atlas = Solver_LBFGS_Atlas,
VP = Solver_VP,
VP_OSO = Solver_VP_OSO
};
/*
Base Class for Solver-based Simulation/Calculation Methods.
It is templated to allow a flexible choice of Solver to iterate the systems.
*/
template<Solver solver>
class Method_Solver : public Method
{
public:
// Constructor to be used in derived classes
Method_Solver( std::shared_ptr<Data::Parameters_Method> parameters, int idx_img, int idx_chain )
: Method( parameters, idx_img, idx_chain )
{
}
// // `Iterate` uses the `Solver_Iteration` function to evolve given systems according to the
// // `Calculate_Force` implementation of the Method-Subclass.
// // It iterates until: the maximum number of iterations is reached or the maximum
// // walltime is reaches or the force has converged or a file called `STOP` is found
// // or the calculation is stopped externally (via the API).
// virtual void Iterate() override;
// Solver name as string
virtual std::string SolverName() override;
virtual std::string SolverFullName() override;
// Iteration represents one iteration of a certain Solver
virtual void Iteration() override;
protected:
// Prepare random numbers for thermal fields, if needed
virtual void Prepare_Thermal_Field() {}
// Calculate Forces onto Systems
// This is currently overridden by methods to specify how the forces on a set of configurations should be
// calculated. This function is used in `the Solver_...` functions.
// TODO: maybe rename to separate from deterministic and stochastic force functions
virtual void Calculate_Force(
const std::vector<std::shared_ptr<vectorfield>> & configurations, std::vector<vectorfield> & forces )
{
Log( Utility::Log_Level::Error, Utility::Log_Sender::All,
"Tried to use Method_Solver::Calculate_Force() of the Method_Solver class!", this->idx_image,
this->idx_chain );
}
// Calculate virtual Forces onto Systems (can be precession and damping forces, correctly scaled)
// Calculate the effective force on a configuration. It is a combination of
// precession and damping terms for the Hamiltonian, spin currents and
// temperature. This function is used in `the Solver_...` functions.
// Default implementation: direct minimization
virtual void Calculate_Force_Virtual(
const std::vector<std::shared_ptr<vectorfield>> & configurations, const std::vector<vectorfield> & forces,
std::vector<vectorfield> & forces_virtual )
{
// Not Implemented!
Log( Utility::Log_Level::Error, Utility::Log_Sender::All,
"Tried to use Method_Solver::Calculate_Force_Virtual() of the Method_Solver class!", this->idx_image,
this->idx_chain );
}
// Calculate maximum of absolute values of force components for a spin configuration
virtual scalar Force_on_Image_MaxAbsComponent( const vectorfield & image, vectorfield & force ) final;
// Calculate maximum torque for a spin configuration
virtual scalar MaxTorque_on_Image( const vectorfield & image, vectorfield & force ) final;
// ...
// virtual bool Iterations_Allowed() override;
// Check if the forces are converged
virtual bool Converged();
// Check if any stop criteria were encountered
bool ContinueIterating() override
{
return Method::ContinueIterating() && !this->Converged();
}
// Initialise contains the initialisations of arrays etc. for a certain solver
virtual void Initialize() override;
virtual void Finalize() override;
// Log message blocks
virtual void Message_Start() override;
virtual void Message_Step() override;
virtual void Message_End() override;
//////////// DEPONDT ////////////////////////////////////////////////////////////
// Temporaries for virtual forces
std::vector<vectorfield> rotationaxis;
std::vector<scalarfield> forces_virtual_norm;
// Preccession angle
scalarfield angle;
//////////// LBFGS ////////////////////////////////////////////////////////////
// General
int n_lbfgs_memory;
int local_iter;
scalar maxmove;
scalarfield rho;
scalarfield alpha;
// Atlas coords
std::vector<field<vector2field>> atlas_updates;
std::vector<field<vector2field>> grad_atlas_updates;
std::vector<scalarfield> atlas_coords3;
std::vector<vector2field> atlas_directions;
std::vector<vector2field> atlas_residuals;
std::vector<vector2field> atlas_residuals_last;
std::vector<vector2field> atlas_q_vec;
// OSO
std::vector<field<vectorfield>> delta_a;
std::vector<field<vectorfield>> delta_grad;
std::vector<vectorfield> searchdir;
std::vector<vectorfield> grad;
std::vector<vectorfield> grad_pr;
std::vector<vectorfield> q_vec;
// buffer variables for checking convergence for solver and Newton-Raphson
// std::vector<scalarfield> r_dot_d, dda2;
//////////// VP ///////////////////////////////////////////////////////////////
// "Mass of our particle" which we accelerate
scalar m = 1.0;
// Force in previous step [noi][nos]
std::vector<vectorfield> forces_previous;
// Velocity in previous step [noi][nos]
std::vector<vectorfield> velocities_previous;
// Velocity used in the Steps [noi][nos]
std::vector<vectorfield> velocities;
// Projection of velocities onto the forces [noi]
std::vector<scalar> projection;
// |force|^2
std::vector<scalar> force_norm2;
// Temporary Spins arrays
vectorfield temp1, temp2;
// Actual Forces on the configurations
std::vector<vectorfield> forces;
std::vector<vectorfield> forces_predictor;
// Virtual Forces used in the Steps
std::vector<vectorfield> forces_virtual;
std::vector<vectorfield> forces_virtual_predictor;
// RK 4
std::vector<std::shared_ptr<vectorfield>> configurations_k1;
std::vector<std::shared_ptr<vectorfield>> configurations_k2;
std::vector<std::shared_ptr<vectorfield>> configurations_k3;
std::vector<std::shared_ptr<vectorfield>> configurations_k4;
// Random vector array
vectorfield xi;
// Pointers to Configurations (for Solver methods)
std::vector<std::shared_ptr<vectorfield>> configurations;
std::vector<std::shared_ptr<vectorfield>> configurations_predictor;
std::vector<std::shared_ptr<vectorfield>> configurations_temp;
};
// Return the maximum of absolute values of force components for an image
template<Solver solver>
scalar Method_Solver<solver>::Force_on_Image_MaxAbsComponent( const vectorfield & image, vectorfield & force )
{
// Take out component in direction of v2
Manifoldmath::project_tangential( force, image );
// We want the Maximum of Absolute Values of all force components on all images
return Vectormath::max_abs_component( force );
}
// Return the maximum norm of the torque for an image
template<Solver solver>
scalar Method_Solver<solver>::MaxTorque_on_Image( const vectorfield & image, vectorfield & force )
{
// Take out component in direction of v2
Manifoldmath::project_tangential( force, image );
return Vectormath::max_norm( force );
}
template<Solver solver>
bool Method_Solver<solver>::Converged()
{
bool converged = false;
if( this->max_torque < this->parameters->force_convergence )
converged = true;
return converged;
}
// Default implementation: do nothing
template<Solver solver>
void Method_Solver<solver>::Initialize(){};
// Default implementation: do nothing
template<Solver solver>
void Method_Solver<solver>::Finalize(){};
// Default implementation: do nothing
template<Solver solver>
void Method_Solver<solver>::Iteration(){};
template<Solver solver>
void Method_Solver<solver>::Message_Start()
{
using namespace Utility;
//---- Log messages
std::vector<std::string> block;
block.push_back( fmt::format( "------------ Started {} Calculation ------------", this->Name() ) );
block.push_back( fmt::format( " Going to iterate {} step(s)", this->n_log ) );
block.push_back( fmt::format( " with {} iterations per step", this->n_iterations_log ) );
block.push_back( fmt::format(
" Force convergence parameter: {:." + fmt::format( "{}", this->print_precision ) + "f}",
this->parameters->force_convergence ) );
block.push_back( fmt::format(
" Maximum torque: {:." + fmt::format( "{}", this->print_precision ) + "f}",
this->max_torque ) );
block.push_back( fmt::format( " Solver: {}", this->SolverFullName() ) );
if( this->Name() == "GNEB" )
{
scalar length = Manifoldmath::dist_geodesic( *this->configurations[0], *this->configurations[this->noi - 1] );
block.push_back( fmt::format( " Total path length: {}", length ) );
}
block.push_back( "-----------------------------------------------------" );
Log.SendBlock( Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain );
}
template<Solver solver>
void Method_Solver<solver>::Message_Step()
{
using namespace Utility;
std::string percentage = fmt::format( "{:.2f}%:", 100 * double( this->iteration ) / double( this->n_iterations ) );
bool llg_dynamics
= this->Name() == "LLG"
&& !(
this->systems[this->idx_image]->llg_parameters->direct_minimization || solver == Solver::VP
|| solver == Solver::VP_OSO || solver == Solver::LBFGS_OSO || solver == Solver::LBFGS_Atlas );
// Update time of current step
auto t_current = system_clock::now();
// Send log message
std::vector<std::string> block;
block.push_back( fmt::format(
"----- {} Calculation ({} Solver): {}", this->Name(), this->SolverName(),
Timing::DateTimePassed( t_current - this->t_start ) ) );
block.push_back(
fmt::format( " Time since last step: {}", Timing::DateTimePassed( t_current - this->t_last ) ) );
block.push_back(
fmt::format( " Completed {:>8} {} / {} iterations", percentage, this->iteration, this->n_iterations ) );
block.push_back( fmt::format(
" Iterations / sec: {:.2f}",
this->n_iterations_log / Timing::SecondsPassed( t_current - this->t_last ) ) );
if( llg_dynamics )
block.push_back( fmt::format( " Simulated time: {} ps", this->get_simulated_time() ) );
if( this->Name() == "GNEB" )
{
scalar length = Manifoldmath::dist_geodesic( *this->configurations[0], *this->configurations[this->noi - 1] );
block.push_back( fmt::format( " Total path length: {}", length ) );
}
block.push_back( fmt::format(
" Force convergence parameter: {:." + fmt::format( "{}", this->print_precision ) + "f}",
this->parameters->force_convergence ) );
block.push_back( fmt::format(
" Maximum torque: {:." + fmt::format( "{}", this->print_precision ) + "f}",
this->max_torque ) );
Log.SendBlock( Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain );
// Update time of last step
this->t_last = t_current;
}
template<Solver solver>
void Method_Solver<solver>::Message_End()
{
using namespace Utility;
std::string percentage = fmt::format( "{:.2f}%:", 100 * double( this->iteration ) / double( this->n_iterations ) );
bool llg_dynamics
= this->Name() == "LLG"
&& !(
this->systems[this->idx_image]->llg_parameters->direct_minimization || solver == Solver::VP
|| solver == Solver::VP_OSO || solver == Solver::LBFGS_OSO || solver == Solver::LBFGS_Atlas );
//---- End timings
auto t_end = system_clock::now();
//---- Termination reason
std::string reason = "";
if( this->StopFile_Present() )
reason = "A STOP file has been found";
else if( this->Converged() )
reason = "The force converged";
else if( this->Walltime_Expired( t_end - this->t_start ) )
reason = "The maximum walltime has been reached";
//---- Log messages
std::vector<std::string> block;
block.push_back( fmt::format( "------------ Terminated {} Calculation ------------", this->Name() ) );
if( reason.length() > 0 )
block.push_back( fmt::format( "------- Reason: {}", reason ) );
block.push_back( fmt::format( " Total duration: {}", Timing::DateTimePassed( t_end - this->t_start ) ) );
block.push_back(
fmt::format( " Completed {:>8} {} / {} iterations", percentage, this->iteration, this->n_iterations ) );
block.push_back( fmt::format(
" Iterations / sec: {:.2f}", this->iteration / Timing::SecondsPassed( t_end - this->t_start ) ) );
if( llg_dynamics )
block.push_back( fmt::format( " Simulated time: {} ps", this->get_simulated_time() ) );
if( this->Name() == "GNEB" )
{
scalar length = Manifoldmath::dist_geodesic( *this->configurations[0], *this->configurations[this->noi - 1] );
block.push_back( fmt::format( " Total path length: {}", length ) );
}
block.push_back( fmt::format(
" Force convergence parameter: {:." + fmt::format( "{}", this->print_precision ) + "f}",
this->parameters->force_convergence ) );
block.push_back( fmt::format(
" Maximum torque: {:." + fmt::format( "{}", this->print_precision ) + "f}",
this->max_torque ) );
block.push_back( fmt::format( " Solver: {}", this->SolverFullName() ) );
block.push_back( "-----------------------------------------------------" );
Log.SendBlock( Log_Level::All, this->SenderName, block, this->idx_image, this->idx_chain );
}
template<>
inline std::string Method_Solver<Solver::None>::SolverName()
{
return "None";
};
template<>
inline std::string Method_Solver<Solver::None>::SolverFullName()
{
return "None";
};
// Include headers which specialize the Solver functions
#include <engine/Solver_Depondt.hpp>
#include <engine/Solver_Heun.hpp>
#include <engine/Solver_LBFGS_Atlas.hpp>
#include <engine/Solver_LBFGS_OSO.hpp>
#include <engine/Solver_RK4.hpp>
#include <engine/Solver_SIB.hpp>
#include <engine/Solver_VP.hpp>
#include <engine/Solver_VP_OSO.hpp>
} // namespace Engine
#endif<|endoftext|> |
<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeTypePch.h"
namespace Js
{
// -------------------------------------------------------------------------------------------------------------------------
// TypePropertyCacheElement
// -------------------------------------------------------------------------------------------------------------------------
TypePropertyCacheElement::TypePropertyCacheElement()
: id(Constants::NoProperty), tag(1), index(0), prototypeObjectWithProperty(nullptr)
{
}
PropertyId TypePropertyCacheElement::Id() const
{
return id;
}
PropertyIndex TypePropertyCacheElement::Index() const
{
return index;
}
bool TypePropertyCacheElement::IsInlineSlot() const
{
return isInlineSlot;
}
bool TypePropertyCacheElement::IsSetPropertyAllowed() const
{
return isSetPropertyAllowed;
}
bool TypePropertyCacheElement::IsMissing() const
{
return isMissing;
}
DynamicObject *TypePropertyCacheElement::PrototypeObjectWithProperty() const
{
return prototypeObjectWithProperty;
}
void TypePropertyCacheElement::Cache(
const PropertyId id,
const PropertyIndex index,
const bool isInlineSlot,
const bool isSetPropertyAllowed)
{
Assert(id != Constants::NoProperty);
Assert(index != Constants::NoSlot);
this->id = id;
this->index = index;
this->isInlineSlot = isInlineSlot;
this->isSetPropertyAllowed = isSetPropertyAllowed;
this->isMissing = false;
this->prototypeObjectWithProperty = nullptr;
}
void TypePropertyCacheElement::Cache(
const PropertyId id,
const PropertyIndex index,
const bool isInlineSlot,
const bool isSetPropertyAllowed,
const bool isMissing,
DynamicObject *const prototypeObjectWithProperty,
Type *const myParentType)
{
Assert(id != Constants::NoProperty);
Assert(index != Constants::NoSlot);
Assert(prototypeObjectWithProperty);
Assert(myParentType);
if(this->id != id || !this->prototypeObjectWithProperty)
myParentType->GetScriptContext()->GetThreadContext()->RegisterTypeWithProtoPropertyCache(id, myParentType);
this->id = id;
this->index = index;
this->isInlineSlot = isInlineSlot;
this->isSetPropertyAllowed = isSetPropertyAllowed;
this->isMissing = isMissing;
this->prototypeObjectWithProperty = prototypeObjectWithProperty;
Assert(this->isMissing == (uint16)(this->prototypeObjectWithProperty == this->prototypeObjectWithProperty->GetLibrary()->GetMissingPropertyHolder()));
}
void TypePropertyCacheElement::Clear()
{
id = Constants::NoProperty;
}
// -------------------------------------------------------------------------------------------------------------------------
// TypePropertyCache
// -------------------------------------------------------------------------------------------------------------------------
size_t TypePropertyCache::ElementIndex(const PropertyId id)
{
Assert(id != Constants::NoProperty);
Assert((TypePropertyCache_NumElements & TypePropertyCache_NumElements - 1) == 0);
return id & TypePropertyCache_NumElements - 1;
}
inline bool TypePropertyCache::TryGetIndexForLoad(
const bool checkMissing,
const PropertyId id,
PropertyIndex *const index,
bool *const isInlineSlot,
bool *const isMissing,
DynamicObject * *const prototypeObjectWithProperty) const
{
Assert(index);
Assert(isInlineSlot);
Assert(isMissing);
Assert(prototypeObjectWithProperty);
const TypePropertyCacheElement &element = elements[ElementIndex(id)];
if(element.Id() != id || (!checkMissing && element.IsMissing()))
return false;
*index = element.Index();
*isInlineSlot = element.IsInlineSlot();
*isMissing = checkMissing ? element.IsMissing() : false;
*prototypeObjectWithProperty = element.PrototypeObjectWithProperty();
return true;
}
inline bool TypePropertyCache::TryGetIndexForStore(
const PropertyId id,
PropertyIndex *const index,
bool *const isInlineSlot) const
{
Assert(index);
Assert(isInlineSlot);
const TypePropertyCacheElement &element = elements[ElementIndex(id)];
if(element.Id() != id ||
!element.IsSetPropertyAllowed() ||
element.PrototypeObjectWithProperty())
{
return false;
}
Assert(!element.IsMissing());
*index = element.Index();
*isInlineSlot = element.IsInlineSlot();
return true;
}
bool TypePropertyCache::TryGetProperty(
const bool checkMissing,
RecyclableObject *const propertyObject,
const PropertyId propertyId,
Var *const propertyValue,
ScriptContext *const requestContext,
PropertyCacheOperationInfo *const operationInfo,
PropertyValueInfo *const propertyValueInfo)
{
Assert(propertyValueInfo);
Assert(propertyValueInfo->GetInlineCache() || propertyValueInfo->GetPolymorphicInlineCache());
PropertyIndex propertyIndex;
DynamicObject *prototypeObjectWithProperty;
bool isInlineSlot, isMissing;
if(!TryGetIndexForLoad(
checkMissing,
propertyId,
&propertyIndex,
&isInlineSlot,
&isMissing,
&prototypeObjectWithProperty))
{
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache get miss"),
propertyId,
requestContext,
propertyObject);
}
#endif
return false;
}
if(!prototypeObjectWithProperty)
{
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache get hit"),
propertyId,
requestContext,
propertyObject);
}
#endif
#if DBG
const PropertyIndex typeHandlerPropertyIndex =
DynamicObject
::FromVar(propertyObject)
->GetDynamicType()
->GetTypeHandler()
->InlineOrAuxSlotIndexToPropertyIndex(propertyIndex, isInlineSlot);
Assert(typeHandlerPropertyIndex == propertyObject->GetPropertyIndex(propertyId));
#endif
*propertyValue =
isInlineSlot
? DynamicObject::FromVar(propertyObject)->GetInlineSlot(propertyIndex)
: DynamicObject::FromVar(propertyObject)->GetAuxSlot(propertyIndex);
if(propertyObject->GetScriptContext() == requestContext)
{
DebugOnly(Var getPropertyValue = JavascriptOperators::GetProperty(propertyObject, propertyId, requestContext));
Assert(*propertyValue == getPropertyValue ||
(getPropertyValue == requestContext->GetLibrary()->GetNull() && requestContext->GetThreadContext()->IsDisableImplicitCall() && propertyObject->GetType()->IsExternal()));
CacheOperators::Cache<false, true, false>(
false,
DynamicObject::FromVar(propertyObject),
false,
propertyObject->GetType(),
nullptr,
propertyId,
propertyIndex,
isInlineSlot,
false,
0,
propertyValueInfo,
requestContext);
return true;
}
else
{
*propertyValue = CrossSite::MarshalVar(requestContext, *propertyValue);
}
// Cannot use GetProperty and compare results since they may not compare equal when they're marshaled
if(operationInfo)
{
operationInfo->cacheType = CacheType_TypeProperty;
operationInfo->slotType = isInlineSlot ? SlotType_Inline : SlotType_Aux;
}
return true;
}
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache get hit prototype"),
propertyId,
requestContext,
propertyObject);
}
#endif
#if DBG
const PropertyIndex typeHandlerPropertyIndex =
prototypeObjectWithProperty
->GetDynamicType()
->GetTypeHandler()
->InlineOrAuxSlotIndexToPropertyIndex(propertyIndex, isInlineSlot);
Assert(typeHandlerPropertyIndex == prototypeObjectWithProperty->GetPropertyIndex(propertyId));
#endif
*propertyValue =
isInlineSlot
? prototypeObjectWithProperty->GetInlineSlot(propertyIndex)
: prototypeObjectWithProperty->GetAuxSlot(propertyIndex);
if(prototypeObjectWithProperty->GetScriptContext() == requestContext)
{
Assert(*propertyValue == JavascriptOperators::GetProperty(propertyObject, propertyId, requestContext));
if(propertyObject->GetScriptContext() != requestContext)
{
return true;
}
CacheOperators::Cache<false, true, false>(
true,
prototypeObjectWithProperty,
false,
propertyObject->GetType(),
nullptr,
propertyId,
propertyIndex,
isInlineSlot,
isMissing,
0,
propertyValueInfo,
requestContext);
return true;
}
else
{
*propertyValue = CrossSite::MarshalVar(requestContext, *propertyValue);
}
// Cannot use GetProperty and compare results since they may not compare equal when they're marshaled
if(operationInfo)
{
operationInfo->cacheType = CacheType_TypeProperty;
operationInfo->slotType = isInlineSlot ? SlotType_Inline : SlotType_Aux;
}
return true;
}
bool TypePropertyCache::TrySetProperty(
RecyclableObject *const object,
const PropertyId propertyId,
Var propertyValue,
ScriptContext *const requestContext,
PropertyCacheOperationInfo *const operationInfo,
PropertyValueInfo *const propertyValueInfo)
{
Assert(propertyValueInfo);
Assert(propertyValueInfo->GetInlineCache() || propertyValueInfo->GetPolymorphicInlineCache());
PropertyIndex propertyIndex;
bool isInlineSlot;
if(!TryGetIndexForStore(propertyId, &propertyIndex, &isInlineSlot))
{
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache set miss"),
propertyId,
requestContext,
object);
}
#endif
return false;
}
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache set hit"),
propertyId,
requestContext,
object);
}
#endif
#if ENABLE_FIXED_FIELDS
Assert(!object->IsFixedProperty(propertyId));
#endif
Assert(
(
DynamicObject
::FromVar(object)
->GetDynamicType()
->GetTypeHandler()
->InlineOrAuxSlotIndexToPropertyIndex(propertyIndex, isInlineSlot)
) ==
object->GetPropertyIndex(propertyId));
Assert(object->CanStorePropertyValueDirectly(propertyId, false));
ScriptContext *const objectScriptContext = object->GetScriptContext();
propertyValue = CrossSite::MarshalVar(objectScriptContext, propertyValue, objectScriptContext);
if(isInlineSlot)
{
DynamicObject::FromVar(object)->SetInlineSlot(SetSlotArguments(propertyId, propertyIndex, propertyValue));
}
else
{
DynamicObject::FromVar(object)->SetAuxSlot(SetSlotArguments(propertyId, propertyIndex, propertyValue));
}
if(objectScriptContext == requestContext)
{
CacheOperators::Cache<false, false, false>(
false,
DynamicObject::FromVar(object),
false,
object->GetType(),
nullptr,
propertyId,
propertyIndex,
isInlineSlot,
false,
0,
propertyValueInfo,
requestContext);
return true;
}
if(operationInfo)
{
operationInfo->cacheType = CacheType_TypeProperty;
operationInfo->slotType = isInlineSlot ? SlotType_Inline : SlotType_Aux;
}
return true;
}
void TypePropertyCache::Cache(
const PropertyId id,
const PropertyIndex index,
const bool isInlineSlot,
const bool isSetPropertyAllowed)
{
elements[ElementIndex(id)].Cache(id, index, isInlineSlot, isSetPropertyAllowed);
}
void TypePropertyCache::Cache(
const PropertyId id,
const PropertyIndex index,
const bool isInlineSlot,
const bool isSetPropertyAllowed,
const bool isMissing,
DynamicObject *const prototypeObjectWithProperty,
Type *const myParentType)
{
Assert(myParentType);
Assert(myParentType->GetPropertyCache() == this);
elements[ElementIndex(id)].Cache(
id,
index,
isInlineSlot,
isSetPropertyAllowed,
isMissing,
prototypeObjectWithProperty,
myParentType);
}
void TypePropertyCache::ClearIfPropertyIsOnAPrototype(const PropertyId id)
{
TypePropertyCacheElement &element = elements[ElementIndex(id)];
if(element.Id() == id && element.PrototypeObjectWithProperty())
element.Clear();
}
void TypePropertyCache::Clear(const PropertyId id)
{
TypePropertyCacheElement &element = elements[ElementIndex(id)];
if(element.Id() == id)
element.Clear();
}
}
<commit_msg>[1.7>master] [MERGE #3882 @obastemur] PropertyCache: assume property's context != object's context<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeTypePch.h"
namespace Js
{
// -------------------------------------------------------------------------------------------------------------------------
// TypePropertyCacheElement
// -------------------------------------------------------------------------------------------------------------------------
TypePropertyCacheElement::TypePropertyCacheElement()
: id(Constants::NoProperty), tag(1), index(0), prototypeObjectWithProperty(nullptr)
{
}
PropertyId TypePropertyCacheElement::Id() const
{
return id;
}
PropertyIndex TypePropertyCacheElement::Index() const
{
return index;
}
bool TypePropertyCacheElement::IsInlineSlot() const
{
return isInlineSlot;
}
bool TypePropertyCacheElement::IsSetPropertyAllowed() const
{
return isSetPropertyAllowed;
}
bool TypePropertyCacheElement::IsMissing() const
{
return isMissing;
}
DynamicObject *TypePropertyCacheElement::PrototypeObjectWithProperty() const
{
return prototypeObjectWithProperty;
}
void TypePropertyCacheElement::Cache(
const PropertyId id,
const PropertyIndex index,
const bool isInlineSlot,
const bool isSetPropertyAllowed)
{
Assert(id != Constants::NoProperty);
Assert(index != Constants::NoSlot);
this->id = id;
this->index = index;
this->isInlineSlot = isInlineSlot;
this->isSetPropertyAllowed = isSetPropertyAllowed;
this->isMissing = false;
this->prototypeObjectWithProperty = nullptr;
}
void TypePropertyCacheElement::Cache(
const PropertyId id,
const PropertyIndex index,
const bool isInlineSlot,
const bool isSetPropertyAllowed,
const bool isMissing,
DynamicObject *const prototypeObjectWithProperty,
Type *const myParentType)
{
Assert(id != Constants::NoProperty);
Assert(index != Constants::NoSlot);
Assert(prototypeObjectWithProperty);
Assert(myParentType);
if(this->id != id || !this->prototypeObjectWithProperty)
myParentType->GetScriptContext()->GetThreadContext()->RegisterTypeWithProtoPropertyCache(id, myParentType);
this->id = id;
this->index = index;
this->isInlineSlot = isInlineSlot;
this->isSetPropertyAllowed = isSetPropertyAllowed;
this->isMissing = isMissing;
this->prototypeObjectWithProperty = prototypeObjectWithProperty;
Assert(this->isMissing == (uint16)(this->prototypeObjectWithProperty == this->prototypeObjectWithProperty->GetLibrary()->GetMissingPropertyHolder()));
}
void TypePropertyCacheElement::Clear()
{
id = Constants::NoProperty;
}
// -------------------------------------------------------------------------------------------------------------------------
// TypePropertyCache
// -------------------------------------------------------------------------------------------------------------------------
size_t TypePropertyCache::ElementIndex(const PropertyId id)
{
Assert(id != Constants::NoProperty);
Assert((TypePropertyCache_NumElements & TypePropertyCache_NumElements - 1) == 0);
return id & TypePropertyCache_NumElements - 1;
}
inline bool TypePropertyCache::TryGetIndexForLoad(
const bool checkMissing,
const PropertyId id,
PropertyIndex *const index,
bool *const isInlineSlot,
bool *const isMissing,
DynamicObject * *const prototypeObjectWithProperty) const
{
Assert(index);
Assert(isInlineSlot);
Assert(isMissing);
Assert(prototypeObjectWithProperty);
const TypePropertyCacheElement &element = elements[ElementIndex(id)];
if(element.Id() != id || (!checkMissing && element.IsMissing()))
return false;
*index = element.Index();
*isInlineSlot = element.IsInlineSlot();
*isMissing = checkMissing ? element.IsMissing() : false;
*prototypeObjectWithProperty = element.PrototypeObjectWithProperty();
return true;
}
inline bool TypePropertyCache::TryGetIndexForStore(
const PropertyId id,
PropertyIndex *const index,
bool *const isInlineSlot) const
{
Assert(index);
Assert(isInlineSlot);
const TypePropertyCacheElement &element = elements[ElementIndex(id)];
if(element.Id() != id ||
!element.IsSetPropertyAllowed() ||
element.PrototypeObjectWithProperty())
{
return false;
}
Assert(!element.IsMissing());
*index = element.Index();
*isInlineSlot = element.IsInlineSlot();
return true;
}
bool TypePropertyCache::TryGetProperty(
const bool checkMissing,
RecyclableObject *const propertyObject,
const PropertyId propertyId,
Var *const propertyValue,
ScriptContext *const requestContext,
PropertyCacheOperationInfo *const operationInfo,
PropertyValueInfo *const propertyValueInfo)
{
Assert(propertyValueInfo);
Assert(propertyValueInfo->GetInlineCache() || propertyValueInfo->GetPolymorphicInlineCache());
PropertyIndex propertyIndex;
DynamicObject *prototypeObjectWithProperty;
bool isInlineSlot, isMissing;
if(!TryGetIndexForLoad(
checkMissing,
propertyId,
&propertyIndex,
&isInlineSlot,
&isMissing,
&prototypeObjectWithProperty))
{
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache get miss"),
propertyId,
requestContext,
propertyObject);
}
#endif
return false;
}
if(!prototypeObjectWithProperty)
{
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache get hit"),
propertyId,
requestContext,
propertyObject);
}
#endif
#if DBG
const PropertyIndex typeHandlerPropertyIndex =
DynamicObject
::FromVar(propertyObject)
->GetDynamicType()
->GetTypeHandler()
->InlineOrAuxSlotIndexToPropertyIndex(propertyIndex, isInlineSlot);
Assert(typeHandlerPropertyIndex == propertyObject->GetPropertyIndex(propertyId));
#endif
*propertyValue =
isInlineSlot
? DynamicObject::FromVar(propertyObject)->GetInlineSlot(propertyIndex)
: DynamicObject::FromVar(propertyObject)->GetAuxSlot(propertyIndex);
if(propertyObject->GetScriptContext() == requestContext)
{
DebugOnly(Var getPropertyValue = JavascriptOperators::GetProperty(propertyObject, propertyId, requestContext));
Assert(*propertyValue == getPropertyValue ||
(getPropertyValue == requestContext->GetLibrary()->GetNull() && requestContext->GetThreadContext()->IsDisableImplicitCall() && propertyObject->GetType()->IsExternal()));
CacheOperators::Cache<false, true, false>(
false,
DynamicObject::FromVar(propertyObject),
false,
propertyObject->GetType(),
nullptr,
propertyId,
propertyIndex,
isInlineSlot,
false,
0,
propertyValueInfo,
requestContext);
return true;
}
else
{
*propertyValue = CrossSite::MarshalVar(requestContext, *propertyValue);
}
// Cannot use GetProperty and compare results since they may not compare equal when they're marshaled
if(operationInfo)
{
operationInfo->cacheType = CacheType_TypeProperty;
operationInfo->slotType = isInlineSlot ? SlotType_Inline : SlotType_Aux;
}
return true;
}
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache get hit prototype"),
propertyId,
requestContext,
propertyObject);
}
#endif
#if DBG
const PropertyIndex typeHandlerPropertyIndex =
prototypeObjectWithProperty
->GetDynamicType()
->GetTypeHandler()
->InlineOrAuxSlotIndexToPropertyIndex(propertyIndex, isInlineSlot);
Assert(typeHandlerPropertyIndex == prototypeObjectWithProperty->GetPropertyIndex(propertyId));
#endif
*propertyValue =
isInlineSlot
? prototypeObjectWithProperty->GetInlineSlot(propertyIndex)
: prototypeObjectWithProperty->GetAuxSlot(propertyIndex);
if(prototypeObjectWithProperty->GetScriptContext() == requestContext)
{
Assert(*propertyValue == JavascriptOperators::GetProperty(propertyObject, propertyId, requestContext));
if(propertyObject->GetScriptContext() != requestContext)
{
return true;
}
CacheOperators::Cache<false, true, false>(
true,
prototypeObjectWithProperty,
false,
propertyObject->GetType(),
nullptr,
propertyId,
propertyIndex,
isInlineSlot,
isMissing,
0,
propertyValueInfo,
requestContext);
return true;
}
else
{
*propertyValue = CrossSite::MarshalVar(requestContext, *propertyValue);
}
// Cannot use GetProperty and compare results since they may not compare equal when they're marshaled
if(operationInfo)
{
operationInfo->cacheType = CacheType_TypeProperty;
operationInfo->slotType = isInlineSlot ? SlotType_Inline : SlotType_Aux;
}
return true;
}
bool TypePropertyCache::TrySetProperty(
RecyclableObject *const object,
const PropertyId propertyId,
Var propertyValue,
ScriptContext *const requestContext,
PropertyCacheOperationInfo *const operationInfo,
PropertyValueInfo *const propertyValueInfo)
{
Assert(propertyValueInfo);
Assert(propertyValueInfo->GetInlineCache() || propertyValueInfo->GetPolymorphicInlineCache());
PropertyIndex propertyIndex;
bool isInlineSlot;
if(!TryGetIndexForStore(propertyId, &propertyIndex, &isInlineSlot))
{
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache set miss"),
propertyId,
requestContext,
object);
}
#endif
return false;
}
#if DBG_DUMP
if(PHASE_TRACE1(TypePropertyCachePhase))
{
CacheOperators::TraceCache(
static_cast<InlineCache *>(nullptr),
_u("TypePropertyCache set hit"),
propertyId,
requestContext,
object);
}
#endif
#if ENABLE_FIXED_FIELDS
Assert(!object->IsFixedProperty(propertyId));
#endif
Assert(
(
DynamicObject
::FromVar(object)
->GetDynamicType()
->GetTypeHandler()
->InlineOrAuxSlotIndexToPropertyIndex(propertyIndex, isInlineSlot)
) ==
object->GetPropertyIndex(propertyId));
Assert(object->CanStorePropertyValueDirectly(propertyId, false));
ScriptContext *const objectScriptContext = object->GetScriptContext();
// force check: propertyValue's context != object's context.
// TODO: investigate why?
propertyValue = CrossSite::MarshalVar(objectScriptContext, propertyValue);
if(isInlineSlot)
{
DynamicObject::FromVar(object)->SetInlineSlot(SetSlotArguments(propertyId, propertyIndex, propertyValue));
}
else
{
DynamicObject::FromVar(object)->SetAuxSlot(SetSlotArguments(propertyId, propertyIndex, propertyValue));
}
if(objectScriptContext == requestContext)
{
CacheOperators::Cache<false, false, false>(
false,
DynamicObject::FromVar(object),
false,
object->GetType(),
nullptr,
propertyId,
propertyIndex,
isInlineSlot,
false,
0,
propertyValueInfo,
requestContext);
return true;
}
if(operationInfo)
{
operationInfo->cacheType = CacheType_TypeProperty;
operationInfo->slotType = isInlineSlot ? SlotType_Inline : SlotType_Aux;
}
return true;
}
void TypePropertyCache::Cache(
const PropertyId id,
const PropertyIndex index,
const bool isInlineSlot,
const bool isSetPropertyAllowed)
{
elements[ElementIndex(id)].Cache(id, index, isInlineSlot, isSetPropertyAllowed);
}
void TypePropertyCache::Cache(
const PropertyId id,
const PropertyIndex index,
const bool isInlineSlot,
const bool isSetPropertyAllowed,
const bool isMissing,
DynamicObject *const prototypeObjectWithProperty,
Type *const myParentType)
{
Assert(myParentType);
Assert(myParentType->GetPropertyCache() == this);
elements[ElementIndex(id)].Cache(
id,
index,
isInlineSlot,
isSetPropertyAllowed,
isMissing,
prototypeObjectWithProperty,
myParentType);
}
void TypePropertyCache::ClearIfPropertyIsOnAPrototype(const PropertyId id)
{
TypePropertyCacheElement &element = elements[ElementIndex(id)];
if(element.Id() == id && element.PrototypeObjectWithProperty())
element.Clear();
}
void TypePropertyCache::Clear(const PropertyId id)
{
TypePropertyCacheElement &element = elements[ElementIndex(id)];
if(element.Id() == id)
element.Clear();
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// particle id probability densities //
// //
// The AliPID class stores the probability densities for the different //
// particle type hypotheses electron, muon, pion, kaon, proton, photon, //
// pi0, neutron, K0 and electron conversion. These probability densities //
// are determined from the detector response functions. //
// The * and *= operators are overloaded for AliPID to combine the PIDs //
// from different detectors. //
// //
// The Bayesian probability to be a particle of a given type can be //
// calculated from the probability densities, if the a priori probabilities //
// (or abundences, concentrations) of particle species are known. These //
// priors can be given as argument to the GetProbability or GetMostProbable //
// method or they can be set globally by calling the static method //
// SetPriors(). //
// //
// The implementation of this class is based on the note ... //
// by Iouri Belikov and Karel Safarik. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <TClass.h>
#include <TDatabasePDG.h>
#include <TPDGCode.h>
#include "AliLog.h"
#include "AliPDG.h"
#include "AliPID.h"
#define M(PID) TDatabasePDG::Instance()->GetParticle(fgkParticleCode[(PID)])->Mass()
ClassImp(AliPID)
const char* AliPID::fgkParticleName[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
"electron",
"muon",
"pion",
"kaon",
"proton",
"photon",
"pi0",
"neutron",
"kaon0",
"eleCon",
"deuteron",
"triton",
"helium-3",
"alpha",
"unknown"
};
const char* AliPID::fgkParticleShortName[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
"e",
"mu",
"pi",
"K",
"p",
"photon",
"pi0",
"n",
"K0",
"eleCon",
"d",
"t",
"he3",
"alpha",
"unknown"
};
const char* AliPID::fgkParticleLatexName[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
"e",
"#mu",
"#pi",
"K",
"p",
"#gamma",
"#pi_{0}",
"n",
"K_{0}",
"eleCon",
"d",
"t",
"he3",
"#alpha",
"unknown"
};
const Int_t AliPID::fgkParticleCode[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
::kElectron,
::kMuonMinus,
::kPiPlus,
::kKPlus,
::kProton,
::kGamma,
::kPi0,
::kNeutron,
::kK0,
::kElectron,
1000010020,
1000010030,
1000020030,
1000020040,
0
};
/*const*/ Float_t AliPID::fgkParticleMass[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
/*
M(kElectron), // electron
M(kMuon), // muon
M(kPion), // pion
M(kKaon), // kaon
M(kProton), // proton
M(kPhoton), // photon
M(kPi0), // pi0
M(kNeutron), // neutron
M(kKaon0), // kaon0
M(kEleCon), // electron conversion
M(kDeuteron), // deuteron
M(kTriton), // triton
M(kHe3), // he3
M(kAlpha), // alpha
0.00000 // unknown
*/
};
Double_t AliPID::fgPrior[kSPECIESN] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
//_______________________________________________________________________
AliPID::AliPID() :
TObject(),
fCharged(0)
{
//
// Default constructor
//
Init();
// set default values (= equal probabilities)
for (Int_t i = 0; i < kSPECIESN; i++)
fProbDensity[i] = 1./kSPECIESN;
}
//_______________________________________________________________________
AliPID::AliPID(const Double_t* probDensity, Bool_t charged) :
TObject(),
fCharged(charged)
{
//
// Standard constructor
//
Init();
// set given probability densities
for (Int_t i = 0; i < kSPECIES; i++)
fProbDensity[i] = probDensity[i];
for (Int_t i = kSPECIES; i < kSPECIESN; i++)
fProbDensity[i] = ((charged) ? 0 : probDensity[i]);
}
//_______________________________________________________________________
AliPID::AliPID(const Float_t* probDensity, Bool_t charged) :
TObject(),
fCharged(charged)
{
//
// Standard constructor
//
Init();
// set given probability densities
for (Int_t i = 0; i < kSPECIES; i++)
fProbDensity[i] = probDensity[i];
for (Int_t i = kSPECIES; i < kSPECIESN; i++)
fProbDensity[i] = ((charged) ? 0 : probDensity[i]);
}
//_______________________________________________________________________
AliPID::AliPID(const AliPID& pid) :
TObject(pid),
fCharged(pid.fCharged)
{
//
// copy constructor
//
// We do not call init here, MUST already be done
for (Int_t i = 0; i < kSPECIESN; i++)
fProbDensity[i] = pid.fProbDensity[i];
}
//_______________________________________________________________________
void AliPID::SetProbabilities(const Double_t* probDensity, Bool_t charged)
{
//
// Set the probability densities
//
for (Int_t i = 0; i < kSPECIES; i++)
fProbDensity[i] = probDensity[i];
for (Int_t i = kSPECIES; i < kSPECIESN; i++)
fProbDensity[i] = ((charged) ? 0 : probDensity[i]);
}
//_______________________________________________________________________
AliPID& AliPID::operator = (const AliPID& pid)
{
// assignment operator
fCharged = pid.fCharged;
for (Int_t i = 0; i < kSPECIESN; i++) {
fProbDensity[i] = pid.fProbDensity[i];
}
return *this;
}
//_______________________________________________________________________
void AliPID::Init()
{
//
// Initialise the masses
//
// Initialise only once...
if(!fgkParticleMass[0]) {
AliPDG::AddParticlesToPdgDataBase();
for (Int_t i = 0; i < kSPECIESN + kSPECIESLN; i++)
fgkParticleMass[i] = M(i);
}
}
//_____________________________________________________________________________
Double_t AliPID::GetProbability(EParticleType iType,
const Double_t* prior) const
{
//
// Get the probability to be a particle of type "iType"
// assuming the a priori probabilities "prior"
//
Double_t sum = 0.;
Int_t nSpecies = ((fCharged) ? kSPECIES : kSPECIESN);
for (Int_t i = 0; i < nSpecies; i++) {
sum += fProbDensity[i] * prior[i];
}
if (sum <= 0) {
AliError("Invalid probability densities or priors");
return -1;
}
return fProbDensity[iType] * prior[iType] / sum;
}
//_____________________________________________________________________________
Double_t AliPID::GetProbability(EParticleType iType) const
{
// get the probability to be a particle of type "iType"
// assuming the globaly set a priori probabilities
return GetProbability(iType, fgPrior);
}
//_____________________________________________________________________________
void AliPID::GetProbabilities(Double_t* probabilities,
const Double_t* prior) const
{
// get the probabilities to be a particle of given type
// assuming the a priori probabilities "prior"
Double_t sum = 0.;
Int_t nSpecies = ((fCharged) ? kSPECIES : kSPECIESN);
for (Int_t i = 0; i < nSpecies; i++) {
sum += fProbDensity[i] * prior[i];
}
if (sum <= 0) {
AliError("Invalid probability densities or priors");
for (Int_t i = 0; i < nSpecies; i++) probabilities[i] = -1;
return;
}
for (Int_t i = 0; i < nSpecies; i++) {
probabilities[i] = fProbDensity[i] * prior[i] / sum;
}
}
//_____________________________________________________________________________
void AliPID::GetProbabilities(Double_t* probabilities) const
{
// get the probabilities to be a particle of given type
// assuming the globaly set a priori probabilities
GetProbabilities(probabilities, fgPrior);
}
//_____________________________________________________________________________
AliPID::EParticleType AliPID::GetMostProbable(const Double_t* prior) const
{
// get the most probable particle id hypothesis
// assuming the a priori probabilities "prior"
Double_t max = 0.;
EParticleType id = kPion;
Int_t nSpecies = ((fCharged) ? kSPECIES : kSPECIESN);
for (Int_t i = 0; i < nSpecies; i++) {
Double_t prob = fProbDensity[i] * prior[i];
if (prob > max) {
max = prob;
id = EParticleType(i);
}
}
if (max == 0) {
AliError("Invalid probability densities or priors");
}
return id;
}
//_____________________________________________________________________________
AliPID::EParticleType AliPID::GetMostProbable() const
{
// get the most probable particle id hypothesis
// assuming the globaly set a priori probabilities
return GetMostProbable(fgPrior);
}
//_____________________________________________________________________________
void AliPID::SetPriors(const Double_t* prior, Bool_t charged)
{
// use the given priors as global a priori probabilities
Double_t sum = 0;
for (Int_t i = 0; i < kSPECIESN; i++) {
if (charged && (i >= kSPECIES)) {
fgPrior[i] = 0;
} else {
if (prior[i] < 0) {
AliWarningClass(Form("negative prior (%g) for %ss. "
"Using 0 instead.", prior[i],
fgkParticleName[i]));
fgPrior[i] = 0;
} else {
fgPrior[i] = prior[i];
}
}
sum += prior[i];
}
if (sum == 0) {
AliWarningClass("all priors are zero.");
}
}
//_____________________________________________________________________________
void AliPID::SetPrior(EParticleType iType, Double_t prior)
{
// use the given prior as global a priori probability for particles
// of type "iType"
if (prior < 0) {
AliWarningClass(Form("negative prior (%g) for %ss. Using 0 instead.",
prior, fgkParticleName[iType]));
prior = 0;
}
fgPrior[iType] = prior;
}
//_____________________________________________________________________________
AliPID& AliPID::operator *= (const AliPID& pid)
{
// combine this probability densities with the one of "pid"
for (Int_t i = 0; i < kSPECIESN; i++) {
fProbDensity[i] *= pid.fProbDensity[i];
}
return *this;
}
//_____________________________________________________________________________
AliPID operator * (const AliPID& pid1, const AliPID& pid2)
{
// combine the two probability densities
AliPID result;
result *= pid1;
result *= pid2;
return result;
}
<commit_msg>Fixing coverity 18133<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// particle id probability densities //
// //
// The AliPID class stores the probability densities for the different //
// particle type hypotheses electron, muon, pion, kaon, proton, photon, //
// pi0, neutron, K0 and electron conversion. These probability densities //
// are determined from the detector response functions. //
// The * and *= operators are overloaded for AliPID to combine the PIDs //
// from different detectors. //
// //
// The Bayesian probability to be a particle of a given type can be //
// calculated from the probability densities, if the a priori probabilities //
// (or abundences, concentrations) of particle species are known. These //
// priors can be given as argument to the GetProbability or GetMostProbable //
// method or they can be set globally by calling the static method //
// SetPriors(). //
// //
// The implementation of this class is based on the note ... //
// by Iouri Belikov and Karel Safarik. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <TClass.h>
#include <TDatabasePDG.h>
#include <TPDGCode.h>
#include "AliLog.h"
#include "AliPDG.h"
#include "AliPID.h"
#define M(PID) TDatabasePDG::Instance()->GetParticle(fgkParticleCode[(PID)])->Mass()
ClassImp(AliPID)
const char* AliPID::fgkParticleName[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
"electron",
"muon",
"pion",
"kaon",
"proton",
"photon",
"pi0",
"neutron",
"kaon0",
"eleCon",
"deuteron",
"triton",
"helium-3",
"alpha",
"unknown"
};
const char* AliPID::fgkParticleShortName[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
"e",
"mu",
"pi",
"K",
"p",
"photon",
"pi0",
"n",
"K0",
"eleCon",
"d",
"t",
"he3",
"alpha",
"unknown"
};
const char* AliPID::fgkParticleLatexName[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
"e",
"#mu",
"#pi",
"K",
"p",
"#gamma",
"#pi_{0}",
"n",
"K_{0}",
"eleCon",
"d",
"t",
"he3",
"#alpha",
"unknown"
};
const Int_t AliPID::fgkParticleCode[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
::kElectron,
::kMuonMinus,
::kPiPlus,
::kKPlus,
::kProton,
::kGamma,
::kPi0,
::kNeutron,
::kK0,
::kElectron,
1000010020,
1000010030,
1000020030,
1000020040,
0
};
/*const*/ Float_t AliPID::fgkParticleMass[AliPID::kSPECIESN+AliPID::kSPECIESLN+1] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
/*
M(kElectron), // electron
M(kMuon), // muon
M(kPion), // pion
M(kKaon), // kaon
M(kProton), // proton
M(kPhoton), // photon
M(kPi0), // pi0
M(kNeutron), // neutron
M(kKaon0), // kaon0
M(kEleCon), // electron conversion
M(kDeuteron), // deuteron
M(kTriton), // triton
M(kHe3), // he3
M(kAlpha), // alpha
0.00000 // unknown
*/
};
Double_t AliPID::fgPrior[kSPECIESN] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
//_______________________________________________________________________
AliPID::AliPID() :
TObject(),
fCharged(0)
{
//
// Default constructor
//
Init();
// set default values (= equal probabilities)
for (Int_t i = 0; i < kSPECIESN; i++)
fProbDensity[i] = 1./kSPECIESN;
}
//_______________________________________________________________________
AliPID::AliPID(const Double_t* probDensity, Bool_t charged) :
TObject(),
fCharged(charged)
{
//
// Standard constructor
//
Init();
// set given probability densities
for (Int_t i = 0; i < kSPECIES; i++)
fProbDensity[i] = probDensity[i];
for (Int_t i = kSPECIES; i < kSPECIESN; i++)
fProbDensity[i] = ((charged) ? 0 : probDensity[i]);
}
//_______________________________________________________________________
AliPID::AliPID(const Float_t* probDensity, Bool_t charged) :
TObject(),
fCharged(charged)
{
//
// Standard constructor
//
Init();
// set given probability densities
for (Int_t i = 0; i < kSPECIES; i++)
fProbDensity[i] = probDensity[i];
for (Int_t i = kSPECIES; i < kSPECIESN; i++)
fProbDensity[i] = ((charged) ? 0 : probDensity[i]);
}
//_______________________________________________________________________
AliPID::AliPID(const AliPID& pid) :
TObject(pid),
fCharged(pid.fCharged)
{
//
// copy constructor
//
// We do not call init here, MUST already be done
for (Int_t i = 0; i < kSPECIESN; i++)
fProbDensity[i] = pid.fProbDensity[i];
}
//_______________________________________________________________________
void AliPID::SetProbabilities(const Double_t* probDensity, Bool_t charged)
{
//
// Set the probability densities
//
for (Int_t i = 0; i < kSPECIES; i++)
fProbDensity[i] = probDensity[i];
for (Int_t i = kSPECIES; i < kSPECIESN; i++)
fProbDensity[i] = ((charged) ? 0 : probDensity[i]);
}
//_______________________________________________________________________
AliPID& AliPID::operator = (const AliPID& pid)
{
// assignment operator
if(this != &pid) {
fCharged = pid.fCharged;
for (Int_t i = 0; i < kSPECIESN; i++) {
fProbDensity[i] = pid.fProbDensity[i];
}
}
return *this;
}
//_______________________________________________________________________
void AliPID::Init()
{
//
// Initialise the masses
//
// Initialise only once...
if(!fgkParticleMass[0]) {
AliPDG::AddParticlesToPdgDataBase();
for (Int_t i = 0; i < kSPECIESN + kSPECIESLN; i++)
fgkParticleMass[i] = M(i);
}
}
//_____________________________________________________________________________
Double_t AliPID::GetProbability(EParticleType iType,
const Double_t* prior) const
{
//
// Get the probability to be a particle of type "iType"
// assuming the a priori probabilities "prior"
//
Double_t sum = 0.;
Int_t nSpecies = ((fCharged) ? kSPECIES : kSPECIESN);
for (Int_t i = 0; i < nSpecies; i++) {
sum += fProbDensity[i] * prior[i];
}
if (sum <= 0) {
AliError("Invalid probability densities or priors");
return -1;
}
return fProbDensity[iType] * prior[iType] / sum;
}
//_____________________________________________________________________________
Double_t AliPID::GetProbability(EParticleType iType) const
{
// get the probability to be a particle of type "iType"
// assuming the globaly set a priori probabilities
return GetProbability(iType, fgPrior);
}
//_____________________________________________________________________________
void AliPID::GetProbabilities(Double_t* probabilities,
const Double_t* prior) const
{
// get the probabilities to be a particle of given type
// assuming the a priori probabilities "prior"
Double_t sum = 0.;
Int_t nSpecies = ((fCharged) ? kSPECIES : kSPECIESN);
for (Int_t i = 0; i < nSpecies; i++) {
sum += fProbDensity[i] * prior[i];
}
if (sum <= 0) {
AliError("Invalid probability densities or priors");
for (Int_t i = 0; i < nSpecies; i++) probabilities[i] = -1;
return;
}
for (Int_t i = 0; i < nSpecies; i++) {
probabilities[i] = fProbDensity[i] * prior[i] / sum;
}
}
//_____________________________________________________________________________
void AliPID::GetProbabilities(Double_t* probabilities) const
{
// get the probabilities to be a particle of given type
// assuming the globaly set a priori probabilities
GetProbabilities(probabilities, fgPrior);
}
//_____________________________________________________________________________
AliPID::EParticleType AliPID::GetMostProbable(const Double_t* prior) const
{
// get the most probable particle id hypothesis
// assuming the a priori probabilities "prior"
Double_t max = 0.;
EParticleType id = kPion;
Int_t nSpecies = ((fCharged) ? kSPECIES : kSPECIESN);
for (Int_t i = 0; i < nSpecies; i++) {
Double_t prob = fProbDensity[i] * prior[i];
if (prob > max) {
max = prob;
id = EParticleType(i);
}
}
if (max == 0) {
AliError("Invalid probability densities or priors");
}
return id;
}
//_____________________________________________________________________________
AliPID::EParticleType AliPID::GetMostProbable() const
{
// get the most probable particle id hypothesis
// assuming the globaly set a priori probabilities
return GetMostProbable(fgPrior);
}
//_____________________________________________________________________________
void AliPID::SetPriors(const Double_t* prior, Bool_t charged)
{
// use the given priors as global a priori probabilities
Double_t sum = 0;
for (Int_t i = 0; i < kSPECIESN; i++) {
if (charged && (i >= kSPECIES)) {
fgPrior[i] = 0;
} else {
if (prior[i] < 0) {
AliWarningClass(Form("negative prior (%g) for %ss. "
"Using 0 instead.", prior[i],
fgkParticleName[i]));
fgPrior[i] = 0;
} else {
fgPrior[i] = prior[i];
}
}
sum += prior[i];
}
if (sum == 0) {
AliWarningClass("all priors are zero.");
}
}
//_____________________________________________________________________________
void AliPID::SetPrior(EParticleType iType, Double_t prior)
{
// use the given prior as global a priori probability for particles
// of type "iType"
if (prior < 0) {
AliWarningClass(Form("negative prior (%g) for %ss. Using 0 instead.",
prior, fgkParticleName[iType]));
prior = 0;
}
fgPrior[iType] = prior;
}
//_____________________________________________________________________________
AliPID& AliPID::operator *= (const AliPID& pid)
{
// combine this probability densities with the one of "pid"
for (Int_t i = 0; i < kSPECIESN; i++) {
fProbDensity[i] *= pid.fProbDensity[i];
}
return *this;
}
//_____________________________________________________________________________
AliPID operator * (const AliPID& pid1, const AliPID& pid2)
{
// combine the two probability densities
AliPID result;
result *= pid1;
result *= pid2;
return result;
}
<|endoftext|> |
<commit_before>#include "RenderingSystem.h"
#include "Engine.h"
#include "AutoBinder.hpp"
using namespace Core;
using namespace Device;
using namespace Rendering;
using namespace Rendering::Camera;
using namespace Rendering::Shader;
using namespace Rendering::Renderer;
using namespace Rendering::RenderState;
using namespace Rendering::GI;
using namespace Rendering::Manager;
using namespace Rendering::Light;
using namespace Rendering::Shadow;
using namespace Rendering::Material;
void RenderingSystem::InitializeRenderer(Engine& engine, const RenderSetting&& param)
{
Object& object = engine.GetObjectManager().Acquire(param.mainCamName);
MainCamera& maincam = engine.GetComponentSystem().SetMainCamera(object.GetObjectID());
maincam.Initialize(engine.GetDirectX(), _shaderManager, param.renderRect);
engine.AddRootObject(object);
_shadowRenderer.Initialize(engine.GetDirectX(), param.shadowMapResolution, param.shadowMapResolution, param.shadowMapResolution);
_mainRenderer.Initialize(engine.GetDirectX(), _shaderManager, _bufferManager, maincam, param.giParam);
_defaultShaders.Initialize(engine.GetDirectX(), _shaderManager);
_backBufferMaker.Initialize(engine.GetDirectX(), _shaderManager);
}
void RenderingSystem::Initialize(Engine& engine)
{
_materialManager.Initialize(engine.GetDirectX());
_postProcessing.Initialize(engine.GetDirectX(), _shaderManager, engine.GetComponentSystem().GetMainCamera());
}
void RenderingSystem::Update(Engine& engine, float dt)
{
_postProcessing.SetElapsedTime(dt);
}
void RenderingSystem::Render(Engine& engine, float dt)
{
auto& dx = engine.GetDirectX();
_materialManager.UpdateConstBuffer(dx);
const auto& compoSys = engine.GetComponentSystem();
const auto& shadowMgr = compoSys.GetManager_Direct<ShadowManager>();
const auto cullParam = engine.GetCullingParam();
const auto meshRenderParam = GetMeshRenderParam();
_shadowRenderer.RenderShadowMap<SpotLightShadow>(dx, shadowMgr, _materialManager, cullParam, meshRenderParam);
_shadowRenderer.RenderShadowMap<PointLightShadow>(dx, shadowMgr, _materialManager, cullParam, meshRenderParam);
_shadowRenderer.RenderShadowMap<DirectionalLightShadow>(dx, shadowMgr, _materialManager, cullParam, meshRenderParam);
const auto& lightMgr = compoSys.GetManager_Direct<LightManager>();
const auto& mainCamera = compoSys.GetMainCamera();
if (_useSkyScattering)
{
_skyScatteringRenderer.CheckRenderAbleWithUpdateCB(engine.GetDirectX(), engine.GetTransformPool(), lightMgr, mainCamera);
if (_skyScatteringRenderer.GetRenderAble())
_skyScatteringRenderer.Render(engine.GetDirectX(), mainCamera, lightMgr);
}
_mainRenderer.UpdateCB(dx, mainCamera, lightMgr);
const SkyBoxMaterial* skyboxMaterial = _materialManager.Find<SkyBoxMaterial>(mainCamera.GetSkyBoxMaterialID());
_mainRenderer.Render(dx, MainRenderer::Param{mainCamera, meshRenderParam, _materialManager, lightMgr, ShadowSystem{shadowMgr, _shadowRenderer}, std::move(cullParam), skyboxMaterial});
_postProcessing.SetElapsedTime(dt);
_postProcessing.UpdateCB(dx);
_postProcessing.Render(dx, _mainRenderer, mainCamera);
AutoBinderSampler<PixelShader> sampler(dx, SamplerStateBindIndex(0), SamplerState::Point);
_backBufferMaker.Render(dx, dx.GetBackBufferRT(), *_mainRenderer.GetResultMap()->GetTexture2D());
dx.GetSwapChain()->Present(0, 0);
_shadowRenderer.ClearDirty();
}
void RenderingSystem::Destroy(Engine& engine)
{
}
MaterialID RenderingSystem::ActivateSkyScattering(Engine& engine, uint resolution, const Object& directionalLightObject)
{
assert(_useSkyScattering == false);
_useSkyScattering = true;
_skyScatteringRenderer.Initialize(engine.GetDirectX(), _bufferManager, _shaderManager, _materialManager, resolution);
assert(directionalLightObject.HasComponent<DirectionalLight>());
_skyScatteringRenderer.SetDirectionalLightID(directionalLightObject.GetObjectID());
return _skyScatteringRenderer.GetMaterialID();
}
void RenderingSystem::DeactivateSkyScattering()
{
assert(_useSkyScattering);
_useSkyScattering = false;
_skyScatteringRenderer.Destroy();
}
<commit_msg>RenderingSystem - SkyScattering Map Size 계산 추가<commit_after>#include "RenderingSystem.h"
#include "Engine.h"
#include "AutoBinder.hpp"
#undef min
using namespace Core;
using namespace Device;
using namespace Rendering;
using namespace Rendering::Camera;
using namespace Rendering::Shader;
using namespace Rendering::Renderer;
using namespace Rendering::RenderState;
using namespace Rendering::GI;
using namespace Rendering::Manager;
using namespace Rendering::Light;
using namespace Rendering::Shadow;
using namespace Rendering::Material;
void RenderingSystem::InitializeRenderer(Engine& engine, const RenderSetting&& param)
{
Object& object = engine.GetObjectManager().Acquire(param.mainCamName);
MainCamera& maincam = engine.GetComponentSystem().SetMainCamera(object.GetObjectID());
maincam.Initialize(engine.GetDirectX(), _shaderManager, param.renderRect);
engine.AddRootObject(object);
_shadowRenderer.Initialize(engine.GetDirectX(), param.shadowMapResolution, param.shadowMapResolution, param.shadowMapResolution);
_mainRenderer.Initialize(engine.GetDirectX(), _shaderManager, _bufferManager, maincam, param.giParam);
_defaultShaders.Initialize(engine.GetDirectX(), _shaderManager);
_backBufferMaker.Initialize(engine.GetDirectX(), _shaderManager);
}
void RenderingSystem::Initialize(Engine& engine)
{
_materialManager.Initialize(engine.GetDirectX());
_postProcessing.Initialize(engine.GetDirectX(), _shaderManager, engine.GetComponentSystem().GetMainCamera());
}
void RenderingSystem::Update(Engine& engine, float dt)
{
_postProcessing.SetElapsedTime(dt);
}
void RenderingSystem::Render(Engine& engine, float dt)
{
auto& dx = engine.GetDirectX();
_materialManager.UpdateConstBuffer(dx);
const auto& compoSys = engine.GetComponentSystem();
const auto& shadowMgr = compoSys.GetManager_Direct<ShadowManager>();
const auto cullParam = engine.GetCullingParam();
const auto meshRenderParam = GetMeshRenderParam();
_shadowRenderer.RenderShadowMap<SpotLightShadow>(dx, shadowMgr, _materialManager, cullParam, meshRenderParam);
_shadowRenderer.RenderShadowMap<PointLightShadow>(dx, shadowMgr, _materialManager, cullParam, meshRenderParam);
_shadowRenderer.RenderShadowMap<DirectionalLightShadow>(dx, shadowMgr, _materialManager, cullParam, meshRenderParam);
const auto& lightMgr = compoSys.GetManager_Direct<LightManager>();
const auto& mainCamera = compoSys.GetMainCamera();
if (_useSkyScattering)
{
_skyScatteringRenderer.CheckRenderAbleWithUpdateCB(engine.GetDirectX(), engine.GetTransformPool(), lightMgr, mainCamera);
if (_skyScatteringRenderer.GetRenderAble())
_skyScatteringRenderer.Render(engine.GetDirectX(), mainCamera, lightMgr);
}
_mainRenderer.UpdateCB(dx, mainCamera, lightMgr);
const SkyBoxMaterial* skyboxMaterial = _materialManager.Find<SkyBoxMaterial>(mainCamera.GetSkyBoxMaterialID());
_mainRenderer.Render(dx, MainRenderer::Param{mainCamera, meshRenderParam, _materialManager, lightMgr, ShadowSystem{shadowMgr, _shadowRenderer}, std::move(cullParam), skyboxMaterial});
_postProcessing.SetElapsedTime(dt);
_postProcessing.UpdateCB(dx);
_postProcessing.Render(dx, _mainRenderer, mainCamera);
AutoBinderSampler<PixelShader> sampler(dx, SamplerStateBindIndex(0), SamplerState::Point);
_backBufferMaker.Render(dx, dx.GetBackBufferRT(), *_mainRenderer.GetResultMap()->GetTexture2D());
dx.GetSwapChain()->Present(0, 0);
_shadowRenderer.ClearDirty();
}
void RenderingSystem::Destroy(Engine& engine)
{
}
MaterialID RenderingSystem::ActivateSkyScattering(Engine& engine, uint resolution, const Object& directionalLightObject)
{
assert(_useSkyScattering == false);
_useSkyScattering = true;
Size<uint> viewport = engine.GetDirectX().GetBackBufferRect().size.Cast<uint>();
uint minSize = std::min(viewport.w, viewport.h);
auto Log2Uint = [](uint i) -> uint
{
return static_cast<uint>(log(static_cast<float>(i)) / log(2.0f));
};
resolution = std::min(static_cast<uint>(1 << Log2Uint(minSize)), resolution);
_skyScatteringRenderer.Initialize(engine.GetDirectX(), _bufferManager, _shaderManager, _materialManager, resolution);
assert(directionalLightObject.HasComponent<DirectionalLight>());
_skyScatteringRenderer.SetDirectionalLightID(directionalLightObject.GetObjectID());
return _skyScatteringRenderer.GetMaterialID();
}
void RenderingSystem::DeactivateSkyScattering()
{
assert(_useSkyScattering);
_useSkyScattering = false;
_skyScatteringRenderer.Destroy();
}
<|endoftext|> |
<commit_before>//===- BasicCalleeAnalysis.cpp - Determine callees per call site ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SILAnalysis/BasicCalleeAnalysis.h"
#include "swift/AST/Decl.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILPasses/Utils/Local.h"
#include <algorithm>
using namespace swift;
void CalleeCache::sortAndUniqueCallees() {
llvm::DenseMap<SILFunction *, unsigned int> FunctionEnumeration;
// Enumerate the functions in the module to use as keys in sorting.
unsigned int count = 0;
for (auto &F : M)
FunctionEnumeration[&F] = count++;
auto Lookup = [&FunctionEnumeration](SILFunction *F) -> unsigned int {
auto It = FunctionEnumeration.find(F);
assert(It != FunctionEnumeration.end() &&
"Function unexpectedly not found in enumeration!");
return It->second;
};
// Sort the callees for each decl and remove duplicates.
for (auto &Pair : TheCache) {
auto &Callees = *Pair.second.getPointer();
// Sort by enumeration number so that clients get a stable order.
std::sort(Callees.begin(), Callees.end(),
[&Lookup](SILFunction *Left, SILFunction *Right) {
return Lookup(Left) < Lookup(Right);
});
// Remove duplicates.
Callees.erase(std::unique(Callees.begin(), Callees.end()), Callees.end());
}
}
CalleeCache::CalleesAndCanCallUnknown &
CalleeCache::getOrCreateCalleesForMethod(SILDeclRef Decl) {
auto *AFD = cast<AbstractFunctionDecl>(Decl.getDecl());
auto Found = TheCache.find(AFD);
if (Found != TheCache.end())
return Found->second;
auto *TheCallees = new Callees;
bool canCallUnknown = !calleesAreStaticallyKnowable(M, Decl);
CalleesAndCanCallUnknown Entry(TheCallees, canCallUnknown);
bool Inserted;
CacheType::iterator It;
std::tie(It, Inserted) = TheCache.insert(std::make_pair(AFD, Entry));
assert(Inserted && "Expected new entry to be inserted!");
return It->second;
}
/// Update the callees for each method of a given class, along with
/// all the overridden methods from superclasses.
void CalleeCache::computeClassMethodCalleesForClass(ClassDecl *CD) {
for (auto *Member : CD->getMembers()) {
auto *AFD = dyn_cast<AbstractFunctionDecl>(Member);
if (!AFD)
continue;
auto Method = SILDeclRef(AFD);
auto *CalledFn = M.lookUpFunctionInVTable(CD, Method);
if (!CalledFn)
continue;
bool canCallUnknown = !calleesAreStaticallyKnowable(M, Method);
// Update the callees for this method and all the methods it
// overrides by inserting the call graph node for the function
// that this method invokes.
do {
auto &TheCallees = getOrCreateCalleesForMethod(Method);
assert(TheCallees.getPointer() && "Unexpected null callees!");
TheCallees.getPointer()->push_back(CalledFn);
if (canCallUnknown)
TheCallees.setInt(true);
Method = Method.getOverriddenVTableEntry();
} while (Method);
}
}
void CalleeCache::computeWitnessMethodCalleesForWitnessTable(
SILWitnessTable &WT) {
for (const SILWitnessTable::Entry &Entry : WT.getEntries()) {
if (Entry.getKind() != SILWitnessTable::Method)
continue;
auto &WitnessEntry = Entry.getMethodWitness();
auto Requirement = WitnessEntry.Requirement;
auto *WitnessFn = WitnessEntry.Witness;
// Dead function elimination nulls out entries for functions it removes.
if (!WitnessFn)
continue;
auto &TheCallees = getOrCreateCalleesForMethod(Requirement);
assert(TheCallees.getPointer() && "Unexpected null callees!");
TheCallees.getPointer()->push_back(WitnessFn);
// FIXME: For now, conservatively assume that unknown functions
// can be called from any witness_method call site.
TheCallees.setInt(true);
}
}
/// Compute the callees for each method that appears in a VTable or
/// Witness Table.
void CalleeCache::computeMethodCallees() {
for (auto &VTable : M.getVTableList())
computeClassMethodCalleesForClass(VTable.getClass());
for (auto &WTable : M.getWitnessTableList())
computeWitnessMethodCalleesForWitnessTable(WTable);
}
SILFunction *
CalleeCache::getSingleCalleeForWitnessMethod(WitnessMethodInst *WMI) const {
SILFunction *CalleeFn;
ArrayRef<Substitution> Subs;
SILWitnessTable *WT;
// Attempt to find a specific callee for the given conformance and member.
std::tie(CalleeFn, WT, Subs) = WMI->getModule().lookUpFunctionInWitnessTable(
WMI->getConformance(), WMI->getMember());
return CalleeFn;
}
// Look up the precomputed callees for an abstract function and
// return it as a CalleeList.
CalleeList CalleeCache::getCalleeList(AbstractFunctionDecl *Decl) const {
auto Found = TheCache.find(Decl);
if (Found == TheCache.end())
return CalleeList();
auto &Pair = Found->second;
return CalleeList(*Pair.getPointer(), Pair.getInt());
}
// Return a callee list for the given witness method.
CalleeList CalleeCache::getCalleeList(WitnessMethodInst *WMI) const {
// First attempt to see if we can narrow it down to a single
// function based on the conformance.
if (auto *CalleeFn = getSingleCalleeForWitnessMethod(WMI))
return CalleeList(CalleeFn);
// Otherwise see if we previously computed the callees based on
// witness tables.
auto *Decl = cast<AbstractFunctionDecl>(WMI->getMember().getDecl());
return getCalleeList(Decl);
}
// Return a callee list for a given class method.
CalleeList CalleeCache::getCalleeList(ClassMethodInst *CMI) const {
// Look for precomputed callees based on vtables.
auto *Decl = cast<AbstractFunctionDecl>(CMI->getMember().getDecl());
return getCalleeList(Decl);
}
// Return the list of functions that can be called via the given callee.
CalleeList CalleeCache::getCalleeListForCalleeKind(SILValue Callee) const {
switch (Callee->getKind()) {
default:
assert(!isa<MethodInst>(Callee) &&
"Unhandled method instruction in call graph construction!");
return CalleeList();
case ValueKind::ThinToThickFunctionInst:
Callee = cast<ThinToThickFunctionInst>(Callee)->getOperand();
SWIFT_FALLTHROUGH;
case ValueKind::FunctionRefInst:
return CalleeList(cast<FunctionRefInst>(Callee)->getReferencedFunction());
case ValueKind::PartialApplyInst:
return getCalleeListForCalleeKind(
cast<PartialApplyInst>(Callee)->getCallee());
case ValueKind::WitnessMethodInst:
return getCalleeList(cast<WitnessMethodInst>(Callee));
case ValueKind::ClassMethodInst:
return getCalleeList(cast<ClassMethodInst>(Callee));
case ValueKind::SuperMethodInst:
case ValueKind::DynamicMethodInst:
return CalleeList();
}
}
// Return the list of functions that can be called via the given apply
// site.
CalleeList CalleeCache::getCalleeList(FullApplySite FAS) const {
return getCalleeListForCalleeKind(FAS.getCallee());
}
<commit_msg>Tweak comment and assert in refactored code.<commit_after>//===- BasicCalleeAnalysis.cpp - Determine callees per call site ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SILAnalysis/BasicCalleeAnalysis.h"
#include "swift/AST/Decl.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILPasses/Utils/Local.h"
#include <algorithm>
using namespace swift;
void CalleeCache::sortAndUniqueCallees() {
llvm::DenseMap<SILFunction *, unsigned int> FunctionEnumeration;
// Enumerate the functions in the module to use as keys in sorting.
unsigned int count = 0;
for (auto &F : M)
FunctionEnumeration[&F] = count++;
auto Lookup = [&FunctionEnumeration](SILFunction *F) -> unsigned int {
auto It = FunctionEnumeration.find(F);
assert(It != FunctionEnumeration.end() &&
"Function unexpectedly not found in enumeration!");
return It->second;
};
// Sort the callees for each decl and remove duplicates.
for (auto &Pair : TheCache) {
auto &Callees = *Pair.second.getPointer();
// Sort by enumeration number so that clients get a stable order.
std::sort(Callees.begin(), Callees.end(),
[&Lookup](SILFunction *Left, SILFunction *Right) {
return Lookup(Left) < Lookup(Right);
});
// Remove duplicates.
Callees.erase(std::unique(Callees.begin(), Callees.end()), Callees.end());
}
}
CalleeCache::CalleesAndCanCallUnknown &
CalleeCache::getOrCreateCalleesForMethod(SILDeclRef Decl) {
auto *AFD = cast<AbstractFunctionDecl>(Decl.getDecl());
auto Found = TheCache.find(AFD);
if (Found != TheCache.end())
return Found->second;
auto *TheCallees = new Callees;
bool canCallUnknown = !calleesAreStaticallyKnowable(M, Decl);
CalleesAndCanCallUnknown Entry(TheCallees, canCallUnknown);
bool Inserted;
CacheType::iterator It;
std::tie(It, Inserted) = TheCache.insert(std::make_pair(AFD, Entry));
assert(Inserted && "Expected new entry to be inserted!");
return It->second;
}
/// Update the callees for each method of a given class, along with
/// all the overridden methods from superclasses.
void CalleeCache::computeClassMethodCalleesForClass(ClassDecl *CD) {
for (auto *Member : CD->getMembers()) {
auto *AFD = dyn_cast<AbstractFunctionDecl>(Member);
if (!AFD)
continue;
auto Method = SILDeclRef(AFD);
auto *CalledFn = M.lookUpFunctionInVTable(CD, Method);
if (!CalledFn)
continue;
bool canCallUnknown = !calleesAreStaticallyKnowable(M, Method);
// Update the callees for this method and all the methods it
// overrides by adding this function to their lists.
do {
auto &TheCallees = getOrCreateCalleesForMethod(Method);
assert(TheCallees.getPointer() && "Unexpected null callees!");
TheCallees.getPointer()->push_back(CalledFn);
if (canCallUnknown)
TheCallees.setInt(true);
Method = Method.getOverriddenVTableEntry();
} while (Method);
}
}
void CalleeCache::computeWitnessMethodCalleesForWitnessTable(
SILWitnessTable &WT) {
for (const SILWitnessTable::Entry &Entry : WT.getEntries()) {
if (Entry.getKind() != SILWitnessTable::Method)
continue;
auto &WitnessEntry = Entry.getMethodWitness();
auto Requirement = WitnessEntry.Requirement;
auto *WitnessFn = WitnessEntry.Witness;
// Dead function elimination nulls out entries for functions it removes.
if (!WitnessFn)
continue;
auto &TheCallees = getOrCreateCalleesForMethod(Requirement);
assert(TheCallees.getPointer() && "Unexpected null callees!");
TheCallees.getPointer()->push_back(WitnessFn);
// FIXME: For now, conservatively assume that unknown functions
// can be called from any witness_method call site.
TheCallees.setInt(true);
}
}
/// Compute the callees for each method that appears in a VTable or
/// Witness Table.
void CalleeCache::computeMethodCallees() {
for (auto &VTable : M.getVTableList())
computeClassMethodCalleesForClass(VTable.getClass());
for (auto &WTable : M.getWitnessTableList())
computeWitnessMethodCalleesForWitnessTable(WTable);
}
SILFunction *
CalleeCache::getSingleCalleeForWitnessMethod(WitnessMethodInst *WMI) const {
SILFunction *CalleeFn;
ArrayRef<Substitution> Subs;
SILWitnessTable *WT;
// Attempt to find a specific callee for the given conformance and member.
std::tie(CalleeFn, WT, Subs) = WMI->getModule().lookUpFunctionInWitnessTable(
WMI->getConformance(), WMI->getMember());
return CalleeFn;
}
// Look up the precomputed callees for an abstract function and
// return it as a CalleeList.
CalleeList CalleeCache::getCalleeList(AbstractFunctionDecl *Decl) const {
auto Found = TheCache.find(Decl);
if (Found == TheCache.end())
return CalleeList();
auto &Pair = Found->second;
return CalleeList(*Pair.getPointer(), Pair.getInt());
}
// Return a callee list for the given witness method.
CalleeList CalleeCache::getCalleeList(WitnessMethodInst *WMI) const {
// First attempt to see if we can narrow it down to a single
// function based on the conformance.
if (auto *CalleeFn = getSingleCalleeForWitnessMethod(WMI))
return CalleeList(CalleeFn);
// Otherwise see if we previously computed the callees based on
// witness tables.
auto *Decl = cast<AbstractFunctionDecl>(WMI->getMember().getDecl());
return getCalleeList(Decl);
}
// Return a callee list for a given class method.
CalleeList CalleeCache::getCalleeList(ClassMethodInst *CMI) const {
// Look for precomputed callees based on vtables.
auto *Decl = cast<AbstractFunctionDecl>(CMI->getMember().getDecl());
return getCalleeList(Decl);
}
// Return the list of functions that can be called via the given callee.
CalleeList CalleeCache::getCalleeListForCalleeKind(SILValue Callee) const {
switch (Callee->getKind()) {
default:
assert(!isa<MethodInst>(Callee) &&
"Unhandled method instruction in callee determination!");
return CalleeList();
case ValueKind::ThinToThickFunctionInst:
Callee = cast<ThinToThickFunctionInst>(Callee)->getOperand();
SWIFT_FALLTHROUGH;
case ValueKind::FunctionRefInst:
return CalleeList(cast<FunctionRefInst>(Callee)->getReferencedFunction());
case ValueKind::PartialApplyInst:
return getCalleeListForCalleeKind(
cast<PartialApplyInst>(Callee)->getCallee());
case ValueKind::WitnessMethodInst:
return getCalleeList(cast<WitnessMethodInst>(Callee));
case ValueKind::ClassMethodInst:
return getCalleeList(cast<ClassMethodInst>(Callee));
case ValueKind::SuperMethodInst:
case ValueKind::DynamicMethodInst:
return CalleeList();
}
}
// Return the list of functions that can be called via the given apply
// site.
CalleeList CalleeCache::getCalleeList(FullApplySite FAS) const {
return getCalleeListForCalleeKind(FAS.getCallee());
}
<|endoftext|> |
<commit_before>//===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Top-level implementation for the PowerPC target.
//
//===----------------------------------------------------------------------===//
#include "PPC.h"
#include "PPCTargetAsmInfo.h"
#include "PPCTargetMachine.h"
#include "llvm/PassManager.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Support/FormattedStream.h"
using namespace llvm;
extern "C" void LLVMInitializePowerPCTarget() {
// Register the targets
RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
}
const TargetAsmInfo *PPCTargetMachine::createTargetAsmInfo() const {
if (Subtarget.isDarwin())
return new PPCDarwinTargetAsmInfo(*this);
return new PPCLinuxTargetAsmInfo(*this);
}
PPCTargetMachine::PPCTargetMachine(const Target &T, const std::string &TT,
const std::string &FS, bool is64Bit)
: LLVMTargetMachine(T, TT),
Subtarget(TT, FS, is64Bit),
DataLayout(Subtarget.getTargetDataString()), InstrInfo(*this),
FrameInfo(*this, is64Bit), JITInfo(*this, is64Bit), TLInfo(*this),
InstrItins(Subtarget.getInstrItineraryData()), MachOWriterInfo(*this) {
if (getRelocationModel() == Reloc::Default) {
if (Subtarget.isDarwin())
setRelocationModel(Reloc::DynamicNoPIC);
else
setRelocationModel(Reloc::Static);
}
}
/// Override this for PowerPC. Tail merging happily breaks up instruction issue
/// groups, which typically degrades performance.
bool PPCTargetMachine::getEnableTailMergeDefault() const { return false; }
PPC32TargetMachine::PPC32TargetMachine(const Target &T, const std::string &TT,
const std::string &FS)
: PPCTargetMachine(T, TT, FS, false) {
}
PPC64TargetMachine::PPC64TargetMachine(const Target &T, const std::string &TT,
const std::string &FS)
: PPCTargetMachine(T, TT, FS, true) {
}
//===----------------------------------------------------------------------===//
// Pass Pipeline Configuration
//===----------------------------------------------------------------------===//
bool PPCTargetMachine::addInstSelector(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
// Install an instruction selector.
PM.add(createPPCISelDag(*this));
return false;
}
bool PPCTargetMachine::addPreEmitPass(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
// Must run branch selection immediately preceding the asm printer.
PM.add(createPPCBranchSelectionPass());
return false;
}
bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
MachineCodeEmitter &MCE) {
// The JIT should use the static relocation model in ppc32 mode, PIC in ppc64.
// FIXME: This should be moved to TargetJITInfo!!
if (Subtarget.isPPC64()) {
// We use PIC codegen in ppc64 mode, because otherwise we'd have to use many
// instructions to materialize arbitrary global variable + function +
// constant pool addresses.
setRelocationModel(Reloc::PIC_);
// Temporary workaround for the inability of PPC64 JIT to handle jump
// tables.
DisableJumpTables = true;
} else {
setRelocationModel(Reloc::Static);
}
// Inform the subtarget that we are in JIT mode. FIXME: does this break macho
// writing?
Subtarget.SetJITMode();
// Machine code emitter pass for PowerPC.
PM.add(createPPCCodeEmitterPass(*this, MCE));
return false;
}
bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
JITCodeEmitter &JCE) {
// The JIT should use the static relocation model in ppc32 mode, PIC in ppc64.
// FIXME: This should be moved to TargetJITInfo!!
if (Subtarget.isPPC64()) {
// We use PIC codegen in ppc64 mode, because otherwise we'd have to use many
// instructions to materialize arbitrary global variable + function +
// constant pool addresses.
setRelocationModel(Reloc::PIC_);
// Temporary workaround for the inability of PPC64 JIT to handle jump
// tables.
DisableJumpTables = true;
} else {
setRelocationModel(Reloc::Static);
}
// Inform the subtarget that we are in JIT mode. FIXME: does this break macho
// writing?
Subtarget.SetJITMode();
// Machine code emitter pass for PowerPC.
PM.add(createPPCJITCodeEmitterPass(*this, JCE));
return false;
}
bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
ObjectCodeEmitter &OCE) {
// The JIT should use the static relocation model in ppc32 mode, PIC in ppc64.
// FIXME: This should be moved to TargetJITInfo!!
if (Subtarget.isPPC64()) {
// We use PIC codegen in ppc64 mode, because otherwise we'd have to use many
// instructions to materialize arbitrary global variable + function +
// constant pool addresses.
setRelocationModel(Reloc::PIC_);
// Temporary workaround for the inability of PPC64 JIT to handle jump
// tables.
DisableJumpTables = true;
} else {
setRelocationModel(Reloc::Static);
}
// Inform the subtarget that we are in JIT mode. FIXME: does this break macho
// writing?
Subtarget.SetJITMode();
// Machine code emitter pass for PowerPC.
PM.add(createPPCObjectCodeEmitterPass(*this, OCE));
return false;
}
bool PPCTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
MachineCodeEmitter &MCE) {
// Machine code emitter pass for PowerPC.
PM.add(createPPCCodeEmitterPass(*this, MCE));
return false;
}
bool PPCTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
JITCodeEmitter &JCE) {
// Machine code emitter pass for PowerPC.
PM.add(createPPCJITCodeEmitterPass(*this, JCE));
return false;
}
bool PPCTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
ObjectCodeEmitter &OCE) {
// Machine code emitter pass for PowerPC.
PM.add(createPPCObjectCodeEmitterPass(*this, OCE));
return false;
}
<commit_msg>second half of commit.<commit_after>//===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Top-level implementation for the PowerPC target.
//
//===----------------------------------------------------------------------===//
#include "PPC.h"
#include "PPCTargetAsmInfo.h"
#include "PPCTargetMachine.h"
#include "llvm/PassManager.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Support/FormattedStream.h"
using namespace llvm;
extern "C" void LLVMInitializePowerPCTarget() {
// Register the targets
RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
}
const TargetAsmInfo *PPCTargetMachine::createTargetAsmInfo() const {
if (Subtarget.isDarwin())
return new PPCDarwinTargetAsmInfo(Subtarget.isPPC64());
return new PPCLinuxTargetAsmInfo(Subtarget.isPPC64());
}
PPCTargetMachine::PPCTargetMachine(const Target &T, const std::string &TT,
const std::string &FS, bool is64Bit)
: LLVMTargetMachine(T, TT),
Subtarget(TT, FS, is64Bit),
DataLayout(Subtarget.getTargetDataString()), InstrInfo(*this),
FrameInfo(*this, is64Bit), JITInfo(*this, is64Bit), TLInfo(*this),
InstrItins(Subtarget.getInstrItineraryData()), MachOWriterInfo(*this) {
if (getRelocationModel() == Reloc::Default) {
if (Subtarget.isDarwin())
setRelocationModel(Reloc::DynamicNoPIC);
else
setRelocationModel(Reloc::Static);
}
}
/// Override this for PowerPC. Tail merging happily breaks up instruction issue
/// groups, which typically degrades performance.
bool PPCTargetMachine::getEnableTailMergeDefault() const { return false; }
PPC32TargetMachine::PPC32TargetMachine(const Target &T, const std::string &TT,
const std::string &FS)
: PPCTargetMachine(T, TT, FS, false) {
}
PPC64TargetMachine::PPC64TargetMachine(const Target &T, const std::string &TT,
const std::string &FS)
: PPCTargetMachine(T, TT, FS, true) {
}
//===----------------------------------------------------------------------===//
// Pass Pipeline Configuration
//===----------------------------------------------------------------------===//
bool PPCTargetMachine::addInstSelector(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
// Install an instruction selector.
PM.add(createPPCISelDag(*this));
return false;
}
bool PPCTargetMachine::addPreEmitPass(PassManagerBase &PM,
CodeGenOpt::Level OptLevel) {
// Must run branch selection immediately preceding the asm printer.
PM.add(createPPCBranchSelectionPass());
return false;
}
bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
MachineCodeEmitter &MCE) {
// The JIT should use the static relocation model in ppc32 mode, PIC in ppc64.
// FIXME: This should be moved to TargetJITInfo!!
if (Subtarget.isPPC64()) {
// We use PIC codegen in ppc64 mode, because otherwise we'd have to use many
// instructions to materialize arbitrary global variable + function +
// constant pool addresses.
setRelocationModel(Reloc::PIC_);
// Temporary workaround for the inability of PPC64 JIT to handle jump
// tables.
DisableJumpTables = true;
} else {
setRelocationModel(Reloc::Static);
}
// Inform the subtarget that we are in JIT mode. FIXME: does this break macho
// writing?
Subtarget.SetJITMode();
// Machine code emitter pass for PowerPC.
PM.add(createPPCCodeEmitterPass(*this, MCE));
return false;
}
bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
JITCodeEmitter &JCE) {
// The JIT should use the static relocation model in ppc32 mode, PIC in ppc64.
// FIXME: This should be moved to TargetJITInfo!!
if (Subtarget.isPPC64()) {
// We use PIC codegen in ppc64 mode, because otherwise we'd have to use many
// instructions to materialize arbitrary global variable + function +
// constant pool addresses.
setRelocationModel(Reloc::PIC_);
// Temporary workaround for the inability of PPC64 JIT to handle jump
// tables.
DisableJumpTables = true;
} else {
setRelocationModel(Reloc::Static);
}
// Inform the subtarget that we are in JIT mode. FIXME: does this break macho
// writing?
Subtarget.SetJITMode();
// Machine code emitter pass for PowerPC.
PM.add(createPPCJITCodeEmitterPass(*this, JCE));
return false;
}
bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
ObjectCodeEmitter &OCE) {
// The JIT should use the static relocation model in ppc32 mode, PIC in ppc64.
// FIXME: This should be moved to TargetJITInfo!!
if (Subtarget.isPPC64()) {
// We use PIC codegen in ppc64 mode, because otherwise we'd have to use many
// instructions to materialize arbitrary global variable + function +
// constant pool addresses.
setRelocationModel(Reloc::PIC_);
// Temporary workaround for the inability of PPC64 JIT to handle jump
// tables.
DisableJumpTables = true;
} else {
setRelocationModel(Reloc::Static);
}
// Inform the subtarget that we are in JIT mode. FIXME: does this break macho
// writing?
Subtarget.SetJITMode();
// Machine code emitter pass for PowerPC.
PM.add(createPPCObjectCodeEmitterPass(*this, OCE));
return false;
}
bool PPCTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
MachineCodeEmitter &MCE) {
// Machine code emitter pass for PowerPC.
PM.add(createPPCCodeEmitterPass(*this, MCE));
return false;
}
bool PPCTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
JITCodeEmitter &JCE) {
// Machine code emitter pass for PowerPC.
PM.add(createPPCJITCodeEmitterPass(*this, JCE));
return false;
}
bool PPCTargetMachine::addSimpleCodeEmitter(PassManagerBase &PM,
CodeGenOpt::Level OptLevel,
ObjectCodeEmitter &OCE) {
// Machine code emitter pass for PowerPC.
PM.add(createPPCObjectCodeEmitterPass(*this, OCE));
return false;
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2000-2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "mysql_priv.h"
#include <stdarg.h>
/* Send a error string to client */
void send_error(NET *net, uint sql_errno, const char *err)
{
uint length;
char buff[MYSQL_ERRMSG_SIZE+2];
THD *thd=current_thd;
DBUG_ENTER("send_error");
DBUG_PRINT("enter",("sql_errno: %d err: %s", sql_errno,
err ? err : net->last_error[0] ?
net->last_error : "NULL"));
query_cache_abort(net);
if (thd)
thd->query_error = 1; // needed to catch query errors during replication
if (!err)
{
if (sql_errno)
err=ER(sql_errno);
else
{
if ((err=net->last_error)[0])
sql_errno=net->last_errno;
else
{
sql_errno=ER_UNKNOWN_ERROR;
err=ER(sql_errno); /* purecov: inspected */
}
}
}
if (net->vio == 0)
{
if (thd && thd->bootstrap)
{
/* In bootstrap it's ok to print on stderr */
fprintf(stderr,"ERROR: %d %s\n",sql_errno,err);
}
DBUG_VOID_RETURN;
}
if (net->return_errno)
{ // new client code; Add errno before message
int2store(buff,sql_errno);
length= (uint) (strmake(buff+2,err,MYSQL_ERRMSG_SIZE-1) - buff);
err=buff;
}
else
{
length=(uint) strlen(err);
set_if_smaller(length,MYSQL_ERRMSG_SIZE);
}
VOID(net_write_command(net,(uchar) 255,(char*) err,length));
if (thd)
thd->fatal_error=0; // Error message is given
DBUG_VOID_RETURN;
}
/*
At some point we need to be able to distinguish between warnings and
errors; The following function will help make this easier.
*/
void send_warning(NET *net, uint sql_errno, const char *err)
{
DBUG_ENTER("send_warning");
send_error(net,sql_errno,err);
DBUG_VOID_RETURN;
}
/*
Write error package and flush to client
It's a little too low level, but I don't want to allow another buffer
*/
/* VARARGS3 */
void
net_printf(NET *net, uint errcode, ...)
{
va_list args;
uint length,offset;
const char *format,*text_pos;
int head_length= NET_HEADER_SIZE;
THD *thd=current_thd;
DBUG_ENTER("net_printf");
DBUG_PRINT("enter",("message: %u",errcode));
if (thd)
thd->query_error = 1; // if we are here, something is wrong :-)
query_cache_abort(net); // Safety
va_start(args,errcode);
/*
The following is needed to make net_printf() work with 0 argument for
errorcode and use the argument after that as the format string. This
is useful for rare errors that are not worth the hassle to put in
errmsg.sys, but at the same time, the message is not fixed text
*/
if (errcode)
format= ER(errcode);
else
{
format=va_arg(args,char*);
errcode= ER_UNKNOWN_ERROR;
}
offset= net->return_errno ? 2 : 0;
text_pos=(char*) net->buff+head_length+offset+1;
(void) vsprintf(my_const_cast(char*) (text_pos),format,args);
length=(uint) strlen((char*) text_pos);
if (length >= sizeof(net->last_error))
length=sizeof(net->last_error)-1; /* purecov: inspected */
va_end(args);
if (net->vio == 0)
{
if (thd && thd->bootstrap)
{
/*
In bootstrap it's ok to print on stderr
This may also happen when we get an error from a slave thread
*/
fprintf(stderr,"ERROR: %d %s\n",errcode,text_pos);
thd->fatal_error=1;
}
DBUG_VOID_RETURN;
}
int3store(net->buff,length+1+offset);
net->buff[3]= (net->compress) ? 0 : (uchar) (net->pkt_nr++);
net->buff[head_length]=(uchar) 255; // Error package
if (offset)
int2store(text_pos-2, errcode);
VOID(net_real_write(net,(char*) net->buff,length+head_length+1+offset));
if (thd)
thd->fatal_error=0; // Error message is given
DBUG_VOID_RETURN;
}
void
send_ok(NET *net,ha_rows affected_rows,ulonglong id,const char *message)
{
if (net->no_send_ok) // hack for re-parsing queries
return;
char buff[MYSQL_ERRMSG_SIZE+10],*pos;
DBUG_ENTER("send_ok");
buff[0]=0; // No fields
pos=net_store_length(buff+1,(ulonglong) affected_rows);
pos=net_store_length(pos, (ulonglong) id);
if (net->return_status)
{
int2store(pos,*net->return_status);
pos+=2;
}
if (message)
pos=net_store_data((char*) pos,message);
if (net->vio != 0)
{
VOID(my_net_write(net,buff,(uint) (pos-buff)));
VOID(net_flush(net));
}
DBUG_VOID_RETURN;
}
void
send_eof(NET *net,bool no_flush)
{
static char eof_buff[1]= { (char) 254 }; /* Marker for end of fields */
DBUG_ENTER("send_eof");
if (net->vio != 0)
{
VOID(my_net_write(net,eof_buff,1));
if (!no_flush)
VOID(net_flush(net));
}
DBUG_VOID_RETURN;
}
/****************************************************************************
** Store a field length in logical packet
****************************************************************************/
char *
net_store_length(char *pkg, ulonglong length)
{
uchar *packet=(uchar*) pkg;
if (length < LL(251))
{
*packet=(uchar) length;
return (char*) packet+1;
}
/* 251 is reserved for NULL */
if (length < LL(65536))
{
*packet++=252;
int2store(packet,(uint) length);
return (char*) packet+2;
}
if (length < LL(16777216))
{
*packet++=253;
int3store(packet,(ulong) length);
return (char*) packet+3;
}
*packet++=254;
int8store(packet,length);
return (char*) packet+8;
}
char *
net_store_length(char *pkg, uint length)
{
uchar *packet=(uchar*) pkg;
if (length < 251)
{
*packet=(uchar) length;
return (char*) packet+1;
}
*packet++=252;
int2store(packet,(uint) length);
return (char*) packet+2;
}
/* The following will only be used for short strings < 65K */
char *
net_store_data(char *to,const char *from)
{
uint length=(uint) strlen(from);
to=net_store_length(to,length);
memcpy(to,from,length);
return to+length;
}
char *
net_store_data(char *to,int32 from)
{
char buff[20];
uint length=(uint) (int10_to_str(from,buff,10)-buff);
to=net_store_length(to,length);
memcpy(to,buff,length);
return to+length;
}
char *
net_store_data(char *to,longlong from)
{
char buff[22];
uint length=(uint) (longlong10_to_str(from,buff,10)-buff);
to=net_store_length(to,length);
memcpy(to,buff,length);
return to+length;
}
bool net_store_null(String *packet)
{
return packet->append((char) 251);
}
bool
net_store_data(String *packet,const char *from,uint length)
{
ulong packet_length=packet->length();
if (packet_length+9+length > packet->alloced_length() &&
packet->realloc(packet_length+9+length))
return 1;
char *to=(char*) net_store_length((char*) packet->ptr()+packet_length,
(ulonglong) length);
memcpy(to,from,length);
packet->length((uint) (to+length-packet->ptr()));
return 0;
}
/* The following is only used at short, null terminated data */
bool
net_store_data(String *packet,const char *from)
{
uint length=(uint) strlen(from);
uint packet_length=packet->length();
/*
3 is the longest coding for storing a string with the used
net_store_length() function. We use 5 here 'just in case'
*/
if (packet_length+5+length > packet->alloced_length() &&
packet->realloc(packet_length+5+length))
return 1;
char *to=(char*) net_store_length((char*) packet->ptr()+packet_length,
length);
memcpy(to,from,length);
packet->length((uint) (to+length-packet->ptr()));
return 0;
}
bool
net_store_data(String *packet,uint32 from)
{
char buff[20];
return net_store_data(packet,(char*) buff,
(uint) (int10_to_str(from,buff,10)-buff));
}
bool
net_store_data(String *packet, longlong from)
{
char buff[22];
return net_store_data(packet,(char*) buff,
(uint) (longlong10_to_str(from,buff,10)-buff));
}
bool
net_store_data(String *packet,struct tm *tmp)
{
char buff[20];
sprintf(buff,"%04d-%02d-%02d %02d:%02d:%02d",
((int) (tmp->tm_year+1900)) % 10000,
(int) tmp->tm_mon+1,
(int) tmp->tm_mday,
(int) tmp->tm_hour,
(int) tmp->tm_min,
(int) tmp->tm_sec);
return net_store_data(packet,(char*) buff,19);
}
bool net_store_data(String* packet, I_List<i_string>* str_list)
{
char buf[256];
String tmp(buf, sizeof(buf));
tmp.length(0);
I_List_iterator<i_string> it(*str_list);
i_string* s;
while ((s=it++))
{
if (tmp.length())
tmp.append(',');
tmp.append(s->ptr);
}
return net_store_data(packet, (char*)tmp.ptr(), tmp.length());
}
/*
** translate and store data; These are mainly used by the SHOW functions
*/
bool
net_store_data(String *packet,CONVERT *convert, const char *from,uint length)
{
if (convert)
return convert->store(packet, from, length);
return net_store_data(packet,from,length);
}
bool
net_store_data(String *packet, CONVERT *convert, const char *from)
{
uint length=(uint) strlen(from);
if (convert)
return convert->store(packet, from, length);
return net_store_data(packet,from,length);
}
/*
Function called by my_net_init() to set some check variables
*/
extern "C" {
void my_net_local_init(NET *net)
{
net->max_packet= (uint) global_system_variables.net_buffer_length;
net->read_timeout= (uint) global_system_variables.net_read_timeout;
net->write_timeout=(uint) global_system_variables.net_write_timeout;
net->retry_count= (uint) global_system_variables.net_retry_count;
net->max_packet_size= max(global_system_variables.net_buffer_length,
global_system_variables.max_allowed_packet);
}
}
<commit_msg>use my_vsnprintf() just in case bug#4925<commit_after>/* Copyright (C) 2000-2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "mysql_priv.h"
#include <stdarg.h>
/* Send a error string to client */
void send_error(NET *net, uint sql_errno, const char *err)
{
uint length;
char buff[MYSQL_ERRMSG_SIZE+2];
THD *thd=current_thd;
DBUG_ENTER("send_error");
DBUG_PRINT("enter",("sql_errno: %d err: %s", sql_errno,
err ? err : net->last_error[0] ?
net->last_error : "NULL"));
query_cache_abort(net);
if (thd)
thd->query_error = 1; // needed to catch query errors during replication
if (!err)
{
if (sql_errno)
err=ER(sql_errno);
else
{
if ((err=net->last_error)[0])
sql_errno=net->last_errno;
else
{
sql_errno=ER_UNKNOWN_ERROR;
err=ER(sql_errno); /* purecov: inspected */
}
}
}
if (net->vio == 0)
{
if (thd && thd->bootstrap)
{
/* In bootstrap it's ok to print on stderr */
fprintf(stderr,"ERROR: %d %s\n",sql_errno,err);
}
DBUG_VOID_RETURN;
}
if (net->return_errno)
{ // new client code; Add errno before message
int2store(buff,sql_errno);
length= (uint) (strmake(buff+2,err,MYSQL_ERRMSG_SIZE-1) - buff);
err=buff;
}
else
{
length=(uint) strlen(err);
set_if_smaller(length,MYSQL_ERRMSG_SIZE);
}
VOID(net_write_command(net,(uchar) 255,(char*) err,length));
if (thd)
thd->fatal_error=0; // Error message is given
DBUG_VOID_RETURN;
}
/*
At some point we need to be able to distinguish between warnings and
errors; The following function will help make this easier.
*/
void send_warning(NET *net, uint sql_errno, const char *err)
{
DBUG_ENTER("send_warning");
send_error(net,sql_errno,err);
DBUG_VOID_RETURN;
}
/*
Write error package and flush to client
It's a little too low level, but I don't want to allow another buffer
*/
/* VARARGS3 */
void
net_printf(NET *net, uint errcode, ...)
{
va_list args;
uint length,offset;
const char *format,*text_pos;
int head_length= NET_HEADER_SIZE;
THD *thd=current_thd;
DBUG_ENTER("net_printf");
DBUG_PRINT("enter",("message: %u",errcode));
if (thd)
thd->query_error = 1; // if we are here, something is wrong :-)
query_cache_abort(net); // Safety
va_start(args,errcode);
/*
The following is needed to make net_printf() work with 0 argument for
errorcode and use the argument after that as the format string. This
is useful for rare errors that are not worth the hassle to put in
errmsg.sys, but at the same time, the message is not fixed text
*/
if (errcode)
format= ER(errcode);
else
{
format=va_arg(args,char*);
errcode= ER_UNKNOWN_ERROR;
}
offset= net->return_errno ? 2 : 0;
text_pos=(char*) net->buff+head_length+offset+1;
(void) my_vsnprintf(my_const_cast(char*) (text_pos),
(char*)net->buff_end-text_pos,
format,args);
length=(uint) strlen((char*) text_pos);
if (length >= sizeof(net->last_error))
length=sizeof(net->last_error)-1; /* purecov: inspected */
va_end(args);
if (net->vio == 0)
{
if (thd && thd->bootstrap)
{
/*
In bootstrap it's ok to print on stderr
This may also happen when we get an error from a slave thread
*/
fprintf(stderr,"ERROR: %d %s\n",errcode,text_pos);
thd->fatal_error=1;
}
DBUG_VOID_RETURN;
}
int3store(net->buff,length+1+offset);
net->buff[3]= (net->compress) ? 0 : (uchar) (net->pkt_nr++);
net->buff[head_length]=(uchar) 255; // Error package
if (offset)
int2store(text_pos-2, errcode);
VOID(net_real_write(net,(char*) net->buff,length+head_length+1+offset));
if (thd)
thd->fatal_error=0; // Error message is given
DBUG_VOID_RETURN;
}
void
send_ok(NET *net,ha_rows affected_rows,ulonglong id,const char *message)
{
if (net->no_send_ok) // hack for re-parsing queries
return;
char buff[MYSQL_ERRMSG_SIZE+10],*pos;
DBUG_ENTER("send_ok");
buff[0]=0; // No fields
pos=net_store_length(buff+1,(ulonglong) affected_rows);
pos=net_store_length(pos, (ulonglong) id);
if (net->return_status)
{
int2store(pos,*net->return_status);
pos+=2;
}
if (message)
pos=net_store_data((char*) pos,message);
if (net->vio != 0)
{
VOID(my_net_write(net,buff,(uint) (pos-buff)));
VOID(net_flush(net));
}
DBUG_VOID_RETURN;
}
void
send_eof(NET *net,bool no_flush)
{
static char eof_buff[1]= { (char) 254 }; /* Marker for end of fields */
DBUG_ENTER("send_eof");
if (net->vio != 0)
{
VOID(my_net_write(net,eof_buff,1));
if (!no_flush)
VOID(net_flush(net));
}
DBUG_VOID_RETURN;
}
/****************************************************************************
** Store a field length in logical packet
****************************************************************************/
char *
net_store_length(char *pkg, ulonglong length)
{
uchar *packet=(uchar*) pkg;
if (length < LL(251))
{
*packet=(uchar) length;
return (char*) packet+1;
}
/* 251 is reserved for NULL */
if (length < LL(65536))
{
*packet++=252;
int2store(packet,(uint) length);
return (char*) packet+2;
}
if (length < LL(16777216))
{
*packet++=253;
int3store(packet,(ulong) length);
return (char*) packet+3;
}
*packet++=254;
int8store(packet,length);
return (char*) packet+8;
}
char *
net_store_length(char *pkg, uint length)
{
uchar *packet=(uchar*) pkg;
if (length < 251)
{
*packet=(uchar) length;
return (char*) packet+1;
}
*packet++=252;
int2store(packet,(uint) length);
return (char*) packet+2;
}
/* The following will only be used for short strings < 65K */
char *
net_store_data(char *to,const char *from)
{
uint length=(uint) strlen(from);
to=net_store_length(to,length);
memcpy(to,from,length);
return to+length;
}
char *
net_store_data(char *to,int32 from)
{
char buff[20];
uint length=(uint) (int10_to_str(from,buff,10)-buff);
to=net_store_length(to,length);
memcpy(to,buff,length);
return to+length;
}
char *
net_store_data(char *to,longlong from)
{
char buff[22];
uint length=(uint) (longlong10_to_str(from,buff,10)-buff);
to=net_store_length(to,length);
memcpy(to,buff,length);
return to+length;
}
bool net_store_null(String *packet)
{
return packet->append((char) 251);
}
bool
net_store_data(String *packet,const char *from,uint length)
{
ulong packet_length=packet->length();
if (packet_length+9+length > packet->alloced_length() &&
packet->realloc(packet_length+9+length))
return 1;
char *to=(char*) net_store_length((char*) packet->ptr()+packet_length,
(ulonglong) length);
memcpy(to,from,length);
packet->length((uint) (to+length-packet->ptr()));
return 0;
}
/* The following is only used at short, null terminated data */
bool
net_store_data(String *packet,const char *from)
{
uint length=(uint) strlen(from);
uint packet_length=packet->length();
/*
3 is the longest coding for storing a string with the used
net_store_length() function. We use 5 here 'just in case'
*/
if (packet_length+5+length > packet->alloced_length() &&
packet->realloc(packet_length+5+length))
return 1;
char *to=(char*) net_store_length((char*) packet->ptr()+packet_length,
length);
memcpy(to,from,length);
packet->length((uint) (to+length-packet->ptr()));
return 0;
}
bool
net_store_data(String *packet,uint32 from)
{
char buff[20];
return net_store_data(packet,(char*) buff,
(uint) (int10_to_str(from,buff,10)-buff));
}
bool
net_store_data(String *packet, longlong from)
{
char buff[22];
return net_store_data(packet,(char*) buff,
(uint) (longlong10_to_str(from,buff,10)-buff));
}
bool
net_store_data(String *packet,struct tm *tmp)
{
char buff[20];
sprintf(buff,"%04d-%02d-%02d %02d:%02d:%02d",
((int) (tmp->tm_year+1900)) % 10000,
(int) tmp->tm_mon+1,
(int) tmp->tm_mday,
(int) tmp->tm_hour,
(int) tmp->tm_min,
(int) tmp->tm_sec);
return net_store_data(packet,(char*) buff,19);
}
bool net_store_data(String* packet, I_List<i_string>* str_list)
{
char buf[256];
String tmp(buf, sizeof(buf));
tmp.length(0);
I_List_iterator<i_string> it(*str_list);
i_string* s;
while ((s=it++))
{
if (tmp.length())
tmp.append(',');
tmp.append(s->ptr);
}
return net_store_data(packet, (char*)tmp.ptr(), tmp.length());
}
/*
** translate and store data; These are mainly used by the SHOW functions
*/
bool
net_store_data(String *packet,CONVERT *convert, const char *from,uint length)
{
if (convert)
return convert->store(packet, from, length);
return net_store_data(packet,from,length);
}
bool
net_store_data(String *packet, CONVERT *convert, const char *from)
{
uint length=(uint) strlen(from);
if (convert)
return convert->store(packet, from, length);
return net_store_data(packet,from,length);
}
/*
Function called by my_net_init() to set some check variables
*/
extern "C" {
void my_net_local_init(NET *net)
{
net->max_packet= (uint) global_system_variables.net_buffer_length;
net->read_timeout= (uint) global_system_variables.net_read_timeout;
net->write_timeout=(uint) global_system_variables.net_write_timeout;
net->retry_count= (uint) global_system_variables.net_retry_count;
net->max_packet_size= max(global_system_variables.net_buffer_length,
global_system_variables.max_allowed_packet);
}
}
<|endoftext|> |
<commit_before>// RUN: %clang --analyze -Xclang -analyzer-checker=core,experimental.cplusplus.Iterators -Xclang -verify %s
// XFAIL: win32
// FIXME: Does not work with inlined C++ methods.
// XFAIL: *
#include <vector>
void fum(std::vector<int>::iterator t);
void foo1()
{
// iterators that are defined but not initialized
std::vector<int>::iterator it2;
fum(it2); // expected-warning{{Use of iterator that is not defined}}
*it2; // expected-warning{{Use of iterator that is not defined}}
std::vector<int> v, vv;
std::vector<int>::iterator it = v.begin();
fum(it); // no-warning
*it; // no-warning
// a valid iterator plus an integer is still valid
std::vector<int>::iterator et = it + 3;
while(it != et) { // no-warning
if (*it == 0) // no-warning
*it = 1; // no-warning
}
// iterators from different instances Cannot be compared
et = vv.end();
while(it != et) // expected-warning{{Cannot compare iterators from different containers}}
;
for( std::vector<int>::iterator it = v.begin(); it != v.end(); it++ ) { // no-warning
if (*it == 1) // no-warning
*it = 0; // no-warning
}
// copying a valid iterator results in a valid iterator
et = it; // no-warning
*et; // no-warning
// any combo of valid iterator plus a constant is still valid
et = it + 2; // no-warning
*et; // no-warning
et = 2 + it; // no-warning
*et; // no-warning
et = 2 + 4 + it; // no-warning
*et; // no-warning
// calling insert invalidates unless assigned to as result, but still
// invalidates other iterators on the same instance
it = v.insert( it, 1 ); // no-warning
*et; // expected-warning{{Attempt to use an iterator made invalid by call to 'insert'}}
++it; // no-warning
// calling erase invalidates the iterator
v.erase(it); // no-warning
et = it + 2; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
et = 2 + it + 2; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
et = 2 + it; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
++it; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
it++; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
*it; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
it = v.insert( it, 1 ); // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
// now valid after return from insert
*it; // no-warning
}
// work with using namespace
void foo2()
{
using namespace std;
vector<int> v;
vector<int>::iterator it = v.begin();
*it; // no-warning
v.insert( it, 1 ); // no-warning
*it; // expected-warning{{Attempt to use an iterator made invalid by call to 'insert'}}
it = v.insert( it, 1 ); // expected-warning{{Attempt to use an iterator made invalid by call to 'insert'}}
*it; // no-warning
}
// using reserve eliminates some warnings
void foo3()
{
std::vector<long> v;
std::vector<long>::iterator b = v.begin();
v.reserve( 100 );
// iterator assigned before the reserve is still invalidated
*b; // expected-warning{{Attempt to use an iterator made invalid by call to 'reserve'}}
b = v.begin();
v.insert( b, 1 ); // no-warning
// iterator after assignment is still valid (probably)
*b; // no-warning
}
// check on copying one iterator to another
void foo4()
{
std::vector<float> v, vv;
std::vector<float>::iterator it = v.begin();
*it; // no-warning
v = vv;
*it; // expected-warning{{Attempt to use an iterator made invalid by copying another container to its container}}
}
<commit_msg>test/Analysis/iterators.cpp: Mark as REQUIRES:asserts. It crashes due to assertion failure.<commit_after>// RUN: %clang --analyze -Xclang -analyzer-checker=core,experimental.cplusplus.Iterators -Xclang -verify %s
// XFAIL: win32
// FIXME: Does not work with inlined C++ methods.
// XFAIL: *
// Crashes due to assertion failure.
// REQUIRES: asserts
#include <vector>
void fum(std::vector<int>::iterator t);
void foo1()
{
// iterators that are defined but not initialized
std::vector<int>::iterator it2;
fum(it2); // expected-warning{{Use of iterator that is not defined}}
*it2; // expected-warning{{Use of iterator that is not defined}}
std::vector<int> v, vv;
std::vector<int>::iterator it = v.begin();
fum(it); // no-warning
*it; // no-warning
// a valid iterator plus an integer is still valid
std::vector<int>::iterator et = it + 3;
while(it != et) { // no-warning
if (*it == 0) // no-warning
*it = 1; // no-warning
}
// iterators from different instances Cannot be compared
et = vv.end();
while(it != et) // expected-warning{{Cannot compare iterators from different containers}}
;
for( std::vector<int>::iterator it = v.begin(); it != v.end(); it++ ) { // no-warning
if (*it == 1) // no-warning
*it = 0; // no-warning
}
// copying a valid iterator results in a valid iterator
et = it; // no-warning
*et; // no-warning
// any combo of valid iterator plus a constant is still valid
et = it + 2; // no-warning
*et; // no-warning
et = 2 + it; // no-warning
*et; // no-warning
et = 2 + 4 + it; // no-warning
*et; // no-warning
// calling insert invalidates unless assigned to as result, but still
// invalidates other iterators on the same instance
it = v.insert( it, 1 ); // no-warning
*et; // expected-warning{{Attempt to use an iterator made invalid by call to 'insert'}}
++it; // no-warning
// calling erase invalidates the iterator
v.erase(it); // no-warning
et = it + 2; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
et = 2 + it + 2; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
et = 2 + it; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
++it; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
it++; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
*it; // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
it = v.insert( it, 1 ); // expected-warning{{Attempt to use an iterator made invalid by call to 'erase'}}
// now valid after return from insert
*it; // no-warning
}
// work with using namespace
void foo2()
{
using namespace std;
vector<int> v;
vector<int>::iterator it = v.begin();
*it; // no-warning
v.insert( it, 1 ); // no-warning
*it; // expected-warning{{Attempt to use an iterator made invalid by call to 'insert'}}
it = v.insert( it, 1 ); // expected-warning{{Attempt to use an iterator made invalid by call to 'insert'}}
*it; // no-warning
}
// using reserve eliminates some warnings
void foo3()
{
std::vector<long> v;
std::vector<long>::iterator b = v.begin();
v.reserve( 100 );
// iterator assigned before the reserve is still invalidated
*b; // expected-warning{{Attempt to use an iterator made invalid by call to 'reserve'}}
b = v.begin();
v.insert( b, 1 ); // no-warning
// iterator after assignment is still valid (probably)
*b; // no-warning
}
// check on copying one iterator to another
void foo4()
{
std::vector<float> v, vv;
std::vector<float>::iterator it = v.begin();
*it; // no-warning
v = vv;
*it; // expected-warning{{Attempt to use an iterator made invalid by copying another container to its container}}
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -std=c++11 -triple i686-linux %s -o /dev/null -S
//
// This test's failure mode is running ~forever. (For some value of "forever"
// that's greater than 25 minutes on my machine)
template <typename... Ts>
struct Foo {
template <typename... T>
static void ignore() {}
Foo() { ignore<Ts...>(); }
};
struct Base {
Base();
~Base();
};
#define STAMP(thiz, prev) using thiz = Foo< \
prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, \
prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, \
prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev \
>;
STAMP(A, Base);
STAMP(B, A);
STAMP(C, B);
STAMP(D, C);
STAMP(E, D);
STAMP(F, E);
STAMP(G, F);
STAMP(H, G);
STAMP(I, H);
STAMP(J, I);
STAMP(K, J);
STAMP(L, K);
STAMP(M, L);
STAMP(N, M);
STAMP(O, N);
STAMP(P, O);
STAMP(Q, P);
int main() { Q q; }
<commit_msg>Attempt #2 to appease buildbots<commit_after>// RUN: %clang_cc1 -std=c++11 -triple i686-linux-gnu %s -o /dev/null -S -emit-llvm
//
// This test's failure mode is running ~forever. (For some value of "forever"
// that's greater than 25 minutes on my machine)
template <typename... Ts>
struct Foo {
template <typename... T>
static void ignore() {}
Foo() { ignore<Ts...>(); }
};
struct Base {
Base();
~Base();
};
#define STAMP(thiz, prev) using thiz = Foo< \
prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, \
prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, \
prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev, prev \
>;
STAMP(A, Base);
STAMP(B, A);
STAMP(C, B);
STAMP(D, C);
STAMP(E, D);
STAMP(F, E);
STAMP(G, F);
STAMP(H, G);
STAMP(I, H);
STAMP(J, I);
STAMP(K, J);
STAMP(L, K);
STAMP(M, L);
STAMP(N, M);
STAMP(O, N);
STAMP(P, O);
STAMP(Q, P);
int main() { Q q; }
<|endoftext|> |
<commit_before>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include "timer.h"
using namespace std;
/*
* first is a symbol or file name
* second is the fuzzy match score, smaller is better
*/
typedef pair<string, int> fuzzy_match;
bool is_fuzzy_match(const string& symbol, const string& query,
int* inter_count) {
int qi = 0;
int si = 0;
int lastmatch = -1;
// The number of characters between fuzzy matches. This is 0 if
// query is a substring of symbol. Larger values of inter_count
// will generally be worse matches than smaller values.
*inter_count = 0;
while (qi < query.length() && si < symbol.length()) {
if (query[qi] == symbol[si]) {
if (lastmatch != -1) {
*inter_count += si - lastmatch - 1;
}
lastmatch = si;
++qi;
}
++si;
}
return qi == query.length();
}
vector<string> read_tags_file(const char* tagfile) {
vector<string> tags;
ifstream tag_stream(tagfile);
bool expecting_filename = false;
string line;
while (!tag_stream.eof()) {
getline(tag_stream, line);
if (expecting_filename) {
expecting_filename = false;
size_t comma = line.find(',');
if (comma != string::npos) {
tags.push_back(line.substr(0, comma));
}
} else if (line[0] == 0x0C) {
expecting_filename = true;
continue;
} else {
size_t tag_start = line.find(0x7F);
if (tag_start == string::npos) {
continue;
}
size_t tag_end = line.find(0x01, tag_start);
if (tag_end == string::npos) {
continue;
}
string symbol = line.substr(tag_start + 1, tag_end-tag_start-1);
tags.push_back(symbol);
}
}
return tags;
}
bool is_better_match(const fuzzy_match& lhs, const fuzzy_match& rhs) {
if (lhs.second < rhs.second) {
return true;
} else if (lhs.second == rhs.second) {
if (lhs.first.length() < rhs.first.length()) {
return true;
}
}
return false;
}
vector<fuzzy_match> find_fuzzy_matches(const vector<string>& tags,
const string& query) {
vector<fuzzy_match> matches;
for (int i = 0; i < tags.size(); ++i) {
const string& symbol = tags[i];
int inter_count;
if (is_fuzzy_match(symbol, query, &inter_count)) {
matches.push_back(make_pair(symbol, inter_count));
}
}
return matches;
}
int main(int argc, char** argv) {
if (argc != 2) {
cerr << "usage: " << argv[0] << " tagfile" << endl;
return 1;
}
vector<string> tags = read_tags_file(argv[1]);
while (!cin.eof()) {
string query;
getline(cin, query);
if (query.length()) {
Timer t;
vector<fuzzy_match> matches = find_fuzzy_matches(tags, query);
const size_t limit = 32;
if (matches.size() > limit) {
partial_sort(matches.begin(), matches.begin()+limit, matches.end(),
is_better_match);
}
for (int i = 0; i < min(limit, matches.size()); ++i) {
cout << "MATCH " << matches[i].first << endl;
}
cout << "DONE " << t.elapsedMS() << "ms " <<
"#match: " << matches.size() << endl;
} else {
cout << "DONE" << endl;
}
}
return 0;
}
<commit_msg>[mural] Store more metadata from the tags file<commit_after>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include "timer.h"
using namespace std;
struct TagInfo {
string symbol;
string file;
int row;
TagInfo(const string& _symbol, const string& _file, int _row)
: symbol(_symbol), row(_row), file(_file) {}
};
bool is_fuzzy_match(const string& symbol, const string& query,
int* inter_count) {
int qi = 0;
int si = 0;
int lastmatch = -1;
// The number of characters between fuzzy matches. This is 0 if
// query is a substring of symbol. Larger values of inter_count
// will generally be worse matches than smaller values.
*inter_count = 0;
while (qi < query.length() && si < symbol.length()) {
if (query[qi] == symbol[si]) {
if (lastmatch != -1) {
*inter_count += si - lastmatch - 1;
}
lastmatch = si;
++qi;
}
++si;
}
return qi == query.length();
}
vector<TagInfo> read_tags_file(const char* tagfile) {
ifstream tag_stream(tagfile);
vector<TagInfo> tags;
bool expecting_filename = false;
string current_filename;
while (!tag_stream.eof()) {
string line;
getline(tag_stream, line);
if (expecting_filename) {
expecting_filename = false;
size_t comma = line.find(',');
if (comma != string::npos) {
current_filename = line.substr(0, comma);
tags.push_back(TagInfo(current_filename, current_filename, 0));
}
} else if (line[0] == 0x0C) {
expecting_filename = true;
continue;
} else {
size_t tag_start = line.find(0x7F);
if (tag_start == string::npos) {
continue;
}
size_t tag_end = line.find(0x01, tag_start);
if (tag_end == string::npos) {
continue;
}
size_t col_end = line.find(',', tag_end);
if (col_end == string::npos) {
continue;
}
string symbol = line.substr(tag_start + 1, tag_end-tag_start-1);
string column = line.substr(tag_end+1, col_end);
tags.push_back(TagInfo(symbol, current_filename, atoi(column.c_str())));
}
}
return tags;
}
typedef pair<const TagInfo*, int> FuzzyMatch;
bool is_better_match(const FuzzyMatch& lhs, const FuzzyMatch& rhs) {
if (lhs.second < rhs.second) {
return true;
} else if (lhs.second == rhs.second) {
if (lhs.first->symbol.length() < rhs.first->symbol.length()) {
return true;
}
}
return false;
}
vector<TagInfo> find_fuzzy_matches(const vector<TagInfo>& tags,
const string& query,
const size_t limit) {
vector<FuzzyMatch> matches;
for (int i = 0; i < tags.size(); ++i) {
int inter_count;
const TagInfo& tag = tags[i];
if (is_fuzzy_match(tag.symbol, query, &inter_count)) {
matches.push_back(make_pair(&tag, inter_count));
}
}
if (matches.size() > limit) {
partial_sort(matches.begin(), matches.begin()+limit, matches.end(),
is_better_match);
}
vector<TagInfo> result;
for (int i = 0; i < min(limit, matches.size()); ++i) {
result.push_back(*(matches[i].first));
}
return result;
}
int main(int argc, char** argv) {
if (argc != 2) {
cerr << "usage: " << argv[0] << " tagfile" << endl;
return 1;
}
vector<TagInfo> tags = read_tags_file(argv[1]);
while (!cin.eof()) {
string query;
getline(cin, query);
if (query.length()) {
Timer t;
vector<TagInfo> matches = find_fuzzy_matches(tags, query, 32);
for (int i = 0; i < matches.size(); ++i) {
const TagInfo& match = matches[i];
cout << "MATCH " << match.symbol << endl;
}
cout << "DONE " << t.elapsedMS() << "ms " <<
"#match: " << matches.size() << endl;
} else {
cout << "DONE" << endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>
#include "levels/wave.h"
#include <fstream>
#include <sstream>
#include <string>
#include "engine/game-manager.h"
#include "base/debug.h"
void Wave::Load() {
// Create filename
std::stringstream filename;
filename << "assets/waves/level_" << level_ << ".wave";
// Open file
std::ifstream wave_info(filename.str().c_str());
unsigned accum = 0;
// Read filename
while (wave_info) {
Enemy new_enemy;
// Get spawn time
unsigned seconds;
wave_info >> seconds;
accum = seconds + accum;
new_enemy.spawn_time = sf::seconds(accum);
// Get enemy name
std::string name;
wave_info >> name;
new_enemy.enemy = new EnemyUnit(name);
new_enemy.enemy->Load();
// Get position
sf::Vector2f pos(GameManager::GetWindowSize());
float position = 0;
wave_info >> position;
pos.y = (position / 100) * GameManager::GetWindowSize().y;
// See the spawn
pos.x = GameManager::GetWindowSize().x - 50;
cout << pos.x << " - ";
cout << pos.y << endl;
new_enemy.enemy->set_position(pos);
// Add enemy to wave
wave_.push_back(new_enemy);
}
wave_.pop_back();
}
void Wave::Start() {
clock_.restart();
}
void Wave::Step(sf::Time elapsed) {
auto instances = GameManager::GetInstancesManager();
auto elapsed_time = clock_.getElapsedTime();
while (true) {
if (elapsed_time < wave_[current_enemy_].spawn_time) {
break;
}
instances->AddInstance(wave_[current_enemy_].enemy);
current_enemy_++;
if (current_enemy_ >= wave_.size()) {
instances->RemoveInstance(this);
delete this;
return;
}
}
}
<commit_msg>Remove magic number<commit_after>
#include "levels/wave.h"
#include <fstream>
#include <sstream>
#include <string>
#include "engine/game-manager.h"
#include "base/debug.h"
void Wave::Load() {
// Create filename
std::stringstream filename;
filename << "assets/waves/level_" << level_ << ".wave";
// Open file
std::ifstream wave_info(filename.str().c_str());
unsigned accum = 0;
// Read filename
while (wave_info) {
Enemy new_enemy;
// Get spawn time
unsigned seconds;
wave_info >> seconds;
accum = seconds + accum;
new_enemy.spawn_time = sf::seconds(accum);
// Get enemy name
std::string name;
wave_info >> name;
new_enemy.enemy = new EnemyUnit(name);
new_enemy.enemy->Load();
// Get position
sf::Vector2f pos(GameManager::GetWindowSize());
float position = 0;
wave_info >> position;
pos.y = (position / 100) * GameManager::GetWindowSize().y;
// See the spawn
pos.x = GameManager::GetWindowSize().x;
cout << pos.x << " - ";
cout << pos.y << endl;
new_enemy.enemy->set_position(pos);
// Add enemy to wave
wave_.push_back(new_enemy);
}
wave_.pop_back();
}
void Wave::Start() {
clock_.restart();
}
void Wave::Step(sf::Time elapsed) {
auto instances = GameManager::GetInstancesManager();
auto elapsed_time = clock_.getElapsedTime();
while (true) {
if (elapsed_time < wave_[current_enemy_].spawn_time) {
break;
}
instances->AddInstance(wave_[current_enemy_].enemy);
current_enemy_++;
if (current_enemy_ >= wave_.size()) {
instances->RemoveInstance(this);
delete this;
return;
}
}
}
<|endoftext|> |
<commit_before>// RUN: rm -rf %t
//
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -emit-module -fmodules-cache-path=%t -fmodule-name=diag_flags -x c++ %S/Inputs/module.map -fmodules-ts
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -verify -fmodules-cache-path=%t -I %S/Inputs %s -fmodules-ts
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -verify -fmodules-cache-path=%t -I %S/Inputs %s -fmodules-ts -DIMPLICIT_FLAG -Werror=padded
//
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -emit-module -fmodule-name=diag_flags -x c++ %S/Inputs/module.map -fmodules-ts -o %t/explicit.pcm -Werror=string-plus-int -Wpadded
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -verify -fmodules-cache-path=%t -I %S/Inputs %s -fmodules-ts -DEXPLICIT_FLAG -fmodule-file=%t/explicit.pcm
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -verify -fmodules-cache-path=%t -I %S/Inputs %s -fmodules-ts -DEXPLICIT_FLAG -fmodule-file=%t/explicit.pcm -Werror=padded
import diag_flags;
// Diagnostic flags from the module user make no difference to diagnostics
// emitted within the module when using an explicitly-loaded module.
#ifdef IMPLICIT_FLAG
// expected-error@diag_flags.h:14 {{padding struct}}
#elif defined(EXPLICIT_FLAG)
// expected-warning@diag_flags.h:14 {{padding struct}}
#else
// expected-no-diagnostics
#endif
unsigned n = sizeof(Padded);
<commit_msg>clang/test/Modules/diag-flags.cpp: Appease targeting *-win32 with explicit triple. Fixes r301846.<commit_after>// RUN: rm -rf %t
//
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fmodules -fimplicit-module-maps -emit-module -fmodules-cache-path=%t -fmodule-name=diag_flags -x c++ %S/Inputs/module.map -fmodules-ts
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fmodules -fimplicit-module-maps -verify -fmodules-cache-path=%t -I %S/Inputs %s -fmodules-ts
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fmodules -fimplicit-module-maps -verify -fmodules-cache-path=%t -I %S/Inputs %s -fmodules-ts -DIMPLICIT_FLAG -Werror=padded
//
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fmodules -fimplicit-module-maps -emit-module -fmodule-name=diag_flags -x c++ %S/Inputs/module.map -fmodules-ts -o %t/explicit.pcm -Werror=string-plus-int -Wpadded
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fmodules -fimplicit-module-maps -verify -fmodules-cache-path=%t -I %S/Inputs %s -fmodules-ts -DEXPLICIT_FLAG -fmodule-file=%t/explicit.pcm
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fmodules -fimplicit-module-maps -verify -fmodules-cache-path=%t -I %S/Inputs %s -fmodules-ts -DEXPLICIT_FLAG -fmodule-file=%t/explicit.pcm -Werror=padded
import diag_flags;
// Diagnostic flags from the module user make no difference to diagnostics
// emitted within the module when using an explicitly-loaded module.
#ifdef IMPLICIT_FLAG
// expected-error@diag_flags.h:14 {{padding struct}}
#elif defined(EXPLICIT_FLAG)
// expected-warning@diag_flags.h:14 {{padding struct}}
#else
// expected-no-diagnostics
#endif
unsigned n = sizeof(Padded);
<|endoftext|> |
<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// 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 "Methcla/Audio/Engine.hpp"
#include "Methcla/Audio/Group.hpp"
#include "Methcla/Audio/Node.hpp"
#include "Methcla/Audio/Synth.hpp"
using namespace Methcla::Audio;
Node::Node(Environment& env, Group* target, AddAction addAction)
: Resource(env, env.nodes().nextId())
{
env.nodes().insert(id(), this);
if (target == nullptr) {
m_parent = nullptr;
} else {
switch (addAction) {
case kAddToHead:
m_parent = target;
target->addToHead(*this);
break;
case kAddToTail:
m_parent = target;
target->addToTail(*this);
break;
}
}
}
Node::~Node()
{
env().nodes().remove(id());
}
void Node::free()
{
delete this;
}
<commit_msg>Remove superfluous include<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// 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 "Methcla/Audio/Engine.hpp"
#include "Methcla/Audio/Group.hpp"
#include "Methcla/Audio/Node.hpp"
using namespace Methcla::Audio;
Node::Node(Environment& env, Group* target, AddAction addAction)
: Resource(env, env.nodes().nextId())
{
env.nodes().insert(id(), this);
if (target == nullptr) {
m_parent = nullptr;
} else {
switch (addAction) {
case kAddToHead:
m_parent = target;
target->addToHead(*this);
break;
case kAddToTail:
m_parent = target;
target->addToTail(*this);
break;
}
}
}
Node::~Node()
{
env().nodes().remove(id());
}
void Node::free()
{
delete this;
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "gpac/module.h"
#include "gpac/modules/codec.h"
#include "gpac/modules/service.h"
#include "gpac/internal/terminal_dev.h"
using namespace std;
string signals_fld;
string modules_fld;
GF_ModuleManager *modules;
GF_Config *config;
static void term_on_connect(GF_ClientService *service, LPNETCHANNEL netch, GF_Err err)
{
}
static void term_on_disconnect(GF_ClientService *service, LPNETCHANNEL netch, GF_Err response)
{
}
static void term_on_command(GF_ClientService *service, GF_NetworkCommand *com, GF_Err response)
{
}
static void term_on_data_packet(GF_ClientService *service, LPNETCHANNEL netch, char *data, u32 data_size, GF_SLHeader *hdr, GF_Err reception_status){
}
static Bool is_same_od(GF_ObjectDescriptor *od1, GF_ObjectDescriptor *od2)
{
GF_ESD *esd1, *esd2;
if (gf_list_count(od1->ESDescriptors) != gf_list_count(od2->ESDescriptors)) return GF_FALSE;
esd1 = (GF_ESD *)gf_list_get(od1->ESDescriptors, 0);
if (!esd1) return GF_FALSE;
esd2 = (GF_ESD *)gf_list_get(od2->ESDescriptors, 0);
if (!esd2) return GF_FALSE;
if (esd1->ESID != esd2->ESID) return GF_FALSE;
if (esd1->decoderConfig->streamType != esd2->decoderConfig->streamType) return GF_FALSE;
if (esd1->decoderConfig->objectTypeIndication != esd2->decoderConfig->objectTypeIndication) return GF_FALSE;
return GF_TRUE;
}
static void term_on_media_add(GF_ClientService *service, GF_Descriptor *media_desc, Bool no_scene_check)
{
u32 i, min_od_id;
GF_MediaObject *the_mo;
GF_Scene *scene;
GF_ObjectManager *odm, *root;
GF_ObjectDescriptor *od;
GF_Terminal *term = service->term;
root = service->owner;
if (!root) {
GF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, ("[Service %s] has not root, aborting !\n", service->url));
return;
}
if (root->flags & GF_ODM_DESTROYED) {
GF_LOG(GF_LOG_ERROR, GF_LOG_MEDIA, ("[Service %s] root has been scheduled for destruction - aborting !\n", service->url));
return;
}
scene = root->subscene ? root->subscene : root->parentscene;
if (scene->root_od->addon && (scene->root_od->addon->addon_type == GF_ADDON_TYPE_MAIN)) {
no_scene_check = GF_TRUE;
scene->root_od->flags |= GF_ODM_REGENERATE_SCENE;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_MEDIA, ("[Service %s] %s\n", service->url, media_desc ? "Adding new media object" : "Regenerating scene graph"));
if (!media_desc) {
if (!no_scene_check)
gf_scene_regenerate(scene);
return;
}
switch (media_desc->tag) {
case GF_ODF_OD_TAG:
case GF_ODF_IOD_TAG:
if (root && (root->net_service == service)) {
od = (GF_ObjectDescriptor *)media_desc;
break;
}
default:
gf_odf_desc_del(media_desc);
return;
}
gf_term_lock_net(term, GF_TRUE);
/*object declared this way are not part of an OD stream and are considered as dynamic*/
/* od->objectDescriptorID = GF_MEDIA_EXTERNAL_ID; */
/*check if we have a mediaObject in the scene not attached and matching this object*/
the_mo = NULL;
odm = NULL;
min_od_id = 0;
for (i = 0; i<gf_list_count(scene->scene_objects); i++) {
char *frag, *ext;
GF_ESD *esd;
char *url;
u32 match_esid = 0;
GF_MediaObject *mo = (GF_MediaObject*)gf_list_get(scene->scene_objects, i);
if ((mo->OD_ID != GF_MEDIA_EXTERNAL_ID) && (min_od_id<mo->OD_ID))
min_od_id = mo->OD_ID;
if (!mo->odm) continue;
/*if object is attached to a service, don't bother looking in a different one*/
if (mo->odm->net_service && (mo->odm->net_service != service)) continue;
/*already assigned object - this may happen since the compositor has no control on when objects are declared by the service,
therefore opening file#video and file#audio may result in the objects being declared twice if the service doesn't
keep track of declared objects*/
if (mo->odm->OD) {
if (od->objectDescriptorID && is_same_od(mo->odm->OD, od)) {
/*reassign OD ID*/
if (mo->OD_ID != GF_MEDIA_EXTERNAL_ID) {
od->objectDescriptorID = mo->OD_ID;
}
else {
mo->OD_ID = od->objectDescriptorID;
}
gf_odf_desc_del(media_desc);
gf_term_lock_net(term, GF_FALSE);
return;
}
continue;
}
if (mo->OD_ID != GF_MEDIA_EXTERNAL_ID) {
if (mo->OD_ID == od->objectDescriptorID) {
the_mo = mo;
odm = mo->odm;
break;
}
continue;
}
if (!mo->URLs.count || !mo->URLs.vals[0].url) continue;
frag = NULL;
ext = strrchr(mo->URLs.vals[0].url, '#');
if (ext) {
frag = strchr(ext, '=');
ext[0] = 0;
}
url = mo->URLs.vals[0].url;
if (!strnicmp(url, "file://localhost", 16)) url += 16;
else if (!strnicmp(url, "file://", 7)) url += 7;
else if (!strnicmp(url, "gpac://", 7)) url += 7;
else if (!strnicmp(url, "pid://", 6)) match_esid = atoi(url + 6);
if (!match_esid && !strstr(service->url, url)) {
if (ext) ext[0] = '#';
continue;
}
if (ext) ext[0] = '#';
esd = (GF_ESD*)gf_list_get(od->ESDescriptors, 0);
if (match_esid && (esd->ESID != match_esid))
continue;
/*match type*/
switch (esd->decoderConfig->streamType) {
case GF_STREAM_VISUAL:
if (mo->type != GF_MEDIA_OBJECT_VIDEO) continue;
break;
case GF_STREAM_AUDIO:
if (mo->type != GF_MEDIA_OBJECT_AUDIO) continue;
break;
case GF_STREAM_PRIVATE_MEDIA:
if ((mo->type != GF_MEDIA_OBJECT_AUDIO) && (mo->type != GF_MEDIA_OBJECT_VIDEO)) continue;
break;
case GF_STREAM_SCENE:
if (mo->type != GF_MEDIA_OBJECT_UPDATES) continue;
break;
default:
continue;
}
if (frag) {
u32 frag_id = 0;
u32 ID = od->objectDescriptorID;
if (ID == GF_MEDIA_EXTERNAL_ID) ID = esd->ESID;
frag++;
frag_id = atoi(frag);
if (ID != frag_id) continue;
}
the_mo = mo;
odm = mo->odm;
break;
}
/*add a pass on scene->resource to check for min_od_id,
otherwise we may have another modules declaring an object with ID 0 from
another thread, which will assert (only one object with a givne OD ID)*/
for (i = 0; i<gf_list_count(scene->resources); i++) {
GF_ObjectManager *an_odm = (GF_ObjectManager *)gf_list_get(scene->resources, i);
if (an_odm->OD && (an_odm->OD->objectDescriptorID != GF_MEDIA_EXTERNAL_ID) && (min_od_id < an_odm->OD->objectDescriptorID))
min_od_id = an_odm->OD->objectDescriptorID;
}
if (!odm) {
odm = gf_odm_new();
odm->term = term;
odm->parentscene = scene;
gf_mx_p(scene->mx_resources);
gf_list_add(scene->resources, odm);
gf_mx_v(scene->mx_resources);
}
odm->flags |= GF_ODM_NOT_SETUP;
odm->OD = od;
odm->mo = the_mo;
odm->flags |= GF_ODM_NOT_IN_OD_STREAM;
if (!od->objectDescriptorID) {
od->objectDescriptorID = min_od_id + 1;
}
if (the_mo) the_mo->OD_ID = od->objectDescriptorID;
if (!scene->selected_service_id)
scene->selected_service_id = od->ServiceID;
/*net is unlocked before seting up the object as this might trigger events going into JS and deadlocks
with the compositor*/
gf_term_lock_net(term, GF_FALSE);
GF_LOG(GF_LOG_DEBUG, GF_LOG_MEDIA, ("[ODM%d] setup object - MO %08x\n", odm->OD->objectDescriptorID, odm->mo));
gf_odm_setup_object(odm, service);
/*OD inserted by service: resetup scene*/
if (!no_scene_check && scene->is_dynamic_scene) gf_scene_regenerate(scene);
}
void loadAccessor(const char* url){
GF_ClientService* net_service;
GF_BaseDecoder* ifce_acc = (GF_BaseDecoder*)gf_modules_load_interface_by_name(modules, "Accessor dec", GF_MEDIA_DECODER_INTERFACE);
GF_InputService* ifce_isom = (GF_InputService*)gf_modules_load_interface_by_name(modules, "GPAC IsoMedia Reader", GF_NET_CLIENT_INTERFACE);
GF_SAFEALLOC(net_service, GF_ClientService);
net_service->fn_connect_ack = term_on_connect;
net_service->fn_disconnect_ack = term_on_disconnect;
net_service->fn_command = term_on_command;
net_service->fn_data_packet = term_on_data_packet;
net_service->fn_add_media = term_on_media_add;
ifce_isom->ConnectService(ifce_isom, net_service, url);
//ASSERT_EQ(ifce_acc->CanHandleStream(ifce_acc, 0, NULL, 0), GF_CODEC_SUPPORTED);
ifce_acc->CanHandleStream(ifce_acc, 0, NULL, 0);
gf_modules_close_interface((GF_BaseInterface *)ifce_acc);
gf_modules_close_interface((GF_BaseInterface *)ifce_isom);
}
TEST(File, JPG) {
//void test_jpg() {
string file = signals_fld;
file.append("Freedom.jpg.bvr");
loadAccessor(file.c_str());
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
for (int i = 1; i < argc; i++) {
if (i + 1 != argc){
if (strcmp("-signals", argv[i]) == 0) {
signals_fld = argv[++i];
std::cout << "Test signal folder set to " << signals_fld << endl;
}
else if (strcmp("-modules", argv[i]) == 0) {
modules_fld = argv[++i];
std::cout << "Test modules folder set to " << modules_fld << endl;
}
}
}
gf_sys_init(GF_FALSE);
config = gf_cfg_init(NULL, NULL);
modules = gf_modules_new(NULL, config);
//test_jpg();
return RUN_ALL_TESTS();
}<commit_msg>Update tests<commit_after>#include "gtest/gtest.h"
#include "gpac/module.h"
#include "gpac/modules/codec.h"
#include "gpac/modules/service.h"
#include "gpac/internal/terminal_dev.h"
using namespace std;
string signals_fld;
string modules_fld;
GF_ModuleManager *modules;
GF_Config *config;
GF_MediaDecoder* ifce_acc;
static void term_on_connect(GF_ClientService *service, LPNETCHANNEL netch, GF_Err err)
{
service->ifce->GetServiceDescriptor(service->ifce, 1, "");
}
static void term_on_disconnect(GF_ClientService *service, LPNETCHANNEL netch, GF_Err response)
{
}
static void term_on_command(GF_ClientService *service, GF_NetworkCommand *com, GF_Err response)
{
}
static void term_on_data_packet(GF_ClientService *service, LPNETCHANNEL netch, char *data, u32 data_size, GF_SLHeader *hdr, GF_Err reception_status){
}
static Bool is_same_od(GF_ObjectDescriptor *od1, GF_ObjectDescriptor *od2)
{
return GF_TRUE;
}
static void term_on_media_add(GF_ClientService *service, GF_Descriptor *media_desc, Bool no_scene_check)
{
if (media_desc) {
GF_ESD *esd;
u32 e2;
GF_ObjectDescriptor *odm;
odm = (GF_ObjectDescriptor *)media_desc;
esd = (GF_ESD *)gf_list_get(odm->ESDescriptors, 0);
ASSERT_EQ(ifce_acc->CanHandleStream((GF_BaseDecoder*)ifce_acc, 0, esd, 0), GF_CODEC_SUPPORTED);
ifce_acc->AttachStream((GF_BaseDecoder*)ifce_acc, esd);
}
}
void loadAccessor(const char* url){
GF_ClientService* net_service;
GF_Descriptor *desc;
GF_Err e;
u32 od_type = 0;
char *ext, *redirect_url;
char *sub_url=NULL;
ifce_acc = (GF_MediaDecoder*)gf_modules_load_interface_by_name(modules, "Accessor dec", GF_MEDIA_DECODER_INTERFACE);
GF_InputService* ifce_isom = (GF_InputService*)gf_modules_load_interface_by_name(modules, "GPAC IsoMedia Reader", GF_NET_CLIENT_INTERFACE);
GF_SAFEALLOC(net_service, GF_ClientService);
net_service->fn_connect_ack = term_on_connect;
net_service->fn_disconnect_ack = term_on_disconnect;
net_service->fn_command = term_on_command;
net_service->fn_data_packet = term_on_data_packet;
net_service->fn_add_media = term_on_media_add;
net_service->ifce = ifce_isom;
/* Connecting */
e = ifce_isom->ConnectService(ifce_isom, net_service, url);
/* Decoding */
ifce_isom->ChannelGetSLP(ifce_isom, 0, 0, 0, 0, 0, 0, 0);
e = ifce_acc->ProcessData(ifce_acc, NULL, 0, 0, 0, 0, 0, 0, 0);
gf_modules_close_interface((GF_BaseInterface *)ifce_acc);
gf_modules_close_interface((GF_BaseInterface *)ifce_isom);
}
TEST(File, JPG) {
//void test_jpg() {
string file = signals_fld;
file.append("Freedom.jpg.bvr");
loadAccessor(file.c_str());
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
for (int i = 1; i < argc; i++) {
if (i + 1 != argc){
if (strcmp("-signals", argv[i]) == 0) {
signals_fld = argv[++i];
std::cout << "Test signal folder set to " << signals_fld << endl;
}
else if (strcmp("-modules", argv[i]) == 0) {
modules_fld = argv[++i];
std::cout << "Test modules folder set to " << modules_fld << endl;
}
}
}
gf_sys_init(GF_FALSE);
config = gf_cfg_init(NULL, NULL);
modules = gf_modules_new(NULL, config);
//test_jpg();
return RUN_ALL_TESTS();
}<|endoftext|> |
<commit_before>#include "Address.h"
Address::Address() : addr(0) {
}
Address::Address(uint16_t location) : addr(location) {
}
Address::Address(RegisterGroup from) : addr(from.value()) {
}
Address::Address(WordRegister from) : addr(from.value()) {
}
uint16_t Address::value() const {
return addr;
}
<commit_msg>Remove empty Address constructor<commit_after>#include "Address.h"
Address::Address(uint16_t location) : addr(location) {
}
Address::Address(RegisterGroup from) : addr(from.value()) {
}
Address::Address(WordRegister from) : addr(from.value()) {
}
uint16_t Address::value() const {
return addr;
}
<|endoftext|> |
<commit_before>#include "Binary.hpp"
#include <stdexcept>
#include <algorithm>
#include "constants.hpp"
#include "Tree.hpp"
using namespace std;
int safe_fclose(FILE* fptr) { return fptr ? fclose(fptr) : 0; }
Binary::Binary(const string& binary_file_path) : bin_fptr_(nullptr, safe_fclose)
{
// open the binary file
pll_binary_header_t header;
bin_fptr_ = unique_fptr(pllmod_binary_open(binary_file_path.c_str(), &header), safe_fclose);
if (!bin_fptr_)
throw runtime_error{"Could not open binary file for reading."};
if (header.access_type != PLLMOD_BIN_ACCESS_RANDOM)
throw runtime_error{"Binary file must be random access enabled."};
if (header.n_blocks <= 0)
throw runtime_error{string("Binary file header must have nonzero positive number of blocks: ")
+ to_string(header.n_blocks)};
// proccess the random access map
unsigned int n_blocks;
pll_block_map_t* block_map;
block_map = pllmod_binary_get_map(bin_fptr_.get(), &n_blocks);
assert(block_map);
assert(n_blocks);
for (size_t i = 0; i < n_blocks; i++)
{
map_.push_back(block_map[i]);
}
free(block_map);
}
static long int get_offset(vector<pll_block_map_t>& map, const int block_id)
{
auto item = map.begin();
while (item != map.end())
{
if (item->block_id == block_id)
break;
item++;
}
if(item == map.end())
throw runtime_error{string("Map does not contain block_id: ") + to_string(block_id)};
return item->block_offset;
}
void Binary::load_clv(pll_partition_t * partition, const unsigned int clv_index)
{
assert(bin_fptr_);
assert(clv_index < partition->clv_buffers + partition->tips);
if (partition->attributes & PLL_ATTRIB_PATTERN_TIP)
assert(clv_index >= partition->tips);
if (!(partition->clv[clv_index]))
{
size_t clv_size = partition->sites * partition->states_padded *
partition->rate_cats;
partition->clv[clv_index] = (double*) calloc(clv_size, sizeof(double));
}
unsigned int attributes;
auto err = pllmod_binary_clv_load(
bin_fptr_.get(),
0,
partition,
clv_index,
&attributes,
get_offset(map_, clv_index));
if (err != PLL_SUCCESS)
throw runtime_error{string("Loading CLV failed: ") + pll_errmsg};
}
void Binary::load_tipchars(pll_partition_t * partition, const unsigned int tipchars_index)
{
assert(bin_fptr_);
assert(tipchars_index < partition->tips);
assert(partition->attributes & PLL_ATTRIB_PATTERN_TIP);
unsigned int type, attributes;
size_t size;
auto ptr = pllmod_binary_custom_load(bin_fptr_.get(), 0, &size, &type, &attributes, get_offset(map_, tipchars_index));
if (!ptr)
throw runtime_error{string("Loading tipchar failed: ") + pll_errmsg};
partition->tipchars[tipchars_index] = (unsigned char*)ptr;
}
void Binary::load_scaler(pll_partition_t * partition, const unsigned int scaler_index)
{
assert(bin_fptr_);
assert(scaler_index < partition->scale_buffers);
auto block_offset = partition->clv_buffers + partition->tips;
unsigned int type, attributes;
size_t size;
auto ptr = pllmod_binary_custom_load(bin_fptr_.get(), 0,
&size, &type, &attributes, get_offset(map_, block_offset + scaler_index));
if (!ptr)
throw runtime_error{string("Loading scaler failed: ") + pll_errmsg};
partition->scale_buffer[scaler_index] = (unsigned int*)ptr;
}
static pll_partition_t* skeleton_partition()
{
auto attributes = PLL_ATTRIB_ARCH_SSE;
#ifdef __AVX
attributes = PLL_ATTRIB_ARCH_AVX;
#endif
attributes |= PLL_ATTRIB_PATTERN_TIP;
auto partition = pll_partition_create(
3, // number of tip nodes
1, // number of extra clv buffers
STATES,
1, // number of sites
1, // number of concurrent subs. models
1, // number of probabillity matrices
RATE_CATS,
1, // number of scale buffers
//pll_map_nt,
attributes);
if (!partition)
throw runtime_error{string("Creating skeleton partition: ") + pll_errmsg};
// ensure clv, tipchar and scaler fields are only shallowly allocated
// TODO
return partition;
}
static void dealloc_buffers(pll_partition_t* part)
{
// dealloc clvs and tipchars
if (part->tipchars)
for (size_t i = 0; i < part->tips; ++i)
{
pll_aligned_free(part->tipchars[i]);
part->tipchars[i] = nullptr;
}
if (part->clv)
{
size_t start = (part->attributes & PLL_ATTRIB_PATTERN_TIP) ? part->tips : 0;
for (size_t i = start; i < part->clv_buffers + part->tips; ++i)
{
pll_aligned_free(part->clv[i]);
part->clv[i] = nullptr;
}
}
if (part->scale_buffer)
{
for (size_t i = 0; i < part->scale_buffers; ++i)
{
free(part->scale_buffer[i]);
part->scale_buffer[i] = nullptr;
}
}
}
pll_partition_t* Binary::load_partition()
{
// make skeleton partition that only allocates the pointers to the clv/tipchar buffers
auto skelly = nullptr;// skeleton_partition();
unsigned int attributes = PLLMOD_BIN_ATTRIB_PARTITION_DUMP_WGT;
auto partition = pllmod_binary_partition_load(bin_fptr_.get(), 0, skelly, &attributes,
get_offset(map_, -1));
if (!partition)
throw runtime_error{string("Error loading partition: ") + pll_errmsg};
// free up buffers for things we want to load on demand
// TODO never alloc in the first place
dealloc_buffers(partition);
return partition;
}
pll_utree_t* Binary::load_utree()
{
unsigned int attributes = 0;
auto tree = pllmod_binary_utree_load(bin_fptr_.get(), 0, &attributes, get_offset(map_, -2));
if (!tree)
throw runtime_error{string("Loading tree: ") + pll_errmsg};
return tree;
}
/**
Writes the structures and data encapsulated in Tree to the specified file in the binary format.
Writes them in such a way that the Binary class can read them.
*/
void dump_to_binary(Tree& tree, const string& file)
{
auto num_clvs = tree.partition()->clv_buffers;
auto num_tips = tree.partition()->tips;
auto num_scalers = tree.partition()->scale_buffers;
auto max_clv_index = num_clvs + num_tips;
pll_binary_header_t header;
auto fptr = pllmod_binary_create(
file.c_str(),
&header,
PLLMOD_BIN_ACCESS_RANDOM,
2 + num_clvs + num_tips + num_scalers);
if(!fptr)
throw runtime_error{string("Opening binary file for writing: ") + pll_errmsg};
unsigned int attributes = PLLMOD_BIN_ATTRIB_UPDATE_MAP | PLLMOD_BIN_ATTRIB_PARTITION_DUMP_WGT;
int block_id = -2;
bool use_tipchars = tree.partition()->attributes & PLL_ATTRIB_PATTERN_TIP;
// dump the utree structure
if(!pllmod_binary_utree_dump(fptr, block_id++, tree.tree(), num_tips, attributes))
throw runtime_error{string("Dumping the utree to binary: ") + pll_errmsg};
// dump the partition
if(!pllmod_binary_partition_dump(fptr, block_id++, tree.partition(), attributes))
throw runtime_error{string("Dumping partition to binary: ") + pll_errmsg};
// dump the tipchars, but only if partition uses them
unsigned int tip_index = 0;
if (use_tipchars)
{
for (tip_index = 0; tip_index < num_tips; tip_index++)
{
if(!pllmod_binary_custom_dump(fptr, block_id++, tree.partition()->tipchars[tip_index],
tree.partition()->sites * sizeof(char), attributes))
throw runtime_error{string("Dumping tipchars to binary: ") + pll_errmsg};
}
}
// dump the clvs
for (unsigned int clv_index = tip_index; clv_index < max_clv_index; clv_index++)
{
if(!pllmod_binary_clv_dump(fptr, block_id++, tree.partition(), clv_index, attributes))
throw runtime_error{string("Dumping clvs to binary: ") + pll_errmsg};
}
// dump the scalers
for (unsigned int scaler_index = 0; scaler_index < num_scalers; scaler_index++)
{
if(!pllmod_binary_custom_dump(fptr, block_id++, tree.partition()->scale_buffer[scaler_index],
tree.partition()->sites * sizeof(unsigned int), attributes))
throw runtime_error{string("Dumping scalers to binary: ") + pll_errmsg};
}
fclose(fptr);
}
<commit_msg>fixed segfault in the avx version<commit_after>#include "Binary.hpp"
#include <stdexcept>
#include <algorithm>
#include "constants.hpp"
#include "Tree.hpp"
using namespace std;
int safe_fclose(FILE* fptr) { return fptr ? fclose(fptr) : 0; }
Binary::Binary(const string& binary_file_path) : bin_fptr_(nullptr, safe_fclose)
{
// open the binary file
pll_binary_header_t header;
bin_fptr_ = unique_fptr(pllmod_binary_open(binary_file_path.c_str(), &header), safe_fclose);
if (!bin_fptr_)
throw runtime_error{"Could not open binary file for reading."};
if (header.access_type != PLLMOD_BIN_ACCESS_RANDOM)
throw runtime_error{"Binary file must be random access enabled."};
if (header.n_blocks <= 0)
throw runtime_error{string("Binary file header must have nonzero positive number of blocks: ")
+ to_string(header.n_blocks)};
// proccess the random access map
unsigned int n_blocks;
pll_block_map_t* block_map;
block_map = pllmod_binary_get_map(bin_fptr_.get(), &n_blocks);
assert(block_map);
assert(n_blocks);
for (size_t i = 0; i < n_blocks; i++)
{
map_.push_back(block_map[i]);
}
free(block_map);
}
static long int get_offset(vector<pll_block_map_t>& map, const int block_id)
{
auto item = map.begin();
while (item != map.end())
{
if (item->block_id == block_id)
break;
item++;
}
if(item == map.end())
throw runtime_error{string("Map does not contain block_id: ") + to_string(block_id)};
return item->block_offset;
}
void Binary::load_clv(pll_partition_t * partition, const unsigned int clv_index)
{
assert(bin_fptr_);
assert(clv_index < partition->clv_buffers + partition->tips);
if (partition->attributes & PLL_ATTRIB_PATTERN_TIP)
assert(clv_index >= partition->tips);
if (!(partition->clv[clv_index]))
{
size_t clv_size = partition->sites * partition->states_padded *
partition->rate_cats*sizeof(double);
partition->clv[clv_index] = (double*) pll_aligned_alloc(clv_size, partition->alignment);
if (!partition->clv[i])
throw runtime_error{"Could not allocate CLV memory"};
}
unsigned int attributes;
auto err = pllmod_binary_clv_load(
bin_fptr_.get(),
0,
partition,
clv_index,
&attributes,
get_offset(map_, clv_index));
if (err != PLL_SUCCESS)
throw runtime_error{string("Loading CLV failed: ") + pll_errmsg};
}
void Binary::load_tipchars(pll_partition_t * partition, const unsigned int tipchars_index)
{
assert(bin_fptr_);
assert(tipchars_index < partition->tips);
assert(partition->attributes & PLL_ATTRIB_PATTERN_TIP);
unsigned int type, attributes;
size_t size;
auto ptr = pllmod_binary_custom_load(bin_fptr_.get(), 0, &size, &type, &attributes, get_offset(map_, tipchars_index));
if (!ptr)
throw runtime_error{string("Loading tipchar failed: ") + pll_errmsg};
partition->tipchars[tipchars_index] = (unsigned char*)ptr;
}
void Binary::load_scaler(pll_partition_t * partition, const unsigned int scaler_index)
{
assert(bin_fptr_);
assert(scaler_index < partition->scale_buffers);
auto block_offset = partition->clv_buffers + partition->tips;
unsigned int type, attributes;
size_t size;
auto ptr = pllmod_binary_custom_load(bin_fptr_.get(), 0,
&size, &type, &attributes, get_offset(map_, block_offset + scaler_index));
if (!ptr)
throw runtime_error{string("Loading scaler failed: ") + pll_errmsg};
partition->scale_buffer[scaler_index] = (unsigned int*)ptr;
}
static pll_partition_t* skeleton_partition()
{
auto attributes = PLL_ATTRIB_ARCH_SSE;
#ifdef __AVX
attributes = PLL_ATTRIB_ARCH_AVX;
#endif
attributes |= PLL_ATTRIB_PATTERN_TIP;
auto partition = pll_partition_create(
3, // number of tip nodes
1, // number of extra clv buffers
STATES,
1, // number of sites
1, // number of concurrent subs. models
1, // number of probabillity matrices
RATE_CATS,
1, // number of scale buffers
//pll_map_nt,
attributes);
if (!partition)
throw runtime_error{string("Creating skeleton partition: ") + pll_errmsg};
// ensure clv, tipchar and scaler fields are only shallowly allocated
// TODO
return partition;
}
static void dealloc_buffers(pll_partition_t* part)
{
// dealloc clvs and tipchars
if (part->tipchars)
for (size_t i = 0; i < part->tips; ++i)
{
pll_aligned_free(part->tipchars[i]);
part->tipchars[i] = nullptr;
}
if (part->clv)
{
size_t start = (part->attributes & PLL_ATTRIB_PATTERN_TIP) ? part->tips : 0;
for (size_t i = start; i < part->clv_buffers + part->tips; ++i)
{
pll_aligned_free(part->clv[i]);
part->clv[i] = nullptr;
}
}
if (part->scale_buffer)
{
for (size_t i = 0; i < part->scale_buffers; ++i)
{
free(part->scale_buffer[i]);
part->scale_buffer[i] = nullptr;
}
}
}
pll_partition_t* Binary::load_partition()
{
// make skeleton partition that only allocates the pointers to the clv/tipchar buffers
auto skelly = nullptr;// skeleton_partition();
unsigned int attributes = PLLMOD_BIN_ATTRIB_PARTITION_DUMP_WGT;
auto partition = pllmod_binary_partition_load(bin_fptr_.get(), 0, skelly, &attributes,
get_offset(map_, -1));
if (!partition)
throw runtime_error{string("Error loading partition: ") + pll_errmsg};
// free up buffers for things we want to load on demand
// TODO never alloc in the first place
dealloc_buffers(partition);
return partition;
}
pll_utree_t* Binary::load_utree()
{
unsigned int attributes = 0;
auto tree = pllmod_binary_utree_load(bin_fptr_.get(), 0, &attributes, get_offset(map_, -2));
if (!tree)
throw runtime_error{string("Loading tree: ") + pll_errmsg};
return tree;
}
/**
Writes the structures and data encapsulated in Tree to the specified file in the binary format.
Writes them in such a way that the Binary class can read them.
*/
void dump_to_binary(Tree& tree, const string& file)
{
auto num_clvs = tree.partition()->clv_buffers;
auto num_tips = tree.partition()->tips;
auto num_scalers = tree.partition()->scale_buffers;
auto max_clv_index = num_clvs + num_tips;
pll_binary_header_t header;
auto fptr = pllmod_binary_create(
file.c_str(),
&header,
PLLMOD_BIN_ACCESS_RANDOM,
2 + num_clvs + num_tips + num_scalers);
if(!fptr)
throw runtime_error{string("Opening binary file for writing: ") + pll_errmsg};
unsigned int attributes = PLLMOD_BIN_ATTRIB_UPDATE_MAP | PLLMOD_BIN_ATTRIB_PARTITION_DUMP_WGT;
int block_id = -2;
bool use_tipchars = tree.partition()->attributes & PLL_ATTRIB_PATTERN_TIP;
// dump the utree structure
if(!pllmod_binary_utree_dump(fptr, block_id++, tree.tree(), num_tips, attributes))
throw runtime_error{string("Dumping the utree to binary: ") + pll_errmsg};
// dump the partition
if(!pllmod_binary_partition_dump(fptr, block_id++, tree.partition(), attributes))
throw runtime_error{string("Dumping partition to binary: ") + pll_errmsg};
// dump the tipchars, but only if partition uses them
unsigned int tip_index = 0;
if (use_tipchars)
{
for (tip_index = 0; tip_index < num_tips; tip_index++)
{
if(!pllmod_binary_custom_dump(fptr, block_id++, tree.partition()->tipchars[tip_index],
tree.partition()->sites * sizeof(char), attributes))
throw runtime_error{string("Dumping tipchars to binary: ") + pll_errmsg};
}
}
// dump the clvs
for (unsigned int clv_index = tip_index; clv_index < max_clv_index; clv_index++)
{
if(!pllmod_binary_clv_dump(fptr, block_id++, tree.partition(), clv_index, attributes))
throw runtime_error{string("Dumping clvs to binary: ") + pll_errmsg};
}
// dump the scalers
for (unsigned int scaler_index = 0; scaler_index < num_scalers; scaler_index++)
{
if(!pllmod_binary_custom_dump(fptr, block_id++, tree.partition()->scale_buffer[scaler_index],
tree.partition()->sites * sizeof(unsigned int), attributes))
throw runtime_error{string("Dumping scalers to binary: ") + pll_errmsg};
}
fclose(fptr);
}
<|endoftext|> |
<commit_before>#include "Camera.h"
#include "Window.h"
#include <glm/glm.hpp>
using namespace std;
Camera :: Camera(const std::string& fn, IFactory* factory, ICache* cache)
{
}
bool Camera :: in_frustum(const Box& box) const
{
if(m_bOrtho)
{
if(not box.quick_valid())
return false;
if(box.quick_full())
return true;
return (Box(
glm::vec3(0.0f, 0.0f, -100.0f),
glm::vec3(m_Size.x, m_Size.y, 100.0f)
).collision(box));
}
return true;
}
bool Camera :: in_frustum(glm::vec3 point) const
{
if(m_bOrtho)
return (Box(
glm::vec3(0.0f, 0.0f, -100.0f),
glm::vec3(m_Size.x, m_Size.y, 100.0f)
).collision(point));
return true;
}
const glm::mat4& Camera :: projection() const
{
return m_ProjectionMatrix;
}
const glm::mat4& Camera :: view() const
{
m_ViewMatrix = glm::inverse(*matrix_c(Space::WORLD));
return m_ViewMatrix;
}
void Camera :: window(Window* window)
{
if(not window)
{
m_WindowResize.disconnect();
return;
}
m_WindowResize = window->on_resize.connect([this, window](glm::ivec2 w){
m_Size = w;
recalculate_projection();
});
m_Size = window->size();
recalculate_projection();
}
void Camera :: recalculate_projection()
{
if(m_bOrtho)
{
m_ProjectionMatrix = glm::ortho(
0.0f,
static_cast<float>(m_Size.x),
m_bBottomOrigin ? 0.0f : static_cast<float>(m_Size.y),
m_bBottomOrigin ? static_cast<float>(m_Size.y) : 0.0f,
-100.0f,
100.0f
);
}
else
{
float aspect_ratio = (1.0f * m_Size.x) /
std::max(1.0f, (1.0f * m_Size.y));
m_ProjectionMatrix = glm::perspective(
m_FOV,
aspect_ratio,
0.01f,
1000.0f
);
}
}
void Camera :: ortho(bool origin_bottom)
{
m_bOrtho = true;
m_bBottomOrigin = origin_bottom;
recalculate_projection();
}
void Camera :: perspective(float fov)
{
m_bOrtho = false;
m_FOV = fov;
recalculate_projection();
}
<commit_msg>added todo so i dont forget<commit_after>#include "Camera.h"
#include "Window.h"
#include <glm/glm.hpp>
using namespace std;
Camera :: Camera(const std::string& fn, IFactory* factory, ICache* cache)
{
}
bool Camera :: in_frustum(const Box& box) const
{
if(m_bOrtho)
{
if(not box.quick_valid())
return false;
if(box.quick_full())
return true;
// TODO: this needs to be in world space
return (Box(
glm::vec3(0.0f, 0.0f, -100.0f),
glm::vec3(m_Size.x, m_Size.y, 100.0f)
).collision(box));
}
return true;
}
bool Camera :: in_frustum(glm::vec3 point) const
{
if(m_bOrtho)
return (Box(
glm::vec3(0.0f, 0.0f, -100.0f),
glm::vec3(m_Size.x, m_Size.y, 100.0f)
).collision(point));
return true;
}
const glm::mat4& Camera :: projection() const
{
return m_ProjectionMatrix;
}
const glm::mat4& Camera :: view() const
{
m_ViewMatrix = glm::inverse(*matrix_c(Space::WORLD));
return m_ViewMatrix;
}
void Camera :: window(Window* window)
{
if(not window)
{
m_WindowResize.disconnect();
return;
}
m_WindowResize = window->on_resize.connect([this, window](glm::ivec2 w){
m_Size = w;
recalculate_projection();
});
m_Size = window->size();
recalculate_projection();
}
void Camera :: recalculate_projection()
{
if(m_bOrtho)
{
m_ProjectionMatrix = glm::ortho(
0.0f,
static_cast<float>(m_Size.x),
m_bBottomOrigin ? 0.0f : static_cast<float>(m_Size.y),
m_bBottomOrigin ? static_cast<float>(m_Size.y) : 0.0f,
-100.0f,
100.0f
);
}
else
{
float aspect_ratio = (1.0f * m_Size.x) /
std::max(1.0f, (1.0f * m_Size.y));
m_ProjectionMatrix = glm::perspective(
m_FOV,
aspect_ratio,
0.01f,
1000.0f
);
}
}
void Camera :: ortho(bool origin_bottom)
{
m_bOrtho = true;
m_bBottomOrigin = origin_bottom;
recalculate_projection();
}
void Camera :: perspective(float fov)
{
m_bOrtho = false;
m_FOV = fov;
recalculate_projection();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
*/
#include "Camera.h"
#include <stdio.h>
#include <opencv2/imgproc/imgproc_c.h>
#include "Settings.h"
#include <QtCore/QFile>
Camera::Camera(QObject * parent) :
QObject(parent),
capture_(0)
{
qRegisterMetaType<cv::Mat>("cv::Mat");
connect(&cameraTimer_, SIGNAL(timeout()), this, SLOT(takeImage()));
}
Camera::~Camera()
{
this->stop();
}
void Camera::stop()
{
stopTimer();
if(capture_)
{
cvReleaseCapture(&capture_);
capture_ = 0;
}
}
void Camera::pause()
{
stopTimer();
}
void Camera::takeImage()
{
if(capture_)
{
IplImage * img = 0;
if(cvGrabFrame(capture_)) // capture a frame
{
img = cvRetrieveFrame(capture_); // retrieve the captured frame
}
else
{
printf("CameraVideo: Could not grab a frame, the end of the feed may be reached...\n");
}
//resize
if(img &&
Settings::getCamera_imageWidth() &&
Settings::getCamera_imageHeight() &&
Settings::getCamera_imageWidth() != img->width &&
Settings::getCamera_imageHeight() != img->height)
{
// declare a destination IplImage object with correct size, depth and channels
cv::Mat headerImg = img;
cv::Mat imgMat(Settings::getCamera_imageHeight(),
Settings::getCamera_imageWidth(),
headerImg.type());
//use cvResize to resize source to a destination image (linear interpolation)
IplImage resampledImg = imgMat;
cvResize(img, &resampledImg);
emit imageReceived(imgMat);
}
else
{
emit imageReceived(cv::Mat(img, true));
}
}
}
bool Camera::start()
{
if(!capture_)
{
QString videoFile = Settings::getCamera_videoFilePath();
if(QFile::exists(videoFile))
{
capture_ = cvCaptureFromAVI(videoFile.toStdString().c_str());
if(!capture_)
{
printf("WARNING: Cannot open file \"%s\". If you want to disable loading automatically this video file, clear the Camera/videoFilePath parameter. By default, webcam will be used instead of the file.\n", videoFile.toStdString().c_str());
}
}
if(!capture_)
{
capture_ = cvCaptureFromCAM(Settings::getCamera_deviceId());
if(capture_ && Settings::getCamera_imageWidth() && Settings::getCamera_imageHeight())
{
cvSetCaptureProperty(capture_, CV_CAP_PROP_FRAME_WIDTH, double(Settings::getCamera_imageWidth()));
cvSetCaptureProperty(capture_, CV_CAP_PROP_FRAME_HEIGHT, double(Settings::getCamera_imageHeight()));
}
}
}
if(!capture_)
{
printf("Failed to create a capture object!\n");
return false;
}
startTimer();
return true;
}
void Camera::startTimer()
{
updateImageRate();
cameraTimer_.start();
}
void Camera::stopTimer()
{
cameraTimer_.stop();
}
void Camera::updateImageRate()
{
if(Settings::getCamera_imageRate())
{
cameraTimer_.setInterval(1000/Settings::getCamera_imageRate());
}
else
{
cameraTimer_.setInterval(0);
}
}
<commit_msg>Updated a warning...<commit_after>/*
* Copyright (C) 2011, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
*/
#include "Camera.h"
#include <stdio.h>
#include <opencv2/imgproc/imgproc_c.h>
#include "Settings.h"
#include <QtCore/QFile>
Camera::Camera(QObject * parent) :
QObject(parent),
capture_(0)
{
qRegisterMetaType<cv::Mat>("cv::Mat");
connect(&cameraTimer_, SIGNAL(timeout()), this, SLOT(takeImage()));
}
Camera::~Camera()
{
this->stop();
}
void Camera::stop()
{
stopTimer();
if(capture_)
{
cvReleaseCapture(&capture_);
capture_ = 0;
}
}
void Camera::pause()
{
stopTimer();
}
void Camera::takeImage()
{
if(capture_)
{
IplImage * img = 0;
if(cvGrabFrame(capture_)) // capture a frame
{
img = cvRetrieveFrame(capture_); // retrieve the captured frame
}
else
{
printf("CameraVideo: Could not grab a frame, the end of the feed may be reached...\n");
}
//resize
if(img &&
Settings::getCamera_imageWidth() &&
Settings::getCamera_imageHeight() &&
Settings::getCamera_imageWidth() != img->width &&
Settings::getCamera_imageHeight() != img->height)
{
// declare a destination IplImage object with correct size, depth and channels
cv::Mat headerImg = img;
cv::Mat imgMat(Settings::getCamera_imageHeight(),
Settings::getCamera_imageWidth(),
headerImg.type());
//use cvResize to resize source to a destination image (linear interpolation)
IplImage resampledImg = imgMat;
cvResize(img, &resampledImg);
emit imageReceived(imgMat);
}
else
{
emit imageReceived(cv::Mat(img, true));
}
}
}
bool Camera::start()
{
if(!capture_)
{
QString videoFile = Settings::getCamera_videoFilePath();
if(!videoFile.isEmpty())
{
capture_ = cvCaptureFromAVI(videoFile.toStdString().c_str());
if(!capture_)
{
printf("WARNING: Cannot open file \"%s\". If you want to disable loading automatically this video file, clear the Camera/videoFilePath parameter. By default, webcam will be used instead of the file.\n", videoFile.toStdString().c_str());
}
}
if(!capture_)
{
capture_ = cvCaptureFromCAM(Settings::getCamera_deviceId());
if(capture_ && Settings::getCamera_imageWidth() && Settings::getCamera_imageHeight())
{
cvSetCaptureProperty(capture_, CV_CAP_PROP_FRAME_WIDTH, double(Settings::getCamera_imageWidth()));
cvSetCaptureProperty(capture_, CV_CAP_PROP_FRAME_HEIGHT, double(Settings::getCamera_imageHeight()));
}
}
}
if(!capture_)
{
printf("Failed to create a capture object!\n");
return false;
}
startTimer();
return true;
}
void Camera::startTimer()
{
updateImageRate();
cameraTimer_.start();
}
void Camera::stopTimer()
{
cameraTimer_.stop();
}
void Camera::updateImageRate()
{
if(Settings::getCamera_imageRate())
{
cameraTimer_.setInterval(1000/Settings::getCamera_imageRate());
}
else
{
cameraTimer_.setInterval(0);
}
}
<|endoftext|> |
<commit_before>
/**********************************************************************/
/**********************************************************************/
/* */
/* */
/* ۾ ǵ ! */
/* */
/* */
/**********************************************************************/
/**********************************************************************/
#ifdef _DEBUG
#include "NetworkSample.h"
#include "Packet.h"
#include "NNNetworkSystem.h"
NetworkSample::NetworkSample()
{
NNNetworkSystem::GetInstance()->Init();
NNNetworkSystem::GetInstance()->Connect("127.0.0.1",9001);
m_Time = 0;
}
NetworkSample::~NetworkSample()
{
}
void NetworkSample::Render()
{
NNScene::Render();
}
void NetworkSample::Update( float dTime )
{
NNScene::Update(dTime);
SleepEx(0, TRUE);
m_Time += dTime;
if(m_Time > 1)
{
m_Time = 0;
KeyStateUpdateRequset KSUR = KeyStateUpdateRequset();
KSUR.m_PlayerId = -1;
NNNetworkSystem::GetInstance()->Send(&KSUR);
}
}
#endif<commit_msg>Chatting 샘플용으로 수정<commit_after>
/**********************************************************************/
/**********************************************************************/
/* */
/* */
/* ۾ ǵ ! */
/* */
/* */
/**********************************************************************/
/**********************************************************************/
#ifdef _DEBUG
#include "NetworkSample.h"
#include "Packet.h"
#include "NNNetworkSystem.h"
NetworkSample::NetworkSample()
{
NNNetworkSystem::GetInstance()->Init();
NNNetworkSystem::GetInstance()->Connect("127.0.0.1",9001);
m_Time = 0;
}
NetworkSample::~NetworkSample()
{
}
void NetworkSample::Render()
{
NNScene::Render();
}
void NetworkSample::Update( float dTime )
{
NNScene::Update(dTime);
SleepEx(0, TRUE);
m_Time += dTime;
if(m_Time > 1)
{
m_Time = 0;
ChatBroadcastRequest CBR = ChatBroadcastRequest();
strcpy_s(CBR.m_Chat,"hihi");
NNNetworkSystem::GetInstance()->Send(&CBR);
/* KeyStateUpdateRequset KSUR = KeyStateUpdateRequset();
KSUR.m_PlayerId = -1;
NNNetworkSystem::GetInstance()->Send(&KSUR);*/
}
}
#endif<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file FixedHash.cpp
* @author Lefterus <lefteris@ethdev.com>
* @date 2015
*/
#include <libdevcore/FixedHash.h>
#include "../TestHelper.h"
using namespace std;
using namespace dev;
namespace dev
{
namespace test
{
BOOST_AUTO_TEST_SUITE(FixedHashTests)
BOOST_AUTO_TEST_CASE(FixedHashComparisons)
{
FixedHash<4> h1(sha3("abcd"));
FixedHash<4> h2(sha3("abcd"));
FixedHash<4> h3(sha3("aadd"));
FixedHash<4> h4(0xBAADF00D);
FixedHash<4> h5(0xAAAAAAAA);
FixedHash<4> h6(0xBAADF00D);
BOOST_CHECK(h1 == h2);
BOOST_CHECK(h2 != h3);
BOOST_CHECK(h4 > h5);
BOOST_CHECK(h5 < h4);
BOOST_CHECK(h6 <= h4);
BOOST_CHECK(h6 >= h4);
}
BOOST_AUTO_TEST_CASE(FixedHashXOR)
{
FixedHash<2> h1("0xAAAA");
FixedHash<2> h2("0xBBBB");
BOOST_CHECK((h1 ^ h2) == FixedHash<2>("0x1111"));
h1 ^= h2;
BOOST_CHECK(h1 == FixedHash<2>("0x1111"));
}
BOOST_AUTO_TEST_CASE(FixedHashOR)
{
FixedHash<4> h1("0xD3ADB33F");
FixedHash<4> h2("0xBAADF00D");
FixedHash<4> res("0xFBADF33F");
BOOST_CHECK((h1 | h2) == res);
h1 |= h2;
BOOST_CHECK(h1 == res);
}
BOOST_AUTO_TEST_CASE(FixedHashAND)
{
FixedHash<4> h1("0xD3ADB33F");
FixedHash<4> h2("0xBAADF00D");
FixedHash<4> h3("0x92aDB00D");
BOOST_CHECK((h1 & h2) == h3);
h1 &= h2;
BOOST_CHECK(h1 = h3);
}
BOOST_AUTO_TEST_CASE(FixedHashInvert)
{
FixedHash<4> h1("0xD3ADB33F");
FixedHash<4> h2("0x2C524CC0");
BOOST_CHECK(~h1 == h2);
}
BOOST_AUTO_TEST_CASE(FixedHashContains)
{
FixedHash<4> h1("0xD3ADB331");
FixedHash<4> h2("0x0000B331");
FixedHash<4> h3("0x0000000C");
BOOST_CHECK(h1.contains(h2));
BOOST_CHECK(!h1.contains(h3));
}
void incrementSingleIteration(unsigned seed)
{
unsigned next = seed + 1;
FixedHash<4> h1(seed);
FixedHash<4> h2 = h1;
FixedHash<4> h3(next);
FixedHash<32> hh1(seed);
FixedHash<32> hh2 = hh1;
FixedHash<32> hh3(next);
BOOST_CHECK_EQUAL(++h2, h3);
BOOST_CHECK_EQUAL(++hh2, hh3);
BOOST_CHECK(h2 > h1);
BOOST_CHECK(hh2 > hh1);
unsigned reverse1 = ((FixedHash<4>::Arith)h2).convert_to<unsigned>();
unsigned reverse2 = ((FixedHash<32>::Arith)hh2).convert_to<unsigned>();
BOOST_CHECK_EQUAL(next, reverse1);
BOOST_CHECK_EQUAL(next, reverse2);
}
BOOST_AUTO_TEST_CASE(FixedHashIncrement)
{
incrementSingleIteration(0);
incrementSingleIteration(1);
incrementSingleIteration(0xBAD);
incrementSingleIteration(0xBEEF);
incrementSingleIteration(0xFFFF);
incrementSingleIteration(0xFEDCBA);
incrementSingleIteration(0x7FFFFFFF);
}
BOOST_AUTO_TEST_SUITE_END()
}
}
<commit_msg>test updated<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file FixedHash.cpp
* @author Lefterus <lefteris@ethdev.com>
* @date 2015
*/
#include <libdevcore/FixedHash.h>
#include "../TestHelper.h"
using namespace std;
using namespace dev;
namespace dev
{
namespace test
{
BOOST_AUTO_TEST_SUITE(FixedHashTests)
BOOST_AUTO_TEST_CASE(FixedHashComparisons)
{
FixedHash<4> h1(sha3("abcd"));
FixedHash<4> h2(sha3("abcd"));
FixedHash<4> h3(sha3("aadd"));
FixedHash<4> h4(0xBAADF00D);
FixedHash<4> h5(0xAAAAAAAA);
FixedHash<4> h6(0xBAADF00D);
BOOST_CHECK(h1 == h2);
BOOST_CHECK(h2 != h3);
BOOST_CHECK(h4 > h5);
BOOST_CHECK(h5 < h4);
BOOST_CHECK(h6 <= h4);
BOOST_CHECK(h6 >= h4);
}
BOOST_AUTO_TEST_CASE(FixedHashXOR)
{
FixedHash<2> h1("0xAAAA");
FixedHash<2> h2("0xBBBB");
BOOST_CHECK((h1 ^ h2) == FixedHash<2>("0x1111"));
h1 ^= h2;
BOOST_CHECK(h1 == FixedHash<2>("0x1111"));
}
BOOST_AUTO_TEST_CASE(FixedHashOR)
{
FixedHash<4> h1("0xD3ADB33F");
FixedHash<4> h2("0xBAADF00D");
FixedHash<4> res("0xFBADF33F");
BOOST_CHECK((h1 | h2) == res);
h1 |= h2;
BOOST_CHECK(h1 == res);
}
BOOST_AUTO_TEST_CASE(FixedHashAND)
{
FixedHash<4> h1("0xD3ADB33F");
FixedHash<4> h2("0xBAADF00D");
FixedHash<4> h3("0x92aDB00D");
BOOST_CHECK((h1 & h2) == h3);
h1 &= h2;
BOOST_CHECK(h1 = h3);
}
BOOST_AUTO_TEST_CASE(FixedHashInvert)
{
FixedHash<4> h1("0xD3ADB33F");
FixedHash<4> h2("0x2C524CC0");
BOOST_CHECK(~h1 == h2);
}
BOOST_AUTO_TEST_CASE(FixedHashContains)
{
FixedHash<4> h1("0xD3ADB331");
FixedHash<4> h2("0x0000B331");
FixedHash<4> h3("0x0000000C");
BOOST_CHECK(h1.contains(h2));
BOOST_CHECK(!h1.contains(h3));
}
void incrementSingleIteration(unsigned seed)
{
unsigned next = seed + 1;
FixedHash<4> h1(seed);
FixedHash<4> h2 = h1;
FixedHash<4> h3(next);
FixedHash<32> hh1(seed);
FixedHash<32> hh2 = hh1;
FixedHash<32> hh3(next);
BOOST_CHECK_EQUAL(++h2, h3);
BOOST_CHECK_EQUAL(++hh2, hh3);
BOOST_CHECK(h2 > h1);
BOOST_CHECK(hh2 > hh1);
unsigned reverse1 = ((FixedHash<4>::Arith)h2).convert_to<unsigned>();
unsigned reverse2 = ((FixedHash<32>::Arith)hh2).convert_to<unsigned>();
BOOST_CHECK_EQUAL(next, reverse1);
BOOST_CHECK_EQUAL(next, reverse2);
}
BOOST_AUTO_TEST_CASE(FixedHashIncrement)
{
incrementSingleIteration(0);
incrementSingleIteration(1);
incrementSingleIteration(0xBAD);
incrementSingleIteration(0xBEEF);
incrementSingleIteration(0xFFFF);
incrementSingleIteration(0xFEDCBA);
incrementSingleIteration(0x7FFFFFFF);
FixedHash<4> h(0xFFFFFFFF);
FixedHash<4> zero;
BOOST_CHECK_EQUAL(++h, zero);
}
BOOST_AUTO_TEST_SUITE_END()
}
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Antioch - A Gas Dynamics Thermochemistry Library
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
// C++
#include <limits>
// Antioch
#include "antioch/vector_utils.h"
#include "antioch/reaction.h"
#include "antioch/falloff_reaction.h"
template <typename Scalar>
int tester()
{
using std::abs;
using std::exp;
using std::pow;
const Scalar Cf1 = 1.4;
const Scalar Ea1 = 5.0;
const Scalar beta1 = 1.2;
const Scalar D1 = 2.5;
const Scalar Cf2 = 2.0;
const Scalar Ea2 = 3.0;
const Scalar beta2 = 0.8;
const Scalar D2 = 3.0;
const std::string equation("A + B -> C + D");
const unsigned int n_species(4);
int return_flag = 0;
std::vector<Scalar> mol_densities;
mol_densities.push_back(1e-2);
mol_densities.push_back(1e-2);
mol_densities.push_back(1e-2);
mol_densities.push_back(1e-2);
Scalar M = mol_densities[0];
for(unsigned int i = 1; i < n_species; i++)
{
M += mol_densities[i];
}
const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 100;
for(Scalar T = 300.1; T <= 2500.1; T += 10.)
{
for(unsigned int ikinmod = 0; ikinmod < 6; ikinmod++)
{
Antioch::KineticsType<Scalar> *rate_kinetics1(NULL);
Antioch::KineticsType<Scalar> *rate_kinetics2(NULL);
Scalar k0,kinf,dk0_dT,dkinf_dT;
Scalar rate_exact;
Scalar derive_exact;
std::vector<Scalar> derive_dX_exact;
derive_dX_exact.resize(n_species);
Antioch::KineticsModel::KineticsModel kin_mod;
switch(ikinmod)
{
case 0:
{
kin_mod = Antioch::KineticsModel::HERCOURT_ESSEN;
rate_kinetics1 = new Antioch::HercourtEssenRate<Scalar>(Cf1,beta1,1.);
rate_kinetics2 = new Antioch::HercourtEssenRate<Scalar>(Cf2,beta2,1.);
k0 = Cf1 * pow(T,beta1); kinf = Cf2 * pow(T,beta2);
dk0_dT = Cf1 * pow (T,beta1) * beta1/T; dkinf_dT = Cf2 * pow (T,beta2) * beta2/T;
break;
}
case 1:
{
kin_mod = Antioch::KineticsModel::BERTHELOT;
rate_kinetics1 = new Antioch::BerthelotRate<Scalar>(Cf1,D1);
rate_kinetics2 = new Antioch::BerthelotRate<Scalar>(Cf2,D2);
k0 = Cf1 * exp(D1*T); kinf = Cf2 * exp(D2*T);
dk0_dT = Cf1 * exp(D1*T) * D1; dkinf_dT = Cf2 * exp(D2*T) * D2;
break;
}
case 2:
{
kin_mod = Antioch::KineticsModel::ARRHENIUS;
rate_kinetics1 = new Antioch::ArrheniusRate<Scalar>(Cf1,Ea1,1.);
rate_kinetics2 = new Antioch::ArrheniusRate<Scalar>(Cf2,Ea2,1.);
k0 = Cf1 * exp(-Ea1/T); kinf = Cf2 * exp(-Ea2/T);
dk0_dT = Cf1 * exp(-Ea1/T) * Ea1/pow(T,2); dkinf_dT = Cf2 * exp(-Ea2/T) * Ea2/pow(T,2);
break;
}
case 3:
{
kin_mod = Antioch::KineticsModel::BHE;
rate_kinetics1 = new Antioch::BerthelotHercourtEssenRate<Scalar>(Cf1,beta1,D1,1.);
rate_kinetics2 = new Antioch::BerthelotHercourtEssenRate<Scalar>(Cf2,beta2,D2,1.);
k0 = Cf1 * pow(T,beta1) * exp(D1 * T); kinf = Cf2 * pow(T,beta2) * exp(D2 * T);
dk0_dT = Cf1 * pow(T,beta1) * exp(D1 * T) * (beta1/T + D1); dkinf_dT = Cf2 * pow(T,beta2) * exp(D2 * T) * (beta2/T + D2);
break;
}
case 4:
{
kin_mod = Antioch::KineticsModel::KOOIJ;
rate_kinetics1 = new Antioch::KooijRate<Scalar>(Cf1,beta1,Ea1,1.,1.);
rate_kinetics2 = new Antioch::KooijRate<Scalar>(Cf2,beta2,Ea2,1.,1.);
k0 = Cf1 * pow(T,beta1) * exp(-Ea1/T); kinf = Cf2 * pow(T,beta2) * exp(-Ea2/T);
dk0_dT = Cf1 * pow(T,beta1) * exp(-Ea1/T) * (beta1/T + Ea1/pow(T,2)); dkinf_dT = Cf2 * pow(T,beta2) * exp(-Ea2/T) * (beta2/T + Ea2/pow(T,2));
break;
}
case 5:
{
kin_mod = Antioch::KineticsModel::VANTHOFF;
rate_kinetics1 = new Antioch::VantHoffRate<Scalar>(Cf1,beta1,Ea1,D1,1.,1.);
rate_kinetics2 = new Antioch::VantHoffRate<Scalar>(Cf2,beta2,Ea2,D2,1.,1.);
k0 = Cf1 * pow(T,beta1) * exp(-Ea1/T + D1 * T); kinf = Cf2 * pow(T,beta2) * exp(-Ea2/T + D2 * T);
dk0_dT = Cf1 * pow(T,beta1) * exp(-Ea1/T + D1 * T) * (D1 + beta1/T + Ea1/pow(T,2));
dkinf_dT = Cf2 * pow(T,beta2) * exp(-Ea2/T + D2 * T) * (D2 + beta2/T + Ea2/pow(T,2));
break;
}
}
rate_exact = k0 / (1./M + k0/kinf);
derive_exact = rate_exact * (dk0_dT/k0 - dk0_dT/(kinf/M + k0) + dkinf_dT/(pow(kinf,2)/M + k0*kinf));
for(unsigned int i = 0; i < n_species; i++)
{
derive_dX_exact[i] = rate_exact/(M + pow(M,2)*k0/kinf);
}
Antioch::FalloffReaction<Scalar,Antioch::TroeFalloff<Scalar> > * fall_reaction =
new Antioch::FalloffReaction<Scalar,Antioch::TroeFalloff<Scalar> >(n_species,equation,Antioch::ReactionType::LINDEMANN_FALLOFF,kin_mod);
fall_reaction->add_forward_rate(rate_kinetics1);
fall_reaction->add_forward_rate(rate_kinetics2);
Scalar rate1 = fall_reaction->compute_forward_rate_coefficient(mol_densities,T);
Scalar rate;
Scalar drate_dT;
std::vector<Scalar> drate_dx;
drate_dx.resize(n_species);
fall_reaction->compute_forward_rate_coefficient_and_derivatives(mol_densities,T,rate,drate_dT,drate_dx);
for(unsigned int i = 0; i < n_species; i++)
{
if( abs( (drate_dx[i] - derive_dX_exact[i])/derive_dX_exact[i] ) > tol )
{
std::cout << std::scientific << std::setprecision(16)
<< "Error: Mismatch in rate values." << std::endl
<< "Kinetics model (see enum) " << kin_mod << std::endl
<< "species " << i << std::endl
<< "drate_dc(T) = " << drate_dx[i] << std::endl
<< "drate_dc_exact = " << derive_dX_exact[i] << std::endl;
return_flag = 1;
}
}
if( abs( (rate1 - rate_exact)/rate_exact ) > tol )
{
std::cout << std::scientific << std::setprecision(16)
<< "Error: Mismatch in rate values." << std::endl
<< "Kinetics model (see enum) " << kin_mod << std::endl
<< "T = " << T << " K" << std::endl
<< "rate(T) = " << rate1 << std::endl
<< "rate_exact = " << rate_exact << std::endl;
return_flag = 1;
}
if( abs( (rate - rate_exact)/rate_exact ) > tol )
{
std::cout << std::scientific << std::setprecision(16)
<< "Error: Mismatch in rate values." << std::endl
<< "Kinetics model (see enum) " << kin_mod << std::endl
<< "T = " << T << " K" << std::endl
<< "rate(T) = " << rate << std::endl
<< "rate_exact = " << rate_exact << std::endl;
return_flag = 1;
}
if( abs( (drate_dT - derive_exact)/derive_exact ) > tol )
{
std::cout << std::scientific << std::setprecision(16)
<< "Error: Mismatch in rate derivative values." << std::endl
<< "Kinetics model (see enum) " << kin_mod << std::endl
<< "T = " << T << " K" << std::endl
<< "drate_dT(T) = " << drate_dT << std::endl
<< "derive_exact = " << derive_exact << std::endl;
return_flag = 1;
}
delete fall_reaction;
if(return_flag)return return_flag;
}
}
return return_flag;
}
int main()
{
return (tester<double>() ||
tester<long double>() ||
tester<float>());
}
<commit_msg>Bug fix!!! Loaded a TroeFalloff object instead of Lindemann, produced an invisible nan...<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Antioch - A Gas Dynamics Thermochemistry Library
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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
//
//-----------------------------------------------------------------------el-
// C++
#include <limits>
// Antioch
#include "antioch/vector_utils.h"
#include "antioch/reaction.h"
#include "antioch/falloff_reaction.h"
template <typename Scalar>
int tester()
{
using std::abs;
using std::exp;
using std::pow;
const Scalar Cf1 = 1.4;
const Scalar Ea1 = 5.0;
const Scalar beta1 = 1.2;
const Scalar D1 = 2.5;
const Scalar Cf2 = 2.0;
const Scalar Ea2 = 3.0;
const Scalar beta2 = 0.8;
const Scalar D2 = 3.0;
const std::string equation("A + B -> C + D");
const unsigned int n_species(4);
int return_flag = 0;
std::vector<Scalar> mol_densities;
mol_densities.push_back(1e-2);
mol_densities.push_back(1e-2);
mol_densities.push_back(1e-2);
mol_densities.push_back(1e-2);
Scalar M = mol_densities[0];
for(unsigned int i = 1; i < n_species; i++)
{
M += mol_densities[i];
}
const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 100;
for(Scalar T = 300.1; T <= 2500.1; T += 10.)
{
for(unsigned int ikinmod = 0; ikinmod < 6; ikinmod++)
{
Antioch::KineticsType<Scalar> *rate_kinetics1(NULL);
Antioch::KineticsType<Scalar> *rate_kinetics2(NULL);
Scalar k0,kinf,dk0_dT,dkinf_dT;
Scalar rate_exact;
Scalar derive_exact;
std::vector<Scalar> derive_dX_exact;
derive_dX_exact.resize(n_species);
Antioch::KineticsModel::KineticsModel kin_mod;
switch(ikinmod)
{
case 0:
{
kin_mod = Antioch::KineticsModel::HERCOURT_ESSEN;
rate_kinetics1 = new Antioch::HercourtEssenRate<Scalar>(Cf1,beta1,1.);
rate_kinetics2 = new Antioch::HercourtEssenRate<Scalar>(Cf2,beta2,1.);
k0 = Cf1 * pow(T,beta1); kinf = Cf2 * pow(T,beta2);
dk0_dT = Cf1 * pow (T,beta1) * beta1/T; dkinf_dT = Cf2 * pow (T,beta2) * beta2/T;
break;
}
case 1:
{
kin_mod = Antioch::KineticsModel::BERTHELOT;
rate_kinetics1 = new Antioch::BerthelotRate<Scalar>(Cf1,D1);
rate_kinetics2 = new Antioch::BerthelotRate<Scalar>(Cf2,D2);
k0 = Cf1 * exp(D1*T); kinf = Cf2 * exp(D2*T);
dk0_dT = Cf1 * exp(D1*T) * D1; dkinf_dT = Cf2 * exp(D2*T) * D2;
break;
}
case 2:
{
kin_mod = Antioch::KineticsModel::ARRHENIUS;
rate_kinetics1 = new Antioch::ArrheniusRate<Scalar>(Cf1,Ea1,1.);
rate_kinetics2 = new Antioch::ArrheniusRate<Scalar>(Cf2,Ea2,1.);
k0 = Cf1 * exp(-Ea1/T); kinf = Cf2 * exp(-Ea2/T);
dk0_dT = Cf1 * exp(-Ea1/T) * Ea1/pow(T,2); dkinf_dT = Cf2 * exp(-Ea2/T) * Ea2/pow(T,2);
break;
}
case 3:
{
kin_mod = Antioch::KineticsModel::BHE;
rate_kinetics1 = new Antioch::BerthelotHercourtEssenRate<Scalar>(Cf1,beta1,D1,1.);
rate_kinetics2 = new Antioch::BerthelotHercourtEssenRate<Scalar>(Cf2,beta2,D2,1.);
k0 = Cf1 * pow(T,beta1) * exp(D1 * T); kinf = Cf2 * pow(T,beta2) * exp(D2 * T);
dk0_dT = Cf1 * pow(T,beta1) * exp(D1 * T) * (beta1/T + D1); dkinf_dT = Cf2 * pow(T,beta2) * exp(D2 * T) * (beta2/T + D2);
break;
}
case 4:
{
kin_mod = Antioch::KineticsModel::KOOIJ;
rate_kinetics1 = new Antioch::KooijRate<Scalar>(Cf1,beta1,Ea1,1.,1.);
rate_kinetics2 = new Antioch::KooijRate<Scalar>(Cf2,beta2,Ea2,1.,1.);
k0 = Cf1 * pow(T,beta1) * exp(-Ea1/T); kinf = Cf2 * pow(T,beta2) * exp(-Ea2/T);
dk0_dT = Cf1 * pow(T,beta1) * exp(-Ea1/T) * (beta1/T + Ea1/pow(T,2)); dkinf_dT = Cf2 * pow(T,beta2) * exp(-Ea2/T) * (beta2/T + Ea2/pow(T,2));
break;
}
case 5:
{
kin_mod = Antioch::KineticsModel::VANTHOFF;
rate_kinetics1 = new Antioch::VantHoffRate<Scalar>(Cf1,beta1,Ea1,D1,1.,1.);
rate_kinetics2 = new Antioch::VantHoffRate<Scalar>(Cf2,beta2,Ea2,D2,1.,1.);
k0 = Cf1 * pow(T,beta1) * exp(-Ea1/T + D1 * T); kinf = Cf2 * pow(T,beta2) * exp(-Ea2/T + D2 * T);
dk0_dT = Cf1 * pow(T,beta1) * exp(-Ea1/T + D1 * T) * (D1 + beta1/T + Ea1/pow(T,2));
dkinf_dT = Cf2 * pow(T,beta2) * exp(-Ea2/T + D2 * T) * (D2 + beta2/T + Ea2/pow(T,2));
break;
}
}
rate_exact = k0 / (1.L/M + k0/kinf);
derive_exact = rate_exact * (dk0_dT/k0 - dk0_dT/(kinf/M + k0) + dkinf_dT/(pow(kinf,2)/M + k0*kinf));
for(unsigned int i = 0; i < n_species; i++)
{
derive_dX_exact[i] = rate_exact/(M + pow(M,2)*k0/kinf);
}
Antioch::FalloffReaction<Scalar,Antioch::LindemannFalloff<Scalar> > * fall_reaction =
new Antioch::FalloffReaction<Scalar,Antioch::LindemannFalloff<Scalar> >(n_species,equation,Antioch::ReactionType::LINDEMANN_FALLOFF,kin_mod);
fall_reaction->add_forward_rate(rate_kinetics1);
fall_reaction->add_forward_rate(rate_kinetics2);
Scalar rate1 = fall_reaction->compute_forward_rate_coefficient(mol_densities,T);
Scalar rate;
Scalar drate_dT;
std::vector<Scalar> drate_dx;
drate_dx.resize(n_species);
fall_reaction->compute_forward_rate_coefficient_and_derivatives(mol_densities,T,rate,drate_dT,drate_dx);
for(unsigned int i = 0; i < n_species; i++)
{
if( abs( (drate_dx[i] - derive_dX_exact[i])/derive_dX_exact[i] ) > tol )
{
std::cout << std::scientific << std::setprecision(16)
<< "Error: Mismatch in rate values." << std::endl
<< "Kinetics model (see enum) " << kin_mod << std::endl
<< "species " << i << std::endl
<< "drate_dc(T) = " << drate_dx[i] << std::endl
<< "drate_dc_exact = " << derive_dX_exact[i] << std::endl;
return_flag = 1;
}
}
if( abs( (rate1 - rate_exact)/rate_exact ) > tol )
{
std::cout << std::scientific << std::setprecision(16)
<< "Error: Mismatch in rate values." << std::endl
<< "Kinetics model (see enum) " << kin_mod << std::endl
<< "T = " << T << " K" << std::endl
<< "rate(T) = " << rate1 << std::endl
<< "rate_exact = " << rate_exact << std::endl;
return_flag = 1;
}
if( abs( (rate - rate_exact)/rate_exact ) > tol )
{
std::cout << std::scientific << std::setprecision(16)
<< "Error: Mismatch in rate values." << std::endl
<< "Kinetics model (see enum) " << kin_mod << std::endl
<< "T = " << T << " K" << std::endl
<< "rate(T) = " << rate << std::endl
<< "rate_exact = " << rate_exact << std::endl;
return_flag = 1;
}
if( abs( (drate_dT - derive_exact)/derive_exact ) > tol )
{
std::cout << std::scientific << std::setprecision(16)
<< "Error: Mismatch in rate derivative values." << std::endl
<< "Kinetics model (see enum) " << kin_mod << std::endl
<< "T = " << T << " K" << std::endl
<< "drate_dT(T) = " << drate_dT << std::endl
<< "derive_exact = " << derive_exact << std::endl;
return_flag = 1;
}
delete fall_reaction;
if(return_flag)return return_flag;
}
}
return return_flag;
}
int main()
{
return (tester<double>() ||
tester<long double>() ||
tester<float>());
}
<|endoftext|> |
<commit_before>#include "../test_adam.hpp"
#include "../test_optimizer.hpp"
#include "nnlib/critics/mse.hpp"
#include "nnlib/math/math.hpp"
#include "nnlib/math/random.hpp"
#include "nnlib/nn/linear.hpp"
#include "nnlib/opt/adam.hpp"
using namespace nnlib;
using T = NN_REAL_T;
NNTestClassImpl(Adam)
{
Linear<T> model(2, 3);
MSE<T> critic;
NNRunAbstractTest(Optimizer, Adam, new Adam<T>(model, critic));
NNTestMethod(reset)
{
RandomEngine::sharedEngine().seed(0);
Linear<T> model(2, 3);
MSE<T> critic;
Adam<T> opt(model, critic);
auto inputs = math::rand(Tensor<T>(2));
auto target = math::rand(Tensor<T>(3));
auto before = model.params().copy();
for(size_t i = 0; i < 100; ++i)
opt.step(inputs, target);
auto after = model.params().copy();
model.params().copy(before);
opt.reset();
for(size_t i = 0; i < 100; ++i)
opt.step(inputs, target);
forEach([&](T first, T second)
{
NNTestAlmostEquals(first, second, 1e-12);
}, after, model.params());
}
NNTestMethod(learningRate)
{
RandomEngine::sharedEngine().seed(0);
Linear<T> model(2, 3);
MSE<T> critic;
Adam<T> opt(model, critic);
auto inputs = math::rand(Tensor<T>(2));
auto target = math::rand(Tensor<T>(3));
opt.learningRate(0.1);
NNTestAlmostEquals(opt.learningRate(), 0.1, 1e-12);
auto before = model.params().copy();
opt.step(inputs, target);
T err1 = critic.forward(model.forward(inputs), target);
model.params().copy(before);
opt.reset();
opt.learningRate(1);
opt.step(inputs, target);
T err2 = critic.forward(model.forward(inputs), target);
NNTestLessThan(err2, err1);
}
NNTestMethod(beta1)
{
}
NNTestMethod(beta2)
{
}
}
<commit_msg>Finished Adam tests.<commit_after>#include "../test_adam.hpp"
#include "../test_optimizer.hpp"
#include "nnlib/critics/mse.hpp"
#include "nnlib/math/math.hpp"
#include "nnlib/math/random.hpp"
#include "nnlib/nn/linear.hpp"
#include "nnlib/opt/adam.hpp"
using namespace nnlib;
using T = NN_REAL_T;
NNTestClassImpl(Adam)
{
Linear<T> model(2, 3);
MSE<T> critic;
NNRunAbstractTest(Optimizer, Adam, new Adam<T>(model, critic));
NNTestMethod(reset)
{
NNTestParams()
{
RandomEngine::sharedEngine().seed(0);
Linear<T> model(2, 3);
MSE<T> critic;
Adam<T> opt(model, critic);
auto inputs = math::rand(Tensor<T>(2));
auto target = math::rand(Tensor<T>(3));
auto before = model.params().copy();
for(size_t i = 0; i < 100; ++i)
opt.step(inputs, target);
auto after = model.params().copy();
model.params().copy(before);
opt.reset();
for(size_t i = 0; i < 100; ++i)
opt.step(inputs, target);
forEach([&](T first, T second)
{
NNTestAlmostEquals(first, second, 1e-12);
}, after, model.params());
}
}
NNTestMethod(learningRate)
{
NNTestParams(T)
{
RandomEngine::sharedEngine().seed(0);
Linear<T> model(2, 3);
MSE<T> critic;
Adam<T> opt(model, critic);
auto inputs = math::rand(Tensor<T>(2));
auto target = math::rand(Tensor<T>(3));
opt.learningRate(0.1);
NNTestAlmostEquals(opt.learningRate(), 0.1, 1e-12);
auto before = model.params().copy();
opt.step(inputs, target);
T dist1 = sqrt(math::sum(math::square(before - model.params())));
model.params().copy(before);
opt.reset();
opt.learningRate(1);
opt.step(inputs, target);
T dist2 = sqrt(math::sum(math::square(before - model.params())));
NNTestAlmostEquals(dist1, 0.1 * dist2, 1e-12);
}
}
NNTestMethod(beta1)
{
NNTestParams(T)
{
Linear<T> model(1, 1);
model.params().fill(1);
MSE<T> critic;
Adam<T> opt(model, critic);
opt.beta1(0.5);
NNTestAlmostEquals(opt.beta1(), 0.5, 1e-12);
}
}
NNTestMethod(beta2)
{
NNTestParams(T)
{
Linear<T> model(1, 1);
model.params().fill(1);
MSE<T> critic;
Adam<T> opt(model, critic);
opt.beta2(0.5);
NNTestAlmostEquals(opt.beta2(), 0.5, 1e-12);
}
}
}
<|endoftext|> |
<commit_before>#include "Halide.h"
#include <cstdio>
#include <algorithm>
#include "halide_benchmark.h"
using namespace Halide;
using namespace Halide::Tools;
// 32-bit windows defines powf as a macro, which won't work for us.
#ifdef _WIN32
extern "C" __declspec(dllexport) float pow_ref(float x, float y) {
return pow(x, y);
}
#else
extern "C" float pow_ref(float x, float y) {
return powf(x, y);
}
#endif
HalideExtern_2(float, pow_ref, float, float);
int main(int argc, char **argv) {
Func f, g, h;
Var x, y;
Param<int> pows_per_pixel;
RDom s(0, pows_per_pixel);
f(x, y) = sum(pow_ref((x+1)/512.0f, (y+1+s)/512.0f));
g(x, y) = sum(pow((x+1)/512.0f, (y+1+s)/512.0f));
h(x, y) = sum(fast_pow((x+1)/512.0f, (y+1+s)/512.0f));
f.vectorize(x, 8);
g.vectorize(x, 8);
h.vectorize(x, 8);
Buffer<float> correct_result(2048, 768);
Buffer<float> fast_result(2048, 768);
Buffer<float> faster_result(2048, 768);
pows_per_pixel.set(1);
f.realize(correct_result);
g.realize(fast_result);
h.realize(faster_result);
const int trials = 10;
const int iterations = 10;
pows_per_pixel.set(20);
// All profiling runs are done into the same buffer, to avoid
// cache weirdness.
Buffer<float> timing_scratch(256, 256);
double t1 = 1e3 * benchmark(3, 3, [&]() { f.realize(timing_scratch); });
double t2 = 1e3 * benchmark(trials, iterations, [&]() { g.realize(timing_scratch); });
double t3 = 1e3 * benchmark(trials, iterations, [&]() { h.realize(timing_scratch); });
RDom r(correct_result);
Func fast_error, faster_error;
Expr fast_delta = correct_result(r.x, r.y) - fast_result(r.x, r.y);
Expr faster_delta = correct_result(r.x, r.y) - faster_result(r.x, r.y);
fast_error() += cast<double>(fast_delta * fast_delta);
faster_error() += cast<double>(faster_delta * faster_delta);
Buffer<double> fast_err = fast_error.realize();
Buffer<double> faster_err = faster_error.realize();
int timing_N = timing_scratch.width() * timing_scratch.height() * 10;
int correctness_N = fast_result.width() * fast_result.height();
fast_err(0) = sqrt(fast_err(0)/correctness_N);
faster_err(0) = sqrt(faster_err(0)/correctness_N);
printf("powf: %f ns per pixel\n"
"Halide's pow: %f ns per pixel (rms error = %0.10f)\n"
"Halide's fast_pow: %f ns per pixel (rms error = %0.10f)\n",
1000000*t1 / timing_N,
1000000*t2 / timing_N, fast_err(0),
1000000*t3 / timing_N, faster_err(0));
if (fast_err(0) > 0.000001) {
printf("Error for pow too large\n");
return -1;
}
if (faster_err(0) > 0.0001) {
printf("Error for fast_pow too large\n");
return -1;
}
if (t1 < t2) {
printf("powf is faster than Halide's pow\n");
return -1;
}
if (t2*1.5 < t3) {
printf("pow is more than 1.5x faster than fast_pow\n");
return -1;
}
printf("Success!\n");
return 0;
}
<commit_msg>Fix performance/fast_pow too<commit_after>#include "Halide.h"
#include <cstdio>
#include <algorithm>
#include "halide_benchmark.h"
using namespace Halide;
using namespace Halide::Tools;
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
// powf() is a macro in some environments, so always wrap it
extern "C" DLLEXPORT float pow_ref(float x, float y) {
return powf(x, y);
}
HalideExtern_2(float, pow_ref, float, float);
int main(int argc, char **argv) {
Func f, g, h;
Var x, y;
Param<int> pows_per_pixel;
RDom s(0, pows_per_pixel);
f(x, y) = sum(pow_ref((x+1)/512.0f, (y+1+s)/512.0f));
g(x, y) = sum(pow((x+1)/512.0f, (y+1+s)/512.0f));
h(x, y) = sum(fast_pow((x+1)/512.0f, (y+1+s)/512.0f));
f.vectorize(x, 8);
g.vectorize(x, 8);
h.vectorize(x, 8);
Buffer<float> correct_result(2048, 768);
Buffer<float> fast_result(2048, 768);
Buffer<float> faster_result(2048, 768);
pows_per_pixel.set(1);
f.realize(correct_result);
g.realize(fast_result);
h.realize(faster_result);
const int trials = 10;
const int iterations = 10;
pows_per_pixel.set(20);
// All profiling runs are done into the same buffer, to avoid
// cache weirdness.
Buffer<float> timing_scratch(256, 256);
double t1 = 1e3 * benchmark(3, 3, [&]() { f.realize(timing_scratch); });
double t2 = 1e3 * benchmark(trials, iterations, [&]() { g.realize(timing_scratch); });
double t3 = 1e3 * benchmark(trials, iterations, [&]() { h.realize(timing_scratch); });
RDom r(correct_result);
Func fast_error, faster_error;
Expr fast_delta = correct_result(r.x, r.y) - fast_result(r.x, r.y);
Expr faster_delta = correct_result(r.x, r.y) - faster_result(r.x, r.y);
fast_error() += cast<double>(fast_delta * fast_delta);
faster_error() += cast<double>(faster_delta * faster_delta);
Buffer<double> fast_err = fast_error.realize();
Buffer<double> faster_err = faster_error.realize();
int timing_N = timing_scratch.width() * timing_scratch.height() * 10;
int correctness_N = fast_result.width() * fast_result.height();
fast_err(0) = sqrt(fast_err(0)/correctness_N);
faster_err(0) = sqrt(faster_err(0)/correctness_N);
printf("powf: %f ns per pixel\n"
"Halide's pow: %f ns per pixel (rms error = %0.10f)\n"
"Halide's fast_pow: %f ns per pixel (rms error = %0.10f)\n",
1000000*t1 / timing_N,
1000000*t2 / timing_N, fast_err(0),
1000000*t3 / timing_N, faster_err(0));
if (fast_err(0) > 0.000001) {
printf("Error for pow too large\n");
return -1;
}
if (faster_err(0) > 0.0001) {
printf("Error for fast_pow too large\n");
return -1;
}
if (t1 < t2) {
printf("powf is faster than Halide's pow\n");
return -1;
}
if (t2*1.5 < t3) {
printf("pow is more than 1.5x faster than fast_pow\n");
return -1;
}
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>#include "../src/repeat_detector.h"
void repeat_detector_test() {
using namespace LeviDB;
class Tester : public SuffixTree {
private:
Arena arena;
public:
Tester() noexcept : arena(), SuffixTree(&arena) {}
bool contains(std::string & src, int from) {
const STNode * edge_node = nodeGetSub(_root, char_be_uint8(src[from]));
if (edge_node == nullptr) {
return false;
}
while (true) {
const Slice edge_s = _chunk[edge_node->chunk_idx];
for (int i = edge_node->from; i < edge_node->to; ++i) {
if (edge_s.data()[i] != src[from]) {
return false;
} else {
++from;
if (from == src.size()) {
return true;
}
}
}
edge_node = nodeGetSub(edge_node, char_be_uint8(src[from]));
}
}
};
Tester tester;
srand(19950207);
char alphabet[] = {'A', 'B', 'C', 'D', 'E'};
for (int i = 0; i < 100; ++i) {
std::string sample;
int len = rand() % 20 + 1;
for (int j = 0; j < len; ++j) {
sample += alphabet[rand() % 5];
}
sample += '.';
tester.setitem(sample);
for (int j = 0; j < sample.size(); ++j) {
assert(tester.contains(sample, j));
}
}
};<commit_msg>完成repeat_detector测试<commit_after>#include "../src/repeat_detector.h"
#include <array>
#include <iostream>
void repeat_detector_test() {
class Tester : public LeviDB::SuffixTree {
public:
Tester(LeviDB::Arena * arena) noexcept : SuffixTree(arena) {}
bool contains(std::string & src, int from) const noexcept {
const LeviDB::STNode * edge_node = nodeGetSub(_root, LeviDB::char_be_uint8(src[from]));
if (edge_node == nullptr) {
return false;
}
while (true) {
const LeviDB::Slice edge_s = _chunk[edge_node->chunk_idx];
for (int i = edge_node->from; i < edge_node->to; ++i) {
if (edge_s.data()[i] != src[from]) {
return false;
} else {
++from;
if (from == src.size()) {
return true;
}
}
}
edge_node = nodeGetSub(edge_node, LeviDB::char_be_uint8(src[from]));
}
}
};
LeviDB::Arena arena;
Tester tester(&arena);
srand(19950207);
static constexpr int n = 100;
std::array<std::string, n> sources;
std::array<char, 5> alphabet = {'A', 'B', 'C', 'D', 'E'};
for (int i = 0; i < n; ++i) {
std::string sample;
int len = rand() % 20 + 1;
for (int j = 0; j < len; ++j) {
sample += alphabet[rand() % alphabet.size()];
}
sample += '.';
sources[i] = std::move(sample);
tester.setitem(LeviDB::Slice(sources[i]));
for (int j = 0; j < sample.size(); ++j) {
assert(tester.contains(sample, j));
}
}
std::cout << __FUNCTION__ << std::endl;
};<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "dll_test.hpp"
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/transform/scale_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/pooling/avgp_layer.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE("unit/conv/sgd/1", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.07;
FT_CHECK(25, 5e-2);
TEST_CHECK(0.2);
}
TEST_CASE("unit/conv/sgd/2", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::TANH>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.10;
FT_CHECK(25, 5e-2);
TEST_CHECK(0.4);
}
TEST_CASE("unit/conv/sgd/3", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.07;
FT_CHECK(25, 5e-2);
TEST_CHECK(0.2);
}
TEST_CASE("unit/conv/sgd/4", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::conv_desc<6, 24, 24, 4, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<4 * 20 * 20, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.1;
FT_CHECK(25, 6e-2);
TEST_CHECK(0.2);
}
TEST_CASE("unit/conv/sgd/5", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 8, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::conv_desc<8, 24, 24, 6, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<6 * 20 * 20, 200, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<200, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK(25, 6e-2);
TEST_CHECK(0.2);
}
<commit_msg>Test for partial training<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "dll_test.hpp"
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/transform/scale_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/pooling/avgp_layer.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE("unit/conv/sgd/1", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.07;
FT_CHECK(25, 5e-2);
TEST_CHECK(0.2);
}
TEST_CASE("unit/conv/sgd/2", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::TANH>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.10;
FT_CHECK(25, 5e-2);
TEST_CHECK(0.4);
}
TEST_CASE("unit/conv/sgd/3", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::TANH>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.07;
FT_CHECK(25, 5e-2);
TEST_CHECK(0.2);
}
TEST_CASE("unit/conv/sgd/4", "[unit][conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::conv_desc<6, 24, 24, 4, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<4 * 20 * 20, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.1;
FT_CHECK(25, 6e-2);
TEST_CHECK(0.2);
}
TEST_CASE("unit/conv/sgd/5", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 8, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::conv_desc<8, 24, 24, 6, 5, 5, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<6 * 20 * 20, 200, dll::activation<dll::function::RELU>>::layer_t,
dll::dense_desc<200, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
dll_test::mnist_scale(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.05;
FT_CHECK(25, 6e-2);
TEST_CHECK(0.2);
}
// Test custom training
TEST_CASE("unit/conv/sgd/partial/1", "[conv][dbn][mnist][sgd]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::conv_desc<1, 28, 28, 6, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
dll::dense_desc<6 * 24 * 24, 10, dll::activation<dll::function::SIGMOID>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::batch_size<10>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 1, 28, 28>>(350);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->learning_rate = 0.07;
auto trainer = dbn->get_trainer();
trainer.start_training(*dbn, false, 25);
// Train for 25 epochs
for(size_t epoch = 0; epoch < 25; ++epoch){
trainer.start_epoch(*dbn, epoch);
double error = 0.0;
double loss = 0.0;
for(std::size_t i = 0; i < 7; ++i){
std::tie(loss, error) = trainer.train_partial(
*dbn, false,
dataset.training_images.begin() + i * 50, dataset.training_images.begin() + (i + 1) * 50,
dataset.training_labels.begin() + i * 50,
epoch);
}
if(trainer.stop_epoch(*dbn, epoch, error, loss)){
break;
}
}
auto ft_error = trainer.stop_training(*dbn);
REQUIRE(ft_error < 5e-2);
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
REQUIRE(test_error < 0.2);
}
<|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 "test.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/http_connection.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <boost/optional.hpp>
using namespace libtorrent;
io_service ios;
connection_queue cq(ios);
int connect_handler_called = 0;
int handler_called = 0;
int data_size = 0;
int http_status = 0;
error_code g_error_code;
char data_buffer[4000];
void print_http_header(http_parser const& p)
{
std::cerr << " < " << p.status_code() << " " << p.message() << std::endl;
for (std::map<std::string, std::string>::const_iterator i
= p.headers().begin(), end(p.headers().end()); i != end; ++i)
{
std::cerr << " < " << i->first << ": " << i->second << std::endl;
}
}
void http_connect_handler(http_connection& c)
{
++connect_handler_called;
TEST_CHECK(c.socket().is_open());
error_code ec;
std::cerr << "connected to: " << c.socket().remote_endpoint(ec) << std::endl;
TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec));
}
void http_handler(error_code const& ec, http_parser const& parser
, char const* data, int size, http_connection& c)
{
++handler_called;
data_size = size;
g_error_code = ec;
if (parser.header_finished())
{
http_status = parser.status_code();
if (http_status == 200)
{
TEST_CHECK(memcmp(data, data_buffer, size) == 0);
}
}
print_http_header(parser);
}
void reset_globals()
{
connect_handler_called = 0;
handler_called = 0;
data_size = 0;
http_status = 0;
g_error_code = error_code();
}
void run_test(std::string const& url, int size, int status, int connected
, boost::optional<error_code> ec, proxy_settings const& ps)
{
reset_globals();
std::cerr << " ===== TESTING: " << url << " =====" << std::endl;
std::cerr << " expecting: size: " << size
<< " status: " << status
<< " connected: " << connected
<< " error: " << (ec?ec->message():"no error") << std::endl;
boost::shared_ptr<http_connection> h(new http_connection(ios, cq
, &::http_handler, true, &::http_connect_handler));
h->get(url, seconds(1), 0, &ps);
ios.reset();
error_code e;
ios.run(e);
std::cerr << "connect_handler_called: " << connect_handler_called << std::endl;
std::cerr << "handler_called: " << handler_called << std::endl;
std::cerr << "status: " << http_status << std::endl;
std::cerr << "size: " << data_size << std::endl;
std::cerr << "error_code: " << g_error_code.message() << std::endl;
TEST_CHECK(connect_handler_called == connected);
TEST_CHECK(handler_called == 1);
TEST_CHECK(data_size == size || size == -1);
TEST_CHECK(!ec || g_error_code == *ec);
TEST_CHECK(http_status == status || status == -1);
}
void run_suite(std::string const& protocol, proxy_settings const& ps)
{
if (ps.type != proxy_settings::none)
{
start_proxy(ps.port, ps.type);
}
char const* test_name[] = {"no", "SOCKS4", "SOCKS5"
, "SOCKS5 password protected", "HTTP", "HTTP password protected"};
std::cout << "\n\n********************** using " << test_name[ps.type]
<< " proxy **********************\n" << std::endl;
typedef boost::optional<error_code> err;
// this requires the hosts file to be modified
// run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/relative/redirect", 3216, 200, 2, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/redirect", 3216, 200, 2, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/infinite_redirect", 0, 301, 6, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/test_file", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/test_file.gz", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/non-existing-file", -1, 404, 1, err(), ps);
// if we're going through an http proxy, we won't get the same error as if the hostname
// resolution failed
if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https")
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps);
else
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps);
if (ps.type != proxy_settings::none)
stop_proxy(ps.port);
}
int test_main()
{
std::srand(std::time(0));
std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);
std::ofstream test_file("test_file", std::ios::trunc);
test_file.write(data_buffer, 3216);
TEST_CHECK(test_file.good());
test_file.close();
std::system("gzip -9 -c test_file > test_file.gz");
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8034;
ps.username = "testuser";
ps.password = "testpass";
start_web_server(8001);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("http", ps);
}
stop_web_server(8001);
#ifdef TORRENT_USE_OPENSSL
start_web_server(8001, true);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("https", ps);
}
stop_web_server(8001);
#endif
std::remove("test_file");
return 0;
}
<commit_msg>made test use internal file class instead of ofstream<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 "test.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include "libtorrent/http_connection.hpp"
#include "setup_transfer.hpp"
#include <fstream>
#include <boost/optional.hpp>
using namespace libtorrent;
io_service ios;
connection_queue cq(ios);
int connect_handler_called = 0;
int handler_called = 0;
int data_size = 0;
int http_status = 0;
error_code g_error_code;
char data_buffer[4000];
void print_http_header(http_parser const& p)
{
std::cerr << " < " << p.status_code() << " " << p.message() << std::endl;
for (std::map<std::string, std::string>::const_iterator i
= p.headers().begin(), end(p.headers().end()); i != end; ++i)
{
std::cerr << " < " << i->first << ": " << i->second << std::endl;
}
}
void http_connect_handler(http_connection& c)
{
++connect_handler_called;
TEST_CHECK(c.socket().is_open());
error_code ec;
std::cerr << "connected to: " << c.socket().remote_endpoint(ec) << std::endl;
TEST_CHECK(c.socket().remote_endpoint(ec).address() == address::from_string("127.0.0.1", ec));
}
void http_handler(error_code const& ec, http_parser const& parser
, char const* data, int size, http_connection& c)
{
++handler_called;
data_size = size;
g_error_code = ec;
if (parser.header_finished())
{
http_status = parser.status_code();
if (http_status == 200)
{
TEST_CHECK(memcmp(data, data_buffer, size) == 0);
}
}
print_http_header(parser);
}
void reset_globals()
{
connect_handler_called = 0;
handler_called = 0;
data_size = 0;
http_status = 0;
g_error_code = error_code();
}
void run_test(std::string const& url, int size, int status, int connected
, boost::optional<error_code> ec, proxy_settings const& ps)
{
reset_globals();
std::cerr << " ===== TESTING: " << url << " =====" << std::endl;
std::cerr << " expecting: size: " << size
<< " status: " << status
<< " connected: " << connected
<< " error: " << (ec?ec->message():"no error") << std::endl;
boost::shared_ptr<http_connection> h(new http_connection(ios, cq
, &::http_handler, true, &::http_connect_handler));
h->get(url, seconds(1), 0, &ps);
ios.reset();
error_code e;
ios.run(e);
std::cerr << "connect_handler_called: " << connect_handler_called << std::endl;
std::cerr << "handler_called: " << handler_called << std::endl;
std::cerr << "status: " << http_status << std::endl;
std::cerr << "size: " << data_size << std::endl;
std::cerr << "error_code: " << g_error_code.message() << std::endl;
TEST_CHECK(connect_handler_called == connected);
TEST_CHECK(handler_called == 1);
TEST_CHECK(data_size == size || size == -1);
TEST_CHECK(!ec || g_error_code == *ec);
TEST_CHECK(http_status == status || status == -1);
}
void run_suite(std::string const& protocol, proxy_settings const& ps)
{
if (ps.type != proxy_settings::none)
{
start_proxy(ps.port, ps.type);
}
char const* test_name[] = {"no", "SOCKS4", "SOCKS5"
, "SOCKS5 password protected", "HTTP", "HTTP password protected"};
std::cout << "\n\n********************** using " << test_name[ps.type]
<< " proxy **********************\n" << std::endl;
typedef boost::optional<error_code> err;
// this requires the hosts file to be modified
// run_test(protocol + "://test.dns.ts:8001/test_file", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/relative/redirect", 3216, 200, 2, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/redirect", 3216, 200, 2, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/infinite_redirect", 0, 301, 6, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/test_file", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/test_file.gz", 3216, 200, 1, error_code(), ps);
run_test(protocol + "://127.0.0.1:8001/non-existing-file", -1, 404, 1, err(), ps);
// if we're going through an http proxy, we won't get the same error as if the hostname
// resolution failed
if ((ps.type == proxy_settings::http || ps.type == proxy_settings::http_pw) && protocol != "https")
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, 502, 1, err(), ps);
else
run_test(protocol + "://non-existent-domain.se/non-existing-file", -1, -1, 0, err(), ps);
if (ps.type != proxy_settings::none)
stop_proxy(ps.port);
}
int test_main()
{
std::srand(std::time(0));
std::generate(data_buffer, data_buffer + sizeof(data_buffer), &std::rand);
error_code ec;
file test_file("test_file", file::write_only, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
file::iovec_t b = { data_buffer, 3216};
test_file.writev(0, &b, 1, ec);
TEST_CHECK(!ec);
if (ec) fprintf(stderr, "file error: %s\n", ec.message().c_str());
test_file.close();
std::system("gzip -9 -c test_file > test_file.gz");
proxy_settings ps;
ps.hostname = "127.0.0.1";
ps.port = 8034;
ps.username = "testuser";
ps.password = "testpass";
start_web_server(8001);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("http", ps);
}
stop_web_server(8001);
#ifdef TORRENT_USE_OPENSSL
start_web_server(8001, true);
for (int i = 0; i < 5; ++i)
{
ps.type = (proxy_settings::proxy_type)i;
run_suite("https", ps);
}
stop_web_server(8001);
#endif
std::remove("test_file");
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.