text stringlengths 54 60.6k |
|---|
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 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 "catch.hpp"
#include "dll/dbn.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE( "dbn/mnist_1", "dbn::simple" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(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);
}
TEST_CASE( "dbn/mnist_2", "dbn::containers" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(200);
dataset.training_labels.resize(200);
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 5);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
REQUIRE(error < 5e-2);
}
TEST_CASE( "dbn/mnist_3", "dbn::labels" ) {
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
typedef dll::dbn_desc<
dll::dbn_label_layers<
dll::rbm_desc<28 * 28, 200, dll::batch_size<50>, dll::init_weights, dll::momentum>::rbm_t,
dll::rbm_desc<200, 300, dll::batch_size<50>, dll::momentum>::rbm_t,
dll::rbm_desc<310, 500, dll::batch_size<50>, dll::momentum>::rbm_t>
, dll::batch_size<10>
>::dbn_t dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->train_with_labels(dataset.training_images, dataset.training_labels, 10, 10);
auto error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::label_predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(error < 0.3);
}
TEST_CASE( "dbn/mnist_6", "dbn::cg_gaussian" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible<dll::unit_type::GAUSSIAN>>::rbm_t,
dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::normalize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(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);
}
//This test should not perform well, but should not fail
TEST_CASE( "dbn/mnist_8", "dbn::cg_relu" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::RELU>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(200);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(std::isfinite(error));
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
}
TEST_CASE( "dbn/mnist_15", "dbn::parallel" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::parallel_mode, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(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);
}
TEST_CASE( "dbn/mnist_17", "dbn::memory" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::memory
, dll::batch_size<50>
, dll::big_batch_size<3>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(
dataset.training_images.begin(), dataset.training_images.end(),
dataset.training_labels.begin(), dataset.training_labels.end(),
10);
REQUIRE(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);
//Mostly here to ensure compilation
auto out = dbn->prepare_one_output();
REQUIRE(out.size() > 0);
}
<commit_msg>Make sure there are incomplete batches<commit_after>//=======================================================================
// Copyright (c) 2014-2015 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 "catch.hpp"
#include "dll/dbn.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE( "dbn/mnist_1", "dbn::simple" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(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);
}
TEST_CASE( "dbn/mnist_2", "dbn::containers" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
dataset.training_images.resize(200);
dataset.training_labels.resize(200);
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 5);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
REQUIRE(error < 5e-2);
}
TEST_CASE( "dbn/mnist_3", "dbn::labels" ) {
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
typedef dll::dbn_desc<
dll::dbn_label_layers<
dll::rbm_desc<28 * 28, 200, dll::batch_size<50>, dll::init_weights, dll::momentum>::rbm_t,
dll::rbm_desc<200, 300, dll::batch_size<50>, dll::momentum>::rbm_t,
dll::rbm_desc<310, 500, dll::batch_size<50>, dll::momentum>::rbm_t>
, dll::batch_size<10>
>::dbn_t dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->train_with_labels(dataset.training_images, dataset.training_labels, 10, 10);
auto error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::label_predictor());
std::cout << "test_error:" << error << std::endl;
REQUIRE(error < 0.3);
}
TEST_CASE( "dbn/mnist_6", "dbn::cg_gaussian" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible<dll::unit_type::GAUSSIAN>>::rbm_t,
dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1000);
REQUIRE(!dataset.training_images.empty());
mnist::normalize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(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);
}
//This test should not perform well, but should not fail
TEST_CASE( "dbn/mnist_8", "dbn::cg_relu" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::RELU>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(200);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(std::isfinite(error));
auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
std::cout << "test_error:" << test_error << std::endl;
}
TEST_CASE( "dbn/mnist_15", "dbn::parallel" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::parallel_mode, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::batch_size<50>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(500);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);
REQUIRE(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);
}
TEST_CASE( "dbn/mnist_17", "dbn::memory" ) {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::rbm_t,
dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::rbm_t,
dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t>
, dll::memory
, dll::batch_size<50>
, dll::big_batch_size<3>
>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(1078);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->pretrain(dataset.training_images, 20);
auto error = dbn->fine_tune(
dataset.training_images.begin(), dataset.training_images.end(),
dataset.training_labels.begin(), dataset.training_labels.end(),
10);
REQUIRE(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);
//Mostly here to ensure compilation
auto out = dbn->prepare_one_output();
REQUIRE(out.size() > 0);
}
<|endoftext|> |
<commit_before>{
// display the various 2-d drawing options
//Author: Rene Brun
gROOT->Reset();
gStyle->SetOptStat(0);
gStyle->SetPalette(1);
gStyle->SetCanvasColor(33);
gStyle->SetFrameFillColor(18);
TF2 *f2 = new TF2("f2","xygaus + xygaus(5) + xylandau(10)",-4,4,-4,4);
Double_t params[] = {130,-1.4,1.8,1.5,1, 150,2,0.5,-2,0.5, 3600,-2,0.7,-3,0.3};
f2.SetParameters(params);
TH2F h2("h2","xygaus + xygaus(5) + xylandau(10)",20,-4,4,20,-4,4);
h2.SetFillColor(46);
h2.FillRandom("f2",40000);
TPaveLabel pl;
//basic 2-d options
Float_t x1=0.67, y1=0.875, x2=0.85, y2=0.95;
Int_t cancolor = 17;
TCanvas c2h("c2h","2-d options",10,10,800,600);
c2h.Divide(2,2);
c2h.SetFillColor(cancolor);
c2h.cd(1);
h2.Draw(); pl.DrawPaveLabel(x1,y1,x2,y2,"SCAT","brNDC");
c2h.cd(2);
h2.Draw("box"); pl.DrawPaveLabel(x1,y1,x2,y2,"BOX","brNDC");
c2h.cd(3);
h2.Draw("arr"); pl.DrawPaveLabel(x1,y1,x2,y2,"ARR","brNDC");
c2h.cd(4);
h2.Draw("colz"); pl.DrawPaveLabel(x1,y1,x2,y2,"COLZ","brNDC");
c2h.Update();
// see the canvas begin_html <a href="gif/h2_c2h.gif" >c2h</a> end_html
//text option
TCanvas ctext("ctext","text option",50,50,800,600);
gPad->SetGrid();
ctext.SetFillColor(cancolor);
ctext->SetGrid();
h2.Draw("text"); pl.DrawPaveLabel(x1,y1,x2,y2,"TEXT","brNDC");
ctext.Update();
// see the canvas begin_html <a href="gif/h2_text.gif" >ctext</a> end_html
//contour options
TCanvas cont("contours","contours",100,100,800,600);
cont.Divide(2,2);
gPad->SetGrid();
cont.SetFillColor(cancolor);
cont.cd(1);
h2.Draw("contz"); pl.DrawPaveLabel(x1,y1,x2,y2,"CONTZ","brNDC");
cont.cd(2);
gPad->SetGrid();
h2.Draw("cont1"); pl.DrawPaveLabel(x1,y1,x2,y2,"CONT1","brNDC");
cont.cd(3);
gPad->SetGrid();
h2.Draw("cont2"); pl.DrawPaveLabel(x1,y1,x2,y2,"CONT2","brNDC");
cont.cd(4);
gPad->SetGrid();
h2.Draw("cont3"); pl.DrawPaveLabel(x1,y1,x2,y2,"CONT3","brNDC");
cont.Update();
// see the canvas begin_html <a href="gif/h2_cont.gif" >contours</a> end_html
//lego options
TCanvas lego("lego","lego options",150,150,800,600);
lego.Divide(2,2);
lego.SetFillColor(cancolor);
lego.cd(1);
h2.Draw("lego"); pl.DrawPaveLabel(x1,y1,x2,y2,"LEGO","brNDC");
lego.cd(2);
h2.Draw("lego1"); pl.DrawPaveLabel(x1,y1,x2,y2,"LEGO1","brNDC");
lego.cd(3);
gPad->SetTheta(61); gPad->SetPhi(-82);
h2.Draw("surf1pol"); pl.DrawPaveLabel(x1,y1,x2+0.05,y2,"SURF1POL","brNDC");
lego.cd(4);
gPad->SetTheta(21); gPad->SetPhi(-90);
h2.Draw("surf1cyl"); pl.DrawPaveLabel(x1,y1,x2+0.05,y2,"SURF1CYL","brNDC");
lego.Update();
// see the canvas begin_html <a href="gif/h2_lego.gif" >lego</a> end_html
//surface options
TCanvas surf("surfopt","surface options",200,200,800,600);
surf.Divide(2,2);
surf.SetFillColor(cancolor);
surf.cd(1);
h2.Draw("surf1"); pl.DrawPaveLabel(x1,y1,x2,y2,"SURF1","brNDC");
surf.cd(2);
h2.Draw("surf2z"); pl.DrawPaveLabel(x1,y1,x2,y2,"SURF2Z","brNDC");
surf.cd(3);
h2.Draw("surf3"); pl.DrawPaveLabel(x1,y1,x2,y2,"SURF3","brNDC");
surf.cd(4);
h2.Draw("surf4"); pl.DrawPaveLabel(x1,y1,x2,y2,"SURF4","brNDC");
surf.Update();
// see the canvas begin_html <a href="gif/h2_surf.gif" >surfaces</a> end_html
}
<commit_msg>Now that the canvases are included: remove stale links<commit_after>{
// display the various 2-d drawing options
//Author: Rene Brun
gROOT->Reset();
gStyle->SetOptStat(0);
gStyle->SetPalette(1);
gStyle->SetCanvasColor(33);
gStyle->SetFrameFillColor(18);
TF2 *f2 = new TF2("f2","xygaus + xygaus(5) + xylandau(10)",-4,4,-4,4);
Double_t params[] = {130,-1.4,1.8,1.5,1, 150,2,0.5,-2,0.5, 3600,-2,0.7,-3,0.3};
f2.SetParameters(params);
TH2F h2("h2","xygaus + xygaus(5) + xylandau(10)",20,-4,4,20,-4,4);
h2.SetFillColor(46);
h2.FillRandom("f2",40000);
TPaveLabel pl;
//basic 2-d options
Float_t x1=0.67, y1=0.875, x2=0.85, y2=0.95;
Int_t cancolor = 17;
TCanvas c2h("c2h","2-d options",10,10,800,600);
c2h.Divide(2,2);
c2h.SetFillColor(cancolor);
c2h.cd(1);
h2.Draw(); pl.DrawPaveLabel(x1,y1,x2,y2,"SCAT","brNDC");
c2h.cd(2);
h2.Draw("box"); pl.DrawPaveLabel(x1,y1,x2,y2,"BOX","brNDC");
c2h.cd(3);
h2.Draw("arr"); pl.DrawPaveLabel(x1,y1,x2,y2,"ARR","brNDC");
c2h.cd(4);
h2.Draw("colz"); pl.DrawPaveLabel(x1,y1,x2,y2,"COLZ","brNDC");
c2h.Update();
//text option
TCanvas ctext("ctext","text option",50,50,800,600);
gPad->SetGrid();
ctext.SetFillColor(cancolor);
ctext->SetGrid();
h2.Draw("text"); pl.DrawPaveLabel(x1,y1,x2,y2,"TEXT","brNDC");
ctext.Update();
//contour options
TCanvas cont("contours","contours",100,100,800,600);
cont.Divide(2,2);
gPad->SetGrid();
cont.SetFillColor(cancolor);
cont.cd(1);
h2.Draw("contz"); pl.DrawPaveLabel(x1,y1,x2,y2,"CONTZ","brNDC");
cont.cd(2);
gPad->SetGrid();
h2.Draw("cont1"); pl.DrawPaveLabel(x1,y1,x2,y2,"CONT1","brNDC");
cont.cd(3);
gPad->SetGrid();
h2.Draw("cont2"); pl.DrawPaveLabel(x1,y1,x2,y2,"CONT2","brNDC");
cont.cd(4);
gPad->SetGrid();
h2.Draw("cont3"); pl.DrawPaveLabel(x1,y1,x2,y2,"CONT3","brNDC");
cont.Update();
//lego options
TCanvas lego("lego","lego options",150,150,800,600);
lego.Divide(2,2);
lego.SetFillColor(cancolor);
lego.cd(1);
h2.Draw("lego"); pl.DrawPaveLabel(x1,y1,x2,y2,"LEGO","brNDC");
lego.cd(2);
h2.Draw("lego1"); pl.DrawPaveLabel(x1,y1,x2,y2,"LEGO1","brNDC");
lego.cd(3);
gPad->SetTheta(61); gPad->SetPhi(-82);
h2.Draw("surf1pol"); pl.DrawPaveLabel(x1,y1,x2+0.05,y2,"SURF1POL","brNDC");
lego.cd(4);
gPad->SetTheta(21); gPad->SetPhi(-90);
h2.Draw("surf1cyl"); pl.DrawPaveLabel(x1,y1,x2+0.05,y2,"SURF1CYL","brNDC");
lego.Update();
//surface options
TCanvas surf("surfopt","surface options",200,200,800,600);
surf.Divide(2,2);
surf.SetFillColor(cancolor);
surf.cd(1);
h2.Draw("surf1"); pl.DrawPaveLabel(x1,y1,x2,y2,"SURF1","brNDC");
surf.cd(2);
h2.Draw("surf2z"); pl.DrawPaveLabel(x1,y1,x2,y2,"SURF2Z","brNDC");
surf.cd(3);
h2.Draw("surf3"); pl.DrawPaveLabel(x1,y1,x2,y2,"SURF3","brNDC");
surf.cd(4);
h2.Draw("surf4"); pl.DrawPaveLabel(x1,y1,x2,y2,"SURF4","brNDC");
surf.Update();
}
<|endoftext|> |
<commit_before>#include "GameScene.h"
#include "NNApplication.h"
#include "PacketType.h"
#include "NNNetworkSystem.h"
#include "PacketHandler.h"
CGameScene::CGameScene(void):m_NowGameKeyStates(),m_Angle(0),m_LastAngleChangedTime(timeGetTime())
{
m_LoginHandler = new LoginHandler();
m_LoginBroadcastHandler = new LoginBroadcastHandler();
m_GameKeyStatesUpdateHandler = new GameKeyStatesUpdateHandler();
m_LogoutHandler = new LogoutHandler();
m_MouseAngleUpdateHandler = new MouseAngleUpdateHandler();
m_GameMap = CGameMap::Create();
AddChild(m_GameMap);
m_FPSLbael = NNLabel::Create( L"Normal Label", L" ", 35.f );
AddChild(m_FPSLbael);
NNNetworkSystem::GetInstance()->Init();
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_KEYSTATE,m_GameKeyStatesUpdateHandler);
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_LOGIN,m_LoginHandler);
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_LOGIN_BROADCAST,m_LoginBroadcastHandler);
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_LOGOUT,m_LogoutHandler);
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_MOUSEANGLE,m_MouseAngleUpdateHandler);
NNNetworkSystem::GetInstance()->Connect("127.0.0.1",9001);//10.73.44.30",9001);
NNNetworkSystem::GetInstance()->Write( (const char*)&m_LoginHandler->m_LoginRequestPacket, m_LoginHandler->m_LoginRequestPacket.m_Size );
GetCamera().SetCameraAnchor(CameraAnchor::MIDDLE_CENTER);
}
CGameScene::~CGameScene(void)
{
}
void CGameScene::Render()
{
NNScene::Render();
}
void CGameScene::Update( float dTime )
{
NNScene::Update(dTime);
swprintf_s(m_FPSLabelBuff,L"%d",(int)NNApplication::GetInstance()->GetFPS());
m_FPSLbael->SetString(m_FPSLabelBuff);
if(CPlayerManager::GetInstance()->IsLogin() == true)
{
GetCamera().SetPosition(NNPoint().Lerp(GetCamera().GetPosition(),
CPlayerManager::GetInstance()->GetMyPlayer()->GetPosition()
,0.99f));
if( isChangedGameKeyStates() == true)
{
m_LastAngleChangedTime = timeGetTime();
m_Angle = GetNowAngle();
m_NowGameKeyStates = GetNowGameKeyStates();
//send packet
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_GameKeyStates = GetNowGameKeyStates();
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_PlayerId = CPlayerManager::GetInstance()->GetMyPlayerId();
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_X = CPlayerManager::GetInstance()->GetMyPlayer()->GetPositionX();
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_Y = CPlayerManager::GetInstance()->GetMyPlayer()->GetPositionY();
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_Angle = m_Angle;
NNNetworkSystem::GetInstance()->Write( (const char*)&m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest,
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_Size );
}
if( isChangedAngle() == true )
{
m_LastAngleChangedTime = timeGetTime();
m_Angle = GetNowAngle();
m_MouseAngleUpdateHandler->m_MouseAngleUpdateRequest.m_PlayerId = CPlayerManager::GetInstance()->GetMyPlayerId();
m_MouseAngleUpdateHandler->m_MouseAngleUpdateRequest.m_Angle = m_Angle;
NNNetworkSystem::GetInstance()->Write( (const char*)&m_MouseAngleUpdateHandler->m_MouseAngleUpdateRequest,
m_MouseAngleUpdateHandler->m_MouseAngleUpdateRequest.m_Size );
}
}
}
GameKeyStates CGameScene::GetNowGameKeyStates()
{
GameKeyStates nowGameKeyState;
if( NNInputSystem::GetInstance()->GetKeyState('W') == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState('W') == KEY_DOWN )
nowGameKeyState.upDirectKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState('S') == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState('S') == KEY_DOWN )
nowGameKeyState.downDirectKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState('A') == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState('A') == KEY_DOWN )
nowGameKeyState.leftDirectKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState('D') == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState('D') == KEY_DOWN )
nowGameKeyState.rightDirectKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState(VK_LBUTTON) == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState(VK_LBUTTON) == KEY_DOWN )
nowGameKeyState.attackKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState(VK_RBUTTON) == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState(VK_RBUTTON) == KEY_DOWN )
nowGameKeyState.typeActiveSkillKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState(VK_SPACE) == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState(VK_SPACE) == KEY_DOWN )
nowGameKeyState.userActiveSkillKey = KEYSTATE_PRESSED;
return nowGameKeyState;
}
bool CGameScene::isChangedGameKeyStates()
{
GameKeyStates nowGameKeyState = GetNowGameKeyStates();
if( nowGameKeyState.attackKey != m_NowGameKeyStates.attackKey
||nowGameKeyState.downDirectKey != m_NowGameKeyStates.downDirectKey
||nowGameKeyState.leftDirectKey != m_NowGameKeyStates.leftDirectKey
||nowGameKeyState.rightDirectKey != m_NowGameKeyStates.rightDirectKey
||nowGameKeyState.typeActiveSkillKey != m_NowGameKeyStates.typeActiveSkillKey
||nowGameKeyState.upDirectKey != m_NowGameKeyStates.upDirectKey
||nowGameKeyState.userActiveSkillKey != m_NowGameKeyStates.userActiveSkillKey)
return true;
return false;
}
float CGameScene::GetNowAngle()
{
NNPoint mousePoint = NNInputSystem::GetInstance()->GetMousePosition();
// characterPositionByWC, WC -> window center. ȭ 0,0 ij ǥ
//NNPoint characterPositionByWC = GetCamera().GetPosition() - CPlayerManager::GetInstance()->GetMyPlayer()->GetPosition();
NNPoint referencePointForMouse = NNPoint(GetCamera().GetScreenWidth()/2,GetCamera().GetScreenHeight()/2);// + characterPositionByWC;
return atan2f( NNPoint(mousePoint-referencePointForMouse).GetY() , NNPoint(mousePoint-referencePointForMouse).GetX() )*180.0f/3.14f ;
}
bool CGameScene::isChangedAngle()
{
DWORD time_A = timeGetTime();
if( (timeGetTime() - m_LastAngleChangedTime ) > 20 )
{
//20 и帶 콺 .
if( m_Angle != GetNowAngle() )
{
printf("Oh!!\n");
return true;
}
}
return false;
}<commit_msg>@ fixed name<commit_after>#include "GameScene.h"
#include "NNApplication.h"
#include "PacketType.h"
#include "NNNetworkSystem.h"
#include "PacketHandler.h"
CGameScene::CGameScene(void):m_NowGameKeyStates(),m_Angle(0),m_LastAngleChangedTime(timeGetTime())
{
m_LoginHandler = new LoginHandler();
m_LoginBroadcastHandler = new LoginBroadcastHandler();
m_GameKeyStatesUpdateHandler = new GameKeyStatesUpdateHandler();
m_LogoutHandler = new LogoutHandler();
m_MouseAngleUpdateHandler = new MouseAngleUpdateHandler();
m_GameMap = CGameMap::Create();
AddChild( m_GameMap );
m_FPSLabel = NNLabel::Create( L"Normal Label", L" ", 35.f );
AddChild( m_FPSLabel );
NNNetworkSystem::GetInstance()->Init();
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_KEYSTATE,m_GameKeyStatesUpdateHandler);
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_LOGIN,m_LoginHandler);
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_LOGIN_BROADCAST,m_LoginBroadcastHandler);
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_LOGOUT,m_LogoutHandler);
NNNetworkSystem::GetInstance()->SetPacketHandler(PKT_SC_MOUSEANGLE,m_MouseAngleUpdateHandler);
NNNetworkSystem::GetInstance()->Connect("127.0.0.1",9001);//10.73.44.30",9001);
NNNetworkSystem::GetInstance()->Write( (const char*)&m_LoginHandler->m_LoginRequestPacket, m_LoginHandler->m_LoginRequestPacket.m_Size );
GetCamera().SetCameraAnchor(CameraAnchor::MIDDLE_CENTER);
}
CGameScene::~CGameScene(void)
{
}
void CGameScene::Render()
{
NNScene::Render();
}
void CGameScene::Update( float dTime )
{
NNScene::Update(dTime);
swprintf_s(m_FPSLabelBuff,L"%d",(int)NNApplication::GetInstance()->GetFPS());
m_FPSLabel->SetString(m_FPSLabelBuff);
if( CPlayerManager::GetInstance()->IsLogin() == true )
{
GetCamera().SetPosition(NNPoint().Lerp(GetCamera().GetPosition(),
CPlayerManager::GetInstance()->GetMyPlayer()->GetPosition()
,0.99f));
if( isChangedGameKeyStates() == true )
{
m_LastAngleChangedTime = timeGetTime();
m_Angle = GetNowAngle();
m_NowGameKeyStates = GetNowGameKeyStates();
//send packet
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_GameKeyStates = GetNowGameKeyStates();
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_PlayerId = CPlayerManager::GetInstance()->GetMyPlayerId();
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_X = CPlayerManager::GetInstance()->GetMyPlayer()->GetPositionX();
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_Y = CPlayerManager::GetInstance()->GetMyPlayer()->GetPositionY();
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_MyPlayerInfo.m_Angle = m_Angle;
NNNetworkSystem::GetInstance()->Write( (const char*)&m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest,
m_GameKeyStatesUpdateHandler->m_GameKeyStatesUpdateRequest.m_Size );
}
if( isChangedAngle() == true )
{
m_LastAngleChangedTime = timeGetTime();
m_Angle = GetNowAngle();
m_MouseAngleUpdateHandler->m_MouseAngleUpdateRequest.m_PlayerId = CPlayerManager::GetInstance()->GetMyPlayerId();
m_MouseAngleUpdateHandler->m_MouseAngleUpdateRequest.m_Angle = m_Angle;
NNNetworkSystem::GetInstance()->Write( (const char*)&m_MouseAngleUpdateHandler->m_MouseAngleUpdateRequest,
m_MouseAngleUpdateHandler->m_MouseAngleUpdateRequest.m_Size );
}
}
}
GameKeyStates CGameScene::GetNowGameKeyStates()
{
GameKeyStates nowGameKeyState;
if( NNInputSystem::GetInstance()->GetKeyState('W') == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState('W') == KEY_DOWN )
nowGameKeyState.upDirectKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState('S') == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState('S') == KEY_DOWN )
nowGameKeyState.downDirectKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState('A') == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState('A') == KEY_DOWN )
nowGameKeyState.leftDirectKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState('D') == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState('D') == KEY_DOWN )
nowGameKeyState.rightDirectKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState(VK_LBUTTON) == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState(VK_LBUTTON) == KEY_DOWN )
nowGameKeyState.attackKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState(VK_RBUTTON) == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState(VK_RBUTTON) == KEY_DOWN )
nowGameKeyState.typeActiveSkillKey = KEYSTATE_PRESSED;
if( NNInputSystem::GetInstance()->GetKeyState(VK_SPACE) == KEY_PRESSED ||
NNInputSystem::GetInstance()->GetKeyState(VK_SPACE) == KEY_DOWN )
nowGameKeyState.userActiveSkillKey = KEYSTATE_PRESSED;
return nowGameKeyState;
}
bool CGameScene::isChangedGameKeyStates()
{
GameKeyStates nowGameKeyState = GetNowGameKeyStates();
if( nowGameKeyState.attackKey != m_NowGameKeyStates.attackKey
||nowGameKeyState.downDirectKey != m_NowGameKeyStates.downDirectKey
||nowGameKeyState.leftDirectKey != m_NowGameKeyStates.leftDirectKey
||nowGameKeyState.rightDirectKey != m_NowGameKeyStates.rightDirectKey
||nowGameKeyState.typeActiveSkillKey != m_NowGameKeyStates.typeActiveSkillKey
||nowGameKeyState.upDirectKey != m_NowGameKeyStates.upDirectKey
||nowGameKeyState.userActiveSkillKey != m_NowGameKeyStates.userActiveSkillKey)
return true;
return false;
}
float CGameScene::GetNowAngle()
{
NNPoint mousePoint = NNInputSystem::GetInstance()->GetMousePosition();
// characterPositionByWC, WC -> window center. ȭ 0,0 ij ǥ
//NNPoint characterPositionByWC = GetCamera().GetPosition() - CPlayerManager::GetInstance()->GetMyPlayer()->GetPosition();
NNPoint referencePointForMouse = NNPoint(GetCamera().GetScreenWidth()/2,GetCamera().GetScreenHeight()/2);// + characterPositionByWC;
return atan2f( NNPoint(mousePoint-referencePointForMouse).GetY() , NNPoint(mousePoint-referencePointForMouse).GetX() )*180.0f/3.14f ;
}
bool CGameScene::isChangedAngle()
{
DWORD time_A = timeGetTime();
if( (timeGetTime() - m_LastAngleChangedTime ) > 20 )
{
//20 и帶 콺 .
if( m_Angle != GetNowAngle() )
{
printf("Oh!!\n");
return true;
}
}
return false;
}<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <iostream>
#include "gc/baker.hpp"
#include "objectmemory.hpp"
#include "object_utils.hpp"
#include "builtin/tuple.hpp"
#include "builtin/class.hpp"
#include "builtin/io.hpp"
#include "call_frame.hpp"
#include "gc/gc.hpp"
#include "capi/handles.hpp"
#include "capi/tag.hpp"
#ifdef ENABLE_LLVM
#include "llvm/state.hpp"
#endif
namespace rubinius {
/**
* Creates a BakerGC of the specified size.
*
* The requested size is allocated as a contiguous heap, which is then split
* into three spaces:
* - Eden, which gets half of the heap
* - Heap A and Heap B, which get one quarter of the heap each. Heaps A and B
* alternate between being the Current and Next space on each collection.
*/
BakerGC::BakerGC(ObjectMemory *om, size_t bytes)
: GarbageCollector(om)
, full(bytes * 2)
, eden(full.allocate(bytes), bytes)
, heap_a(full.allocate(bytes / 2), bytes / 2)
, heap_b(full.allocate(bytes / 2), bytes / 2)
, total_objects(0)
, copy_spills_(0)
, autotune_(false)
, tune_threshold_(0)
, original_lifetime_(1)
, lifetime_(1)
{
current = &heap_a;
next = &heap_b;
}
BakerGC::~BakerGC() { }
/**
* Called for each object in the young generation that is seen during garbage
* collection. An object is seen by scanning from the root objects to all
* reachable objects. Therefore, only reachable objects will be seen, and
* reachable objects may be seen more than once.
*
* @returns the new address for the object, so that the source reference can
* be updated when the object has been moved.
*/
Object* BakerGC::saw_object(Object* obj) {
Object* copy;
#ifdef ENABLE_OBJECT_WATCH
if(watched_p(obj)) {
std::cout << "detected " << obj << " during baker collection\n";
}
#endif
if(!obj->reference_p()) return obj;
if(!obj->young_object_p()) return obj;
if(obj->forwarded_p()) return obj->forward();
// This object is already in the next space, we don't want to
// copy it again!
if(next->contains_p(obj)) return obj;
if(unlikely(obj->inc_age() >= lifetime_)) {
copy = object_memory_->promote_object(obj);
promoted_push(copy);
} else if(likely(next->enough_space_p(
obj->size_in_bytes(object_memory_->state())))) {
copy = next->move_object(object_memory_->state(), obj);
total_objects++;
} else {
copy_spills_++;
copy = object_memory_->promote_object(obj);
promoted_push(copy);
}
#ifdef ENABLE_OBJECT_WATCH
if(watched_p(copy)) {
std::cout << "detected " << copy << " during baker collection (2)\n";
}
#endif
return copy;
}
/**
* Scans the remaining unscanned portion of the Next heap.
*/
void BakerGC::copy_unscanned() {
Object* iobj = next->next_unscanned(object_memory_->state());
while(iobj) {
assert(iobj->young_object_p());
if(!iobj->forwarded_p()) scan_object(iobj);
iobj = next->next_unscanned(object_memory_->state());
}
}
/**
* Returns true if the young generation has been fully scanned in the
* current collection.
*/
bool BakerGC::fully_scanned_p() {
// Note: The spaces are swapped at the start of collection, which is why we
// check the Next heap
return next->fully_scanned_p();
}
const static double cOverFullThreshold = 95.0;
const static int cOverFullTimes = 3;
const static size_t cMinimumLifetime = 1;
const static double cUnderFullThreshold = 20.0;
const static int cUnderFullTimes = -3;
const static size_t cMaximumLifetime = 6;
/**
* Perform garbage collection on the young objects.
*/
void BakerGC::collect(GCData& data, YoungCollectStats* stats) {
#ifdef HAVE_VALGRIND_H
(void)VALGRIND_MAKE_MEM_DEFINED(next->start().as_int(), next->size());
(void)VALGRIND_MAKE_MEM_DEFINED(current->start().as_int(), current->size());
#endif
mprotect(next->start(), next->size(), PROT_READ | PROT_WRITE);
mprotect(current->start(), current->size(), PROT_READ | PROT_WRITE);
Object* tmp;
ObjectArray *current_rs = object_memory_->swap_remember_set();
total_objects = 0;
copy_spills_ = 0;
reset_promoted();
// Start by copying objects in the remember set
for(ObjectArray::iterator oi = current_rs->begin();
oi != current_rs->end();
++oi) {
tmp = *oi;
// unremember_object throws a NULL in to remove an object
// so we don't have to compact the set in unremember
if(tmp) {
// assert(tmp->mature_object_p());
// assert(!tmp->forwarded_p());
// Remove the Remember bit, since we're clearing the set.
tmp->clear_remember();
scan_object(tmp);
}
}
delete current_rs;
for(std::list<gc::WriteBarrier*>::iterator wbi = object_memory_->aux_barriers().begin();
wbi != object_memory_->aux_barriers().end();
++wbi) {
gc::WriteBarrier* wb = *wbi;
ObjectArray* rs = wb->swap_remember_set();
for(ObjectArray::iterator oi = rs->begin();
oi != rs->end();
++oi) {
tmp = *oi;
if(tmp) {
tmp->clear_remember();
scan_object(tmp);
}
}
delete rs;
}
for(Roots::Iterator i(data.roots()); i.more(); i.advance()) {
i->set(saw_object(i->get()));
}
if(data.threads()) {
for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
i != data.threads()->end();
++i) {
scan(*i, true);
}
}
for(Allocator<capi::Handle>::Iterator i(data.handles()->allocator()); i.more(); i.advance()) {
if(!i->in_use_p()) continue;
if(!i->weak_p() && i->object()->young_object_p()) {
i->set_object(saw_object(i->object()));
// Users manipulate values accessible from the data* within an
// RData without running a write barrier. Thusly if we see a mature
// rdata, we must always scan it because it could contain
// young pointers.
} else if(!i->object()->young_object_p() && i->is_rdata()) {
scan_object(i->object());
}
assert(i->object()->type_id() > InvalidType && i->object()->type_id() < LastObjectType);
}
std::list<capi::GlobalHandle*>* gh = data.global_handle_locations();
if(gh) {
for(std::list<capi::GlobalHandle*>::iterator i = gh->begin();
i != gh->end();
++i) {
capi::GlobalHandle* global_handle = *i;
capi::Handle** loc = global_handle->handle();
if(capi::Handle* hdl = *loc) {
if(!REFERENCE_P(hdl)) continue;
if(hdl->valid_p()) {
Object* obj = hdl->object();
if(obj && obj->reference_p() && obj->young_object_p()) {
hdl->set_object(saw_object(obj));
}
} else {
std::cerr << "Detected bad handle checking global capi handles\n";
}
}
}
}
#ifdef ENABLE_LLVM
if(LLVMState* ls = data.llvm_state()) ls->gc_scan(this);
#endif
// Handle all promotions to non-young space that occurred.
handle_promotions();
assert(fully_scanned_p());
// We're now done seeing the entire object graph of normal, live references.
// Now we get to handle the unusual references, like finalizers and such.
// Check any weakrefs and replace dead objects with nil
// We need to do this before checking finalizers so people can't access
// objects kept alive for finalization through weakrefs.
clean_weakrefs(true);
// Objects with finalizers must be kept alive until the finalizers have
// run.
walk_finalizers();
// Process possible promotions from processing objects with finalizers.
handle_promotions();
if(!promoted_stack_.empty()) rubinius::bug("promote stack has elements!");
if(!fully_scanned_p()) rubinius::bug("more young refs");
// Remove unreachable locked objects still in the list
if(data.threads()) {
for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
i != data.threads()->end();
++i) {
clean_locked_objects(*i, true);
}
}
// Swap the 2 halves
Heap *x = next;
next = current;
current = x;
if(stats) {
stats->lifetime = lifetime_;
stats->percentage_used = current->percentage_used();
stats->promoted_objects = promoted_objects_;
stats->excess_objects = copy_spills_;
}
// Tune the age at which promotion occurs
if(autotune_) {
double used = current->percentage_used();
if(used > cOverFullThreshold) {
if(tune_threshold_ >= cOverFullTimes) {
if(lifetime_ > cMinimumLifetime) lifetime_--;
} else {
tune_threshold_++;
}
} else if(used < cUnderFullThreshold) {
if(tune_threshold_ <= cUnderFullTimes) {
if(lifetime_ < cMaximumLifetime) lifetime_++;
} else {
tune_threshold_--;
}
} else if(tune_threshold_ > 0) {
tune_threshold_--;
} else if(tune_threshold_ < 0) {
tune_threshold_++;
} else if(tune_threshold_ == 0) {
if(lifetime_ < original_lifetime_) {
lifetime_++;
} else if(lifetime_ > original_lifetime_) {
lifetime_--;
}
}
}
}
bool BakerGC::handle_promotions() {
if(promoted_stack_.empty() && fully_scanned_p()) return false;
while(!promoted_stack_.empty() || !fully_scanned_p()) {
while(!promoted_stack_.empty()) {
Object* obj = promoted_stack_.back();
promoted_stack_.pop_back();
scan_object(obj);
}
copy_unscanned();
}
return true;
}
void BakerGC::walk_finalizers() {
FinalizerHandler* fh = object_memory_->finalizer_handler();
if(!fh) return;
for(FinalizerHandler::iterator i = fh->begin();
!i.end();
/* advance is handled in the loop */)
{
FinalizeObject& fi = i.current();
bool live = true;
if(fi.object->young_object_p()) {
live = fi.object->forwarded_p();
fi.object = saw_object(fi.object);
}
Object *fin = fi.ruby_finalizer;
if(fin && fin != cTrue && fin->young_object_p()) {
fi.ruby_finalizer = saw_object(fi.ruby_finalizer);
}
i.next(live);
}
}
bool BakerGC::in_current_p(Object* obj) {
return current->contains_p(obj);
}
ObjectPosition BakerGC::validate_object(Object* obj) {
if(current->contains_p(obj) || eden.contains_p(obj)) {
return cValid;
} else if(next->contains_p(obj)) {
return cInWrongYoungHalf;
} else {
return cUnknown;
}
}
}
<commit_msg>Use a general reference check, not only cTrue<commit_after>#include <stdlib.h>
#include <iostream>
#include "gc/baker.hpp"
#include "objectmemory.hpp"
#include "object_utils.hpp"
#include "builtin/tuple.hpp"
#include "builtin/class.hpp"
#include "builtin/io.hpp"
#include "call_frame.hpp"
#include "gc/gc.hpp"
#include "capi/handles.hpp"
#include "capi/tag.hpp"
#ifdef ENABLE_LLVM
#include "llvm/state.hpp"
#endif
namespace rubinius {
/**
* Creates a BakerGC of the specified size.
*
* The requested size is allocated as a contiguous heap, which is then split
* into three spaces:
* - Eden, which gets half of the heap
* - Heap A and Heap B, which get one quarter of the heap each. Heaps A and B
* alternate between being the Current and Next space on each collection.
*/
BakerGC::BakerGC(ObjectMemory *om, size_t bytes)
: GarbageCollector(om)
, full(bytes * 2)
, eden(full.allocate(bytes), bytes)
, heap_a(full.allocate(bytes / 2), bytes / 2)
, heap_b(full.allocate(bytes / 2), bytes / 2)
, total_objects(0)
, copy_spills_(0)
, autotune_(false)
, tune_threshold_(0)
, original_lifetime_(1)
, lifetime_(1)
{
current = &heap_a;
next = &heap_b;
}
BakerGC::~BakerGC() { }
/**
* Called for each object in the young generation that is seen during garbage
* collection. An object is seen by scanning from the root objects to all
* reachable objects. Therefore, only reachable objects will be seen, and
* reachable objects may be seen more than once.
*
* @returns the new address for the object, so that the source reference can
* be updated when the object has been moved.
*/
Object* BakerGC::saw_object(Object* obj) {
Object* copy;
#ifdef ENABLE_OBJECT_WATCH
if(watched_p(obj)) {
std::cout << "detected " << obj << " during baker collection\n";
}
#endif
if(!obj->reference_p()) return obj;
if(!obj->young_object_p()) return obj;
if(obj->forwarded_p()) return obj->forward();
// This object is already in the next space, we don't want to
// copy it again!
if(next->contains_p(obj)) return obj;
if(unlikely(obj->inc_age() >= lifetime_)) {
copy = object_memory_->promote_object(obj);
promoted_push(copy);
} else if(likely(next->enough_space_p(
obj->size_in_bytes(object_memory_->state())))) {
copy = next->move_object(object_memory_->state(), obj);
total_objects++;
} else {
copy_spills_++;
copy = object_memory_->promote_object(obj);
promoted_push(copy);
}
#ifdef ENABLE_OBJECT_WATCH
if(watched_p(copy)) {
std::cout << "detected " << copy << " during baker collection (2)\n";
}
#endif
return copy;
}
/**
* Scans the remaining unscanned portion of the Next heap.
*/
void BakerGC::copy_unscanned() {
Object* iobj = next->next_unscanned(object_memory_->state());
while(iobj) {
assert(iobj->young_object_p());
if(!iobj->forwarded_p()) scan_object(iobj);
iobj = next->next_unscanned(object_memory_->state());
}
}
/**
* Returns true if the young generation has been fully scanned in the
* current collection.
*/
bool BakerGC::fully_scanned_p() {
// Note: The spaces are swapped at the start of collection, which is why we
// check the Next heap
return next->fully_scanned_p();
}
const static double cOverFullThreshold = 95.0;
const static int cOverFullTimes = 3;
const static size_t cMinimumLifetime = 1;
const static double cUnderFullThreshold = 20.0;
const static int cUnderFullTimes = -3;
const static size_t cMaximumLifetime = 6;
/**
* Perform garbage collection on the young objects.
*/
void BakerGC::collect(GCData& data, YoungCollectStats* stats) {
#ifdef HAVE_VALGRIND_H
(void)VALGRIND_MAKE_MEM_DEFINED(next->start().as_int(), next->size());
(void)VALGRIND_MAKE_MEM_DEFINED(current->start().as_int(), current->size());
#endif
mprotect(next->start(), next->size(), PROT_READ | PROT_WRITE);
mprotect(current->start(), current->size(), PROT_READ | PROT_WRITE);
Object* tmp;
ObjectArray *current_rs = object_memory_->swap_remember_set();
total_objects = 0;
copy_spills_ = 0;
reset_promoted();
// Start by copying objects in the remember set
for(ObjectArray::iterator oi = current_rs->begin();
oi != current_rs->end();
++oi) {
tmp = *oi;
// unremember_object throws a NULL in to remove an object
// so we don't have to compact the set in unremember
if(tmp) {
// assert(tmp->mature_object_p());
// assert(!tmp->forwarded_p());
// Remove the Remember bit, since we're clearing the set.
tmp->clear_remember();
scan_object(tmp);
}
}
delete current_rs;
for(std::list<gc::WriteBarrier*>::iterator wbi = object_memory_->aux_barriers().begin();
wbi != object_memory_->aux_barriers().end();
++wbi) {
gc::WriteBarrier* wb = *wbi;
ObjectArray* rs = wb->swap_remember_set();
for(ObjectArray::iterator oi = rs->begin();
oi != rs->end();
++oi) {
tmp = *oi;
if(tmp) {
tmp->clear_remember();
scan_object(tmp);
}
}
delete rs;
}
for(Roots::Iterator i(data.roots()); i.more(); i.advance()) {
i->set(saw_object(i->get()));
}
if(data.threads()) {
for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
i != data.threads()->end();
++i) {
scan(*i, true);
}
}
for(Allocator<capi::Handle>::Iterator i(data.handles()->allocator()); i.more(); i.advance()) {
if(!i->in_use_p()) continue;
if(!i->weak_p() && i->object()->young_object_p()) {
i->set_object(saw_object(i->object()));
// Users manipulate values accessible from the data* within an
// RData without running a write barrier. Thusly if we see a mature
// rdata, we must always scan it because it could contain
// young pointers.
} else if(!i->object()->young_object_p() && i->is_rdata()) {
scan_object(i->object());
}
assert(i->object()->type_id() > InvalidType && i->object()->type_id() < LastObjectType);
}
std::list<capi::GlobalHandle*>* gh = data.global_handle_locations();
if(gh) {
for(std::list<capi::GlobalHandle*>::iterator i = gh->begin();
i != gh->end();
++i) {
capi::GlobalHandle* global_handle = *i;
capi::Handle** loc = global_handle->handle();
if(capi::Handle* hdl = *loc) {
if(!REFERENCE_P(hdl)) continue;
if(hdl->valid_p()) {
Object* obj = hdl->object();
if(obj && obj->reference_p() && obj->young_object_p()) {
hdl->set_object(saw_object(obj));
}
} else {
std::cerr << "Detected bad handle checking global capi handles\n";
}
}
}
}
#ifdef ENABLE_LLVM
if(LLVMState* ls = data.llvm_state()) ls->gc_scan(this);
#endif
// Handle all promotions to non-young space that occurred.
handle_promotions();
assert(fully_scanned_p());
// We're now done seeing the entire object graph of normal, live references.
// Now we get to handle the unusual references, like finalizers and such.
// Check any weakrefs and replace dead objects with nil
// We need to do this before checking finalizers so people can't access
// objects kept alive for finalization through weakrefs.
clean_weakrefs(true);
// Objects with finalizers must be kept alive until the finalizers have
// run.
walk_finalizers();
// Process possible promotions from processing objects with finalizers.
handle_promotions();
if(!promoted_stack_.empty()) rubinius::bug("promote stack has elements!");
if(!fully_scanned_p()) rubinius::bug("more young refs");
// Remove unreachable locked objects still in the list
if(data.threads()) {
for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
i != data.threads()->end();
++i) {
clean_locked_objects(*i, true);
}
}
// Swap the 2 halves
Heap *x = next;
next = current;
current = x;
if(stats) {
stats->lifetime = lifetime_;
stats->percentage_used = current->percentage_used();
stats->promoted_objects = promoted_objects_;
stats->excess_objects = copy_spills_;
}
// Tune the age at which promotion occurs
if(autotune_) {
double used = current->percentage_used();
if(used > cOverFullThreshold) {
if(tune_threshold_ >= cOverFullTimes) {
if(lifetime_ > cMinimumLifetime) lifetime_--;
} else {
tune_threshold_++;
}
} else if(used < cUnderFullThreshold) {
if(tune_threshold_ <= cUnderFullTimes) {
if(lifetime_ < cMaximumLifetime) lifetime_++;
} else {
tune_threshold_--;
}
} else if(tune_threshold_ > 0) {
tune_threshold_--;
} else if(tune_threshold_ < 0) {
tune_threshold_++;
} else if(tune_threshold_ == 0) {
if(lifetime_ < original_lifetime_) {
lifetime_++;
} else if(lifetime_ > original_lifetime_) {
lifetime_--;
}
}
}
}
bool BakerGC::handle_promotions() {
if(promoted_stack_.empty() && fully_scanned_p()) return false;
while(!promoted_stack_.empty() || !fully_scanned_p()) {
while(!promoted_stack_.empty()) {
Object* obj = promoted_stack_.back();
promoted_stack_.pop_back();
scan_object(obj);
}
copy_unscanned();
}
return true;
}
void BakerGC::walk_finalizers() {
FinalizerHandler* fh = object_memory_->finalizer_handler();
if(!fh) return;
for(FinalizerHandler::iterator i = fh->begin();
!i.end();
/* advance is handled in the loop */)
{
FinalizeObject& fi = i.current();
bool live = true;
if(fi.object->young_object_p()) {
live = fi.object->forwarded_p();
fi.object = saw_object(fi.object);
}
Object *fin = fi.ruby_finalizer;
if(fin && fin->reference_p() && fin->young_object_p()) {
fi.ruby_finalizer = saw_object(fi.ruby_finalizer);
}
i.next(live);
}
}
bool BakerGC::in_current_p(Object* obj) {
return current->contains_p(obj);
}
ObjectPosition BakerGC::validate_object(Object* obj) {
if(current->contains_p(obj) || eden.contains_p(obj)) {
return cValid;
} else if(next->contains_p(obj)) {
return cInWrongYoungHalf;
} else {
return cUnknown;
}
}
}
<|endoftext|> |
<commit_before>/*
* This program uses PGAPack to do its GA stuff.
* ftp://ftp.mcs.anl.gov/pub/pgapack/pgapack.tar.Z
* I used this one instead of galib because it uses MPI
* to spread load around. It also seems like the API is a little
* cleaner.
*/
#include <pgapack.h>
#include "tmp/scores.h"
#include "tmp/tests.h"
double evaluate(PGAContext *, int, int);
int myMutation(PGAContext *, int, int, double);
int GetIntegerParameter(char *query);
void WriteString(PGAContext *ctx, FILE *fp, int p, int pop);
void showSummary(PGAContext *ctx);
const double threshold = 5.0;
const double nybias = 10.0;
const int exhaustive_eval = 1;
const double mutation_rate = 0.2;
const double mutation_noise = 1.0;
const double regression_coefficient = 0.5;
const double crossover_rate = 0.0;
const int pop_size = 100;
const int replace_num = 25;
const int maxiter = 10000;
void init_data()
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
loadtests();
loadscores();
}
MPI_Bcast(num_tests_hit, num_tests, MPI_CHAR, 0, MPI_COMM_WORLD);
MPI_Bcast(is_spam, num_tests, MPI_CHAR, 0, MPI_COMM_WORLD);
MPI_Bcast(tests_hit, num_tests*max_hits_per_msg, MPI_SHORT, 0, MPI_COMM_WORLD);
}
int main(int argc, char **argv) {
PGAContext *ctx;
MPI_Init(&argc, &argv);
init_data();
ctx = PGACreate(&argc, argv, PGA_DATATYPE_REAL, num_scores, PGA_MINIMIZE);
PGASetUserFunction(ctx, PGA_USERFUNCTION_PRINTSTRING, (void *)WriteString);
PGASetUserFunction(ctx, PGA_USERFUNCTION_ENDOFGEN, (void *)showSummary);
PGASetRealInitRange(ctx, range_lo, range_hi);
PGASetPopSize(ctx, pop_size);
PGASetNumReplaceValue(ctx, replace_num);
PGASetMutationOrCrossoverFlag(ctx, PGA_TRUE);
PGASetMutationBoundedFlag(ctx, PGA_FALSE);
PGASetUserFunction(ctx, PGA_USERFUNCTION_MUTATION, (void *)myMutation);
PGASetCrossoverType(ctx, PGA_CROSSOVER_ONEPT);
PGASetCrossoverProb(ctx, crossover_rate);
PGASetPrintFrequencyValue(ctx,300);
PGASetPrintOptions(ctx, PGA_REPORT_AVERAGE);
PGASetStoppingRuleType(ctx, PGA_STOP_NOCHANGE);
PGASetMaxNoChangeValue(ctx, 300);
PGASetMaxGAIterValue(ctx, maxiter);
PGASetUp(ctx);
// Now fix the alleles for the imutable tests
/*
for(int i=0; i<num_scores; i++)
{
for(int p=0; p<pop_size; p++)
{
PGASetRealAllele(ctx, p, PGA_NEWPOP, i, bestscores[i]);
}
}
*/
PGARun(ctx, evaluate);
PGADestroy(ctx);
MPI_Finalize();
return(0);
}
int ga_yy,ga_yn,ga_ny,ga_nn;
double ynscore,nyscore,yyscore,nnscore;
inline double score_msg(PGAContext *ctx, int p, int pop, int i)
{
double msg_score = 0.0;
// For every test the message hit on
for(int j=num_tests_hit[i]-1; j>=0; j--)
{
// Up the message score by the allele for this test in the genome
msg_score += PGAGetRealAllele(ctx, p, pop, tests_hit[i][j]);
}
// Ok, now we know the score for this message. Let's see how this genome did...
if(is_spam[i])
{
if(msg_score > threshold)
{
// Good positive
ga_yy++;
yyscore += msg_score;
}
else
{
// False negative
ga_yn++;
ynscore += threshold - msg_score;
}
}
else
{
if(msg_score > threshold)
{
// False positive
ga_ny++;
nyscore += msg_score - threshold;
}
else
{
// Good negative
ga_nn++;
nnscore += msg_score;
}
}
return msg_score;
}
double evaluate(PGAContext *ctx, int p, int pop)
{
double tot_score = 0.0;
yyscore = ynscore = nyscore = nnscore = 0.0;
ga_yy=ga_yn=ga_ny=ga_nn=0;
// For every message
for (int i=num_tests-1; i>=0; i--)
{
tot_score += score_msg(ctx,p,pop,i);
}
// yyscore = log(yyscore);
// ynscore = log(ynscore);
// nyscore = log(nyscore);
// nnscore = log(nnscore);
return (double) ((double)ga_yn)+ynscore + (((double)ga_ny)+nyscore)*nybias + (ynscore-nnscore)/1000.0;
}
/*
* This mutation function tosses a weighted coin for each allele. If the allele is to be mutated,
* then the way it's mutated is to regress it toward the mean of the population for that allele,
* then add a little gaussian noise.
*/
int myMutation(PGAContext *ctx, int p, int pop, double mr) {
int count=0;
for (int i=0; i<num_scores; i++)
{
if(is_mutatable[i] && PGARandomFlip(ctx, mr))
{
double gene_sum=0.0;
// Find the mean
for(int j=0; j<pop_size; j++) { if(p!=j) gene_sum += PGAGetRealAllele(ctx, j, pop, i); }
gene_sum /= (double)(pop_size-1);
// Regress towards it...
gene_sum = (1.0-regression_coefficient)*gene_sum+regression_coefficient*PGAGetRealAllele(ctx, p, pop, i);
// Set this gene in this allele to be the average, plus some gaussian noise
PGASetRealAllele(ctx, p, pop, i, PGARandomGaussian(ctx, gene_sum, mutation_noise));
count++;
}
}
return count;
}
void dump()
{
printf ("\n# SUMMARY: %6d / %6d\n#\n", ga_ny, ga_yn);
printf ("# Correctly non-spam: %6d %3.2f%% (%3.2f%% overall)\n", ga_nn, (ga_nn / (float) num_nonspam) * 100.0, (ga_nn / (float) num_tests) * 100.0);
printf ("# Correctly spam: %6d %3.2f%% (%3.2f%% overall)\n", ga_yy, (ga_yy / (float) num_spam) * 100.0, (ga_yy / (float) num_tests) * 100.0);
printf ("# False positives: %6d %3.2f%% (%3.2f%% overall, %6.0f adjusted)\n", ga_ny, (ga_ny / (float) num_nonspam) * 100.0, (ga_ny / (float) num_tests) * 100.0, nyscore*nybias);
printf ("# False negatives: %6d %3.2f%% (%3.2f%% overall, %6.0f adjusted)\n", ga_yn, (ga_yn / (float) num_spam) * 100.0, (ga_yn / (float) num_tests) * 100.0, ynscore);
printf ("# TOTAL: %6d %3.2f%%\n#\n", num_tests, 100.0);
}
/*****************************************************************************
* WriteString sends a visual representation of the chromosome out to fp *
*****************************************************************************/
void WriteString(PGAContext *ctx, FILE *fp, int p, int pop)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(0 == rank)
{
evaluate(ctx,p,pop);
dump();
for(int i=0; i<num_scores; i++)
{
fprintf(fp,"score %-30s %2.1f\n",score_names[i],PGAGetRealAllele(ctx, p, pop, i));
}
fprintf ( fp,"\n" );
}
}
void showSummary(PGAContext *ctx)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(0 == rank)
{
if(0 == PGAGetGAIterValue(ctx) % 300)
{
int genome = PGAGetBestIndex(ctx,PGA_OLDPOP);
PGAGetEvaluation(ctx, genome, PGA_OLDPOP);
dump();
}
else if(0 == PGAGetGAIterValue(ctx) % 5)
{
printf(".");
}
}
}
<commit_msg>Scoring alg changes<commit_after>/*
* This program uses PGAPack to do its GA stuff.
* ftp://ftp.mcs.anl.gov/pub/pgapack/pgapack.tar.Z
* I used this one instead of galib because it uses MPI
* to spread load around. It also seems like the API is a little
* cleaner.
*/
#include <pgapack.h>
#include "tmp/scores.h"
#include "tmp/tests.h"
double evaluate(PGAContext *, int, int);
int myMutation(PGAContext *, int, int, double);
int GetIntegerParameter(char *query);
void WriteString(PGAContext *ctx, FILE *fp, int p, int pop);
void showSummary(PGAContext *ctx);
const double threshold = 5.0;
const double nybias = 10.0;
const int exhaustive_eval = 1;
const double mutation_rate = 0.2;
const double mutation_noise = 2.0;
const double regression_coefficient = 0.5;
const double crossover_rate = 0.0;
const int pop_size = 2000;
const int replace_num = 500;
const int maxiter = 10000;
void init_data()
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
loadtests();
loadscores();
}
MPI_Bcast(num_tests_hit, num_tests, MPI_CHAR, 0, MPI_COMM_WORLD);
MPI_Bcast(is_spam, num_tests, MPI_CHAR, 0, MPI_COMM_WORLD);
MPI_Bcast(tests_hit, num_tests*max_hits_per_msg, MPI_SHORT, 0, MPI_COMM_WORLD);
}
int main(int argc, char **argv) {
PGAContext *ctx;
MPI_Init(&argc, &argv);
init_data();
ctx = PGACreate(&argc, argv, PGA_DATATYPE_REAL, num_scores, PGA_MINIMIZE);
PGASetUserFunction(ctx, PGA_USERFUNCTION_PRINTSTRING, (void *)WriteString);
PGASetUserFunction(ctx, PGA_USERFUNCTION_ENDOFGEN, (void *)showSummary);
PGASetRealInitRange(ctx, range_lo, range_hi);
PGASetPopSize(ctx, pop_size);
PGASetNumReplaceValue(ctx, replace_num);
PGASetMutationOrCrossoverFlag(ctx, PGA_TRUE);
PGASetMutationBoundedFlag(ctx, PGA_FALSE);
PGASetUserFunction(ctx, PGA_USERFUNCTION_MUTATION, (void *)myMutation);
PGASetCrossoverType(ctx, PGA_CROSSOVER_ONEPT);
PGASetCrossoverProb(ctx, crossover_rate);
PGASetPrintFrequencyValue(ctx,300);
PGASetPrintOptions(ctx, PGA_REPORT_AVERAGE);
PGASetStoppingRuleType(ctx, PGA_STOP_NOCHANGE);
PGASetMaxNoChangeValue(ctx, 300);
PGASetMaxGAIterValue(ctx, maxiter);
PGASetUp(ctx);
// Now fix the alleles for the imutable tests
/*
for(int i=0; i<num_scores; i++)
{
for(int p=0; p<pop_size; p++)
{
PGASetRealAllele(ctx, p, PGA_NEWPOP, i, bestscores[i]);
}
}
*/
PGARun(ctx, evaluate);
PGADestroy(ctx);
MPI_Finalize();
return(0);
}
int ga_yy,ga_yn,ga_ny,ga_nn;
double ynscore,nyscore,yyscore,nnscore;
inline double score_msg(PGAContext *ctx, int p, int pop, int i)
{
double msg_score = 0.0;
// For every test the message hit on
for(int j=num_tests_hit[i]-1; j>=0; j--)
{
// Up the message score by the allele for this test in the genome
msg_score += PGAGetRealAllele(ctx, p, pop, tests_hit[i][j]);
}
// Ok, now we know the score for this message. Let's see how this genome did...
if(is_spam[i])
{
if(msg_score >= threshold)
{
// Good positive
ga_yy++;
yyscore += msg_score; // Each true positive means yyscore += at least 5
}
else
{
// False negative
ga_yn++;
ynscore += msg_score; // Each false negative means that ynscore += less than 5
}
}
else
{
if(msg_score >= threshold)
{
// False positive
ga_ny++;
nyscore += msg_score; // Each false positive means nyscore += more than 0
}
else
{
// Good negative
ga_nn++;
nnscore += msg_score; // Each good negative means nnscore += less than 5
}
}
return msg_score;
}
double evaluate(PGAContext *ctx, int p, int pop)
{
double tot_score = 0.0;
yyscore = ynscore = nyscore = nnscore = 0.0;
ga_yy=ga_yn=ga_ny=ga_nn=0;
// For every message
for (int i=num_tests-1; i>=0; i--)
{
tot_score += score_msg(ctx,p,pop,i);
}
// yyscore = log(yyscore);
// ynscore = log(ynscore);
// nyscore = log(nyscore);
// nnscore = log(nnscore);
return (double) ((double)ga_yn + (double)ga_ny*nybias) + (ynscore + nyscore*nybias - (ynscore+nnscore))/tot_score;
}
/*
* This mutation function tosses a weighted coin for each allele. If the allele is to be mutated,
* then the way it's mutated is to regress it toward the mean of the population for that allele,
* then add a little gaussian noise.
*/
int myMutation(PGAContext *ctx, int p, int pop, double mr) {
int count=0;
for (int i=0; i<num_scores; i++)
{
if(is_mutatable[i] && PGARandomFlip(ctx, mr))
{
double gene_sum=0.0;
// Find the mean
for(int j=0; j<pop_size; j++) { if(p!=j) gene_sum += PGAGetRealAllele(ctx, j, pop, i); }
gene_sum /= (double)(pop_size-1);
// Regress towards it...
gene_sum = (1.0-regression_coefficient)*gene_sum+regression_coefficient*PGAGetRealAllele(ctx, p, pop, i);
// Set this gene in this allele to be the average, plus some gaussian noise
PGASetRealAllele(ctx, p, pop, i, PGARandomGaussian(ctx, gene_sum, mutation_noise));
count++;
}
}
return count;
}
void dump()
{
printf ("\n# SUMMARY: %6d / %6d\n#\n", ga_ny, ga_yn);
printf ("# Correctly non-spam: %6d %3.2f%% (%3.2f%% overall)\n", ga_nn, (ga_nn / (float) num_nonspam) * 100.0, (ga_nn / (float) num_tests) * 100.0);
printf ("# Correctly spam: %6d %3.2f%% (%3.2f%% overall)\n", ga_yy, (ga_yy / (float) num_spam) * 100.0, (ga_yy / (float) num_tests) * 100.0);
printf ("# False positives: %6d %3.2f%% (%3.2f%% overall, %6.0f adjusted)\n", ga_ny, (ga_ny / (float) num_nonspam) * 100.0, (ga_ny / (float) num_tests) * 100.0, nyscore*nybias);
printf ("# False negatives: %6d %3.2f%% (%3.2f%% overall, %6.0f adjusted)\n", ga_yn, (ga_yn / (float) num_spam) * 100.0, (ga_yn / (float) num_tests) * 100.0, ynscore);
printf ("# Average score for spam: %3.1f nonspam: %3.1f\n",(ynscore+yyscore)/((double)(ga_yn+ga_yy)),(nyscore+nnscore)/((double)(ga_nn+ga_ny)));
printf ("# TOTAL: %6d %3.2f%%\n#\n", num_tests, 100.0);
}
/*****************************************************************************
* WriteString sends a visual representation of the chromosome out to fp *
*****************************************************************************/
void WriteString(PGAContext *ctx, FILE *fp, int p, int pop)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(0 == rank)
{
evaluate(ctx,p,pop);
dump();
for(int i=0; i<num_scores; i++)
{
fprintf(fp,"score %-30s %2.3f\n",score_names[i],PGAGetRealAllele(ctx, p, pop, i));
}
fprintf ( fp,"\n" );
}
}
void showSummary(PGAContext *ctx)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(0 == rank)
{
if(0 == PGAGetGAIterValue(ctx) % 300)
{
int genome = PGAGetBestIndex(ctx,PGA_OLDPOP);
PGAGetEvaluation(ctx, genome, PGA_OLDPOP);
dump();
}
else if(0 == PGAGetGAIterValue(ctx) % 5)
{
printf(".");
}
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include "xbyak/xbyak.h"
#define NUM_OF_ARRAY(x) (sizeof(x) / sizeof(x[0]))
using namespace Xbyak;
struct TestJmp : public CodeGenerator {
void putNop(int n)
{
for (int i = 0; i < n; i++) {
nop();
}
}
/*
4 X0:
5 00000004 EBFE jmp short X0
6
7 X1:
8 00000006 <res 00000001> dummyX1 resb 1
9 00000007 EBFD jmp short X1
10
11 X126:
12 00000009 <res 0000007E> dummyX126 resb 126
13 00000087 EB80 jmp short X126
14
15 X127:
16 00000089 <res 0000007F> dummyX127 resb 127
17 00000108 E97CFFFFFF jmp near X127
18
19 0000010D EB00 jmp short Y0
20 Y0:
21
22 0000010F EB01 jmp short Y1
23 00000111 <res 00000001> dummyY1 resb 1
24 Y1:
25
26 00000112 EB7F jmp short Y127
27 00000114 <res 0000007F> dummyY127 resb 127
28 Y127:
29
30 00000193 E980000000 jmp near Y128
31 00000198 <res 00000080> dummyY128 resb 128
32 Y128:
*/
TestJmp(int offset, bool isBack, bool isShort)
{
char buf[32];
static int count = 0;
if (isBack) {
sprintf(buf, "L(\"X%d\");\n", count);
L(buf);
putNop(offset);
jmp(buf);
} else {
sprintf(buf, "L(\"Y%d\");\n", count);
if (isShort) {
jmp(buf);
} else {
jmp(buf, T_NEAR);
}
putNop(offset);
L(buf);
}
count++;
}
};
void test1()
{
static const struct Tbl {
int offset;
bool isBack;
bool isShort;
const char *result;
} tbl[] = {
{ 0, true, true, "EBFE" },
{ 1, true, true, "EBFD" },
{ 126, true, true, "EB80" },
{ 127, true, false, "E97CFFFFFF" },
{ 0, false, true, "EB00" },
{ 1, false, true, "EB01" },
{ 127, false, true, "EB7F" },
{ 128, false, false, "E980000000" },
};
for (size_t i = 0; i < NUM_OF_ARRAY(tbl); i++) {
const Tbl *p = &tbl[i];
TestJmp jmp(p->offset, p->isBack, p->isShort);
const uint8 *q = (const uint8*)jmp.getCode();
char buf[32];
if (p->isBack) q += p->offset; /* skip nop */
for (size_t j = 0; j < jmp.getSize() - p->offset; j++) {
sprintf(&buf[j * 2], "%02X", q[j]);
}
if (strcmp(buf, p->result) != 0) {
printf("error %d assume:%s, err=%s\n", i, p->result, buf);
} else {
printf("ok %d\n", i);
}
}
}
int add5(int x) { return x + 5; }
int add2(int x) { return x + 2; }
struct Grow : Xbyak::CodeGenerator {
Grow(int dummySize)
: Xbyak::CodeGenerator(128, Xbyak::AutoGrow)
{
mov(eax, 100);
push(eax);
call(add5);
add(esp, 4);
push(eax);
call(add2);
add(esp, 4);
ret();
for (int i = 0; i < dummySize; i++) {
db(0);
}
}
};
void test2()
{
for (int dummySize = 0; dummySize < 40000; dummySize += 10000) {
printf("dummySize=%d\n", dummySize);
Grow g(dummySize);
g.ready();
int (*f)() = (int (*)())g.getCode();
int x = f();
const int ok = 107;
if (x != ok) {
printf("err %d assume %d\n", x, ok);
} else {
printf("ok\n");
}
}
}
int main()
{
try {
test1();
test2();
} catch (Xbyak::Error err) {
printf("ERR:%s(%d)\n", Xbyak::ConvertErrorToString(err), err);
} catch (...) {
printf("unknown error\n");
}
}
<commit_msg>distinguish label<commit_after>#include <stdio.h>
#include <string.h>
#include "xbyak/xbyak.h"
#define NUM_OF_ARRAY(x) (sizeof(x) / sizeof(x[0]))
using namespace Xbyak;
struct TestJmp : public CodeGenerator {
void putNop(int n)
{
for (int i = 0; i < n; i++) {
nop();
}
}
/*
4 X0:
5 00000004 EBFE jmp short X0
6
7 X1:
8 00000006 <res 00000001> dummyX1 resb 1
9 00000007 EBFD jmp short X1
10
11 X126:
12 00000009 <res 0000007E> dummyX126 resb 126
13 00000087 EB80 jmp short X126
14
15 X127:
16 00000089 <res 0000007F> dummyX127 resb 127
17 00000108 E97CFFFFFF jmp near X127
18
19 0000010D EB00 jmp short Y0
20 Y0:
21
22 0000010F EB01 jmp short Y1
23 00000111 <res 00000001> dummyY1 resb 1
24 Y1:
25
26 00000112 EB7F jmp short Y127
27 00000114 <res 0000007F> dummyY127 resb 127
28 Y127:
29
30 00000193 E980000000 jmp near Y128
31 00000198 <res 00000080> dummyY128 resb 128
32 Y128:
*/
TestJmp(int offset, bool isBack, bool isShort)
{
char buf[32];
static int count = 0;
if (isBack) {
sprintf(buf, "L(\"X%d\");\n", count);
L(buf);
putNop(offset);
jmp(buf);
} else {
sprintf(buf, "L(\"Y%d\");\n", count);
if (isShort) {
jmp(buf);
} else {
jmp(buf, T_NEAR);
}
putNop(offset);
L(buf);
}
count++;
}
};
void test1()
{
static const struct Tbl {
int offset;
bool isBack;
bool isShort;
const char *result;
} tbl[] = {
{ 0, true, true, "EBFE" },
{ 1, true, true, "EBFD" },
{ 126, true, true, "EB80" },
{ 127, true, false, "E97CFFFFFF" },
{ 0, false, true, "EB00" },
{ 1, false, true, "EB01" },
{ 127, false, true, "EB7F" },
{ 128, false, false, "E980000000" },
};
for (size_t i = 0; i < NUM_OF_ARRAY(tbl); i++) {
const Tbl *p = &tbl[i];
TestJmp jmp(p->offset, p->isBack, p->isShort);
const uint8 *q = (const uint8*)jmp.getCode();
char buf[32];
if (p->isBack) q += p->offset; /* skip nop */
for (size_t j = 0; j < jmp.getSize() - p->offset; j++) {
sprintf(&buf[j * 2], "%02X", q[j]);
}
if (strcmp(buf, p->result) != 0) {
printf("error %d assume:%s, err=%s\n", i, p->result, buf);
} else {
printf("ok %d\n", i);
}
}
}
int add5(int x) { return x + 5; }
int add2(int x) { return x + 2; }
struct Grow : Xbyak::CodeGenerator {
Grow(int dummySize)
: Xbyak::CodeGenerator(128, Xbyak::AutoGrow)
{
mov(eax, 100);
push(eax);
call((void*)add5);
add(esp, 4);
push(eax);
call((void*)add2);
add(esp, 4);
ret();
for (int i = 0; i < dummySize; i++) {
db(0);
}
}
};
void test2()
{
for (int dummySize = 0; dummySize < 40000; dummySize += 10000) {
printf("dummySize=%d\n", dummySize);
Grow g(dummySize);
g.ready();
int (*f)() = (int (*)())g.getCode();
int x = f();
const int ok = 107;
if (x != ok) {
printf("err %d assume %d\n", x, ok);
} else {
printf("ok\n");
}
}
}
int main()
{
try {
test1();
test2();
} catch (Xbyak::Error err) {
printf("ERR:%s(%d)\n", Xbyak::ConvertErrorToString(err), err);
} catch (...) {
printf("unknown error\n");
}
}
<|endoftext|> |
<commit_before>/**
* @file SquareMatrix.hpp
*
* A square matrix
*
* @author James Goppert <james.goppert@gmail.com>
*/
#pragma once
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Matrix.hpp"
namespace matrix
{
template <typename Type, size_t M, size_t N>
class Matrix;
template<typename Type, size_t M>
class SquareMatrix : public Matrix<Type, M, M>
{
public:
SquareMatrix() :
Matrix<Type, M, M>()
{
}
SquareMatrix(const Type *data_) :
Matrix<Type, M, M>(data_)
{
}
SquareMatrix(const Matrix<Type, M, M> &other) :
Matrix<Type, M, M>(other)
{
}
/**
* inverse based on LU factorization with partial pivotting
*/
SquareMatrix <Type, M> inverse() const
{
SquareMatrix<Type, M> L;
L.setIdentity();
const SquareMatrix<Type, M> &A = (*this);
SquareMatrix<Type, M> U = A;
SquareMatrix<Type, M> P;
P.setIdentity();
//printf("A:\n"); A.print();
// for all diagonal elements
for (size_t n = 0; n < M; n++) {
// if diagonal is zero, swap with row below
if (fabsf(U(n, n)) < 1e-8f) {
//printf("trying pivot for row %d\n",n);
for (size_t i = 0; i < M; i++) {
if (i == n) {
continue;
}
//printf("\ttrying row %d\n",i);
if (fabsf(U(i, n)) > 1e-8f) {
//printf("swapped %d\n",i);
U.swapRows(i, n);
P.swapRows(i, n);
}
}
}
#ifdef MATRIX_ASSERT
//printf("A:\n"); A.print();
//printf("U:\n"); U.print();
//printf("P:\n"); P.print();
//fflush(stdout);
ASSERT(fabsf(U(n, n)) > 1e-8f);
#endif
// failsafe, return zero matrix
if (fabsf(U(n, n)) < 1e-8f) {
SquareMatrix<Type, M> zero;
zero.setZero();
return zero;
}
// for all rows below diagonal
for (size_t i = (n + 1); i < M; i++) {
L(i, n) = U(i, n) / U(n, n);
// add i-th row and n-th row
// multiplied by: -a(i,n)/a(n,n)
for (size_t k = n; k < M; k++) {
U(i, k) -= L(i, n) * U(n, k);
}
}
}
//printf("L:\n"); L.print();
//printf("U:\n"); U.print();
// solve LY=P*I for Y by forward subst
SquareMatrix<Type, M> Y = P;
// for all columns of Y
for (size_t c = 0; c < M; c++) {
// for all rows of L
for (size_t i = 0; i < M; i++) {
// for all columns of L
for (size_t j = 0; j < i; j++) {
// for all existing y
// subtract the component they
// contribute to the solution
Y(i, c) -= L(i, j) * Y(j, c);
}
// divide by the factor
// on current
// term to be solved
// Y(i,c) /= L(i,i);
// but L(i,i) = 1.0
}
}
//printf("Y:\n"); Y.print();
// solve Ux=y for x by back subst
SquareMatrix<Type, M> X = Y;
// for all columns of X
for (size_t c = 0; c < M; c++) {
// for all rows of U
for (size_t k = 0; k < M; k++) {
// have to go in reverse order
size_t i = M - 1 - k;
// for all columns of U
for (size_t j = i + 1; j < M; j++) {
// for all existing x
// subtract the component they
// contribute to the solution
X(i, c) -= U(i, j) * X(j, c);
}
// divide by the factor
// on current
// term to be solved
X(i, c) /= U(i, i);
}
}
//printf("X:\n"); X.print();
return X;
}
// inverse alias
inline SquareMatrix<Type, M> I() const
{
return inverse();
}
Vector<Type, M> diagonal() const
{
Vector<Type, M> res;
const SquareMatrix<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i, i);
}
return res;
}
SquareMatrix<Type, M> expm(Type dt, size_t n) const
{
SquareMatrix<Type, M> res;
res.setIdentity();
SquareMatrix<Type, M> A_pow = *this;
size_t k_fact = 1;
size_t k = 1;
while (k < n) {
res += A_pow * (Type(pow(dt, k)) / k_fact);
if (k == n) {
break;
}
A_pow *= A_pow;
k_fact *= k;
k++;
}
return res;
}
};
typedef SquareMatrix<float, 3> SquareMatrix3f;
template<typename Type, size_t M>
SquareMatrix<Type, M> eye() {
SquareMatrix<Type, M> m;
m.setIdentity();
return m;
}
template<typename Type, size_t M>
SquareMatrix<Type, M> diag(Vector<Type, M> d) {
SquareMatrix<Type, M> m;
for (size_t i=0; i<M; i++) {
m(i,i) = d(i);
}
return m;
}
}; // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<commit_msg>Travis fix.<commit_after>/**
* @file SquareMatrix.hpp
*
* A square matrix
*
* @author James Goppert <james.goppert@gmail.com>
*/
#pragma once
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Matrix.hpp"
namespace matrix
{
template <typename Type, size_t M, size_t N>
class Matrix;
template<typename Type, size_t M>
class SquareMatrix : public Matrix<Type, M, M>
{
public:
SquareMatrix() :
Matrix<Type, M, M>()
{
}
SquareMatrix(const Type *data_) :
Matrix<Type, M, M>(data_)
{
}
SquareMatrix(const Matrix<Type, M, M> &other) :
Matrix<Type, M, M>(other)
{
}
/**
* inverse based on LU factorization with partial pivotting
*/
SquareMatrix <Type, M> inverse() const
{
SquareMatrix<Type, M> L;
L.setIdentity();
const SquareMatrix<Type, M> &A = (*this);
SquareMatrix<Type, M> U = A;
SquareMatrix<Type, M> P;
P.setIdentity();
//printf("A:\n"); A.print();
// for all diagonal elements
for (size_t n = 0; n < M; n++) {
// if diagonal is zero, swap with row below
if (fabsf(U(n, n)) < 1e-8f) {
//printf("trying pivot for row %d\n",n);
for (size_t i = 0; i < M; i++) {
if (i == n) {
continue;
}
//printf("\ttrying row %d\n",i);
if (fabsf(U(i, n)) > 1e-8f) {
//printf("swapped %d\n",i);
U.swapRows(i, n);
P.swapRows(i, n);
}
}
}
#ifdef MATRIX_ASSERT
//printf("A:\n"); A.print();
//printf("U:\n"); U.print();
//printf("P:\n"); P.print();
//fflush(stdout);
ASSERT(fabsf(U(n, n)) > 1e-8f);
#endif
// failsafe, return zero matrix
if (fabsf(U(n, n)) < 1e-8f) {
SquareMatrix<Type, M> zero;
zero.setZero();
return zero;
}
// for all rows below diagonal
for (size_t i = (n + 1); i < M; i++) {
L(i, n) = U(i, n) / U(n, n);
// add i-th row and n-th row
// multiplied by: -a(i,n)/a(n,n)
for (size_t k = n; k < M; k++) {
U(i, k) -= L(i, n) * U(n, k);
}
}
}
//printf("L:\n"); L.print();
//printf("U:\n"); U.print();
// solve LY=P*I for Y by forward subst
SquareMatrix<Type, M> Y = P;
// for all columns of Y
for (size_t c = 0; c < M; c++) {
// for all rows of L
for (size_t i = 0; i < M; i++) {
// for all columns of L
for (size_t j = 0; j < i; j++) {
// for all existing y
// subtract the component they
// contribute to the solution
Y(i, c) -= L(i, j) * Y(j, c);
}
// divide by the factor
// on current
// term to be solved
// Y(i,c) /= L(i,i);
// but L(i,i) = 1.0
}
}
//printf("Y:\n"); Y.print();
// solve Ux=y for x by back subst
SquareMatrix<Type, M> X = Y;
// for all columns of X
for (size_t c = 0; c < M; c++) {
// for all rows of U
for (size_t k = 0; k < M; k++) {
// have to go in reverse order
size_t i = M - 1 - k;
// for all columns of U
for (size_t j = i + 1; j < M; j++) {
// for all existing x
// subtract the component they
// contribute to the solution
X(i, c) -= U(i, j) * X(j, c);
}
// divide by the factor
// on current
// term to be solved
X(i, c) /= U(i, i);
}
}
//printf("X:\n"); X.print();
return X;
}
// inverse alias
inline SquareMatrix<Type, M> I() const
{
return inverse();
}
Vector<Type, M> diagonal() const
{
Vector<Type, M> res;
const SquareMatrix<Type, M> &self = *this;
for (size_t i = 0; i < M; i++) {
res(i) = self(i, i);
}
return res;
}
SquareMatrix<Type, M> expm(Type dt, size_t n) const
{
SquareMatrix<Type, M> res;
res.setIdentity();
SquareMatrix<Type, M> A_pow = *this;
size_t k_fact = 1;
size_t k = 1;
while (k < n) {
res += A_pow * (Type(pow(dt, k)) / Type(k_fact));
if (k == n) {
break;
}
A_pow *= A_pow;
k_fact *= k;
k++;
}
return res;
}
};
typedef SquareMatrix<float, 3> SquareMatrix3f;
template<typename Type, size_t M>
SquareMatrix<Type, M> eye() {
SquareMatrix<Type, M> m;
m.setIdentity();
return m;
}
template<typename Type, size_t M>
SquareMatrix<Type, M> diag(Vector<Type, M> d) {
SquareMatrix<Type, M> m;
for (size_t i=0; i<M; i++) {
m(i,i) = d(i);
}
return m;
}
}; // namespace matrix
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<|endoftext|> |
<commit_before>#include <Bull/Graphics/Light/AbstractLight.hpp>
namespace Bull
{
String AbstractLight::compose(const String& base, const String& member)
{
return base + "." + member;
}
LightType AbstractLight::getType() const
{
return m_type;
}
void AbstractLight::setAmbientFactor(float ambient)
{
m_ambient = ambient;
}
float AbstractLight::getAmbientFactor() const
{
return m_ambient;
}
void AbstractLight::setDiffuseFactor(float diffuse)
{
m_diffuse = diffuse;
}
float AbstractLight::getDiffuseFactor() const
{
return m_diffuse;
}
void AbstractLight::setColor(const Color& color)
{
m_color = color;
}
const Color& AbstractLight::getColor() const
{
return m_color;
}
AbstractLight::AbstractLight(LightType type) :
m_type(type)
{
setDiffuseFactor(1.f);
setAmbientFactor(0.2f);
}
void AbstractLight::setUniforms(Shader& shader, const String& name) const
{
if(shader.isLinked())
{
shader.setUniformVector(compose(name, "ambient"), Vector4F::makeFromColor(m_color) * m_ambient);
shader.setUniformVector(compose(name, "diffuse"), Vector4F::makeFromColor(m_color) * m_diffuse);
shader.setUniformVector(compose(name, "specular"), Vector4F::makeFromColor(m_color));
}
}
}<commit_msg>[Graphics/AbstractLight] Don't check if the shader is linked<commit_after>#include <Bull/Graphics/Light/AbstractLight.hpp>
namespace Bull
{
String AbstractLight::compose(const String& base, const String& member)
{
return base + "." + member;
}
LightType AbstractLight::getType() const
{
return m_type;
}
void AbstractLight::setAmbientFactor(float ambient)
{
m_ambient = ambient;
}
float AbstractLight::getAmbientFactor() const
{
return m_ambient;
}
void AbstractLight::setDiffuseFactor(float diffuse)
{
m_diffuse = diffuse;
}
float AbstractLight::getDiffuseFactor() const
{
return m_diffuse;
}
void AbstractLight::setColor(const Color& color)
{
m_color = color;
}
const Color& AbstractLight::getColor() const
{
return m_color;
}
AbstractLight::AbstractLight(LightType type) :
m_type(type)
{
setDiffuseFactor(1.f);
setAmbientFactor(0.2f);
}
void AbstractLight::setUniforms(Shader& shader, const String& name) const
{
shader.setUniformVector(compose(name, "ambient"), Vector4F::makeFromColor(m_color) * m_ambient);
shader.setUniformVector(compose(name, "diffuse"), Vector4F::makeFromColor(m_color) * m_diffuse);
shader.setUniformVector(compose(name, "specular"), Vector4F::makeFromColor(m_color));
}
}<|endoftext|> |
<commit_before>// @(#)root/meta:$
// Author: Axel Naumann 2014-05-02
/*************************************************************************
* Copyright (C) 1995-2014, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Persistent version of a TClass. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TProtoClass.h"
#include "TBaseClass.h"
#include "TClass.h"
#include "TDataMember.h"
#include "TEnum.h"
#include "TInterpreter.h"
#include "TList.h"
#include "TListOfDataMembers.h"
#include "TListOfEnums.h"
#include "TRealData.h"
//______________________________________________________________________________
TProtoClass::TProtoClass(TClass* cl):
TNamed(*cl), fBase(cl->GetListOfBases()), fData(cl->GetListOfDataMembers()),
fEnums(cl->GetListOfEnums()), fSizeof(cl->Size()), fCanSplit(cl->fCanSplit),
fStreamerType(cl->fStreamerType), fProperty(cl->fProperty),
fClassProperty(cl->fClassProperty)
{
// Initialize a TProtoClass from a TClass.
if (cl->Property() & kIsNamespace){
fData=new TListOfDataMembers();
fEnums=nullptr;
fPRealData=nullptr;
fOffsetStreamer=0;
return;
}
fPRealData = new TList();
if (!cl->GetCollectionProxy()) {
// Build the list of RealData before we access it:
cl->BuildRealData(0, true /*isTransient*/);
// The data members are ordered as follows:
// - this class's data members,
// - foreach base: base class's data members.
// fPRealData encodes all TProtoRealData objects with a
// TObjString to signal a new class.
TClass* clCurrent = cl;
TRealData* precRd = nullptr;
for (auto realDataObj: *cl->GetListOfRealData()) {
TRealData *rd = (TRealData*)realDataObj;
if (!precRd) precRd = rd;
TClass* clRD = rd->GetDataMember()->GetClass();
if (clRD != clCurrent) {
clCurrent = clRD;
TObjString *clstr = new TObjString(clRD->GetName());
if (precRd->TestBit(TRealData::kTransient)) {
clstr->SetBit(TRealData::kTransient);
}
fPRealData->AddLast(clstr);
precRd = rd;
}
fPRealData->AddLast(new TProtoRealData(rd));
}
if (gDebug > 2) {
for (auto dataPtr : *fPRealData) {
const auto classType = dataPtr->IsA();
const auto dataPtrName = dataPtr->GetName();
if (classType == TProtoRealData::Class())
Info("TProtoClass","Data is a protorealdata: %s", dataPtrName);
if (classType == TObjString::Class())
Info("TProtoClass","Data is a objectstring: %s", dataPtrName);
if (dataPtr->TestBit(TRealData::kTransient))
Info("TProtoClass","And is transient");
}
}
}
cl->CalculateStreamerOffset();
fOffsetStreamer = cl->fOffsetStreamer;
}
//______________________________________________________________________________
TProtoClass::~TProtoClass()
{
// Destructor.
Delete();
}
//______________________________________________________________________________
void TProtoClass::Delete(Option_t* opt /*= ""*/) {
// Delete the containers that are usually owned by their TClass.
if (fPRealData) fPRealData->Delete(opt);
delete fPRealData; fPRealData = 0;
if (fBase) fBase->Delete(opt);
delete fBase; fBase = 0;
if (fData) fData->Delete(opt);
delete fData; fData = 0;
if (fEnums) fEnums->Delete(opt);
delete fEnums; fEnums = 0;
}
#include <iostream>
//______________________________________________________________________________
Bool_t TProtoClass::FillTClass(TClass* cl) {
// Move data from this TProtoClass into cl.
if (cl->fRealData || cl->fBase || cl->fData || cl->fEnums
|| cl->fSizeof != -1 || cl->fCanSplit >= 0
|| cl->fProperty != (-1) ) {
if (cl->fProperty & kIsNamespace){
if (gDebug>0) Info("FillTClass", "Returning w/o doing anything. %s is a namespace.",cl->GetName());
return kTRUE;
}
Error("FillTClass", "TClass %s already initialized!", cl->GetName());
return kFALSE;
}
if (gDebug > 1) Info("FillTClass","Loading TProtoClass for %s - %s",cl->GetName(),GetName());
if (fPRealData) {
// A first loop to retrieve the mother classes before starting to
// fill this TClass instance. This is done in order to avoid recursions
// for example in presence of daughter and mother class present in two
// dictionaries compiled in two different libraries which are not linked
// one with each other.
for (TObject* element: *fPRealData) {
if (element->IsA() == TObjString::Class()) {
if (gDebug > 1) Info("","Treating beforehand mother class %s",element->GetName());
int autoparsingOldval=gInterpreter->SetClassAutoparsing(false);
TClass::GetClass(element->GetName());
gInterpreter->SetClassAutoparsing(autoparsingOldval);
}
}
}
// Copy only the TClass bits.
// not bit 13 and below and not bit 24 and above, just Bits 14 - 23
UInt_t newbits = TestBits(0x00ffc000);
cl->ResetBit(0x00ffc000);
cl->SetBit(newbits);
cl->fName = this->fName;
cl->fTitle = this->fTitle;
cl->fBase = fBase;
cl->fData = (TListOfDataMembers*)fData;
// We need to fill enums one by one to initialise the internal map which is
// transient
cl->fEnums = new TListOfEnums();
for (TObject* enumAsTObj : *fEnums){
cl->fEnums->Add((TEnum*) enumAsTObj);
}
cl->fRealData = new TList(); // FIXME: this should really become a THashList!
cl->fSizeof = fSizeof;
cl->fCanSplit = fCanSplit;
cl->fProperty = fProperty;
cl->fClassProperty = fClassProperty;
cl->fStreamerType = fStreamerType;
// Update pointers to TClass
if (cl->fBase) {
for (auto base: *cl->fBase) {
((TBaseClass*)base)->SetClass(cl);
}
}
if (cl->fData) {
for (auto dm: *cl->fData) {
((TDataMember*)dm)->SetClass(cl);
}
((TListOfDataMembers*)cl->fData)->SetClass(cl);
}
if (cl->fEnums) {
for (auto en: *cl->fEnums) {
((TEnum*)en)->SetClass(cl);
}
((TListOfEnums*)cl->fEnums)->SetClass(cl);
}
TClass* currentRDClass = cl;
if (fPRealData) {
for (TObject* element: *fPRealData) {
if (element->IsA() == TObjString::Class()) {
// We now check for the TClass entry, w/o loading. Indeed we did that above.
// If the class is not found, it means that really it was not selected and we
// replace it with an empty placeholder with the status of kForwardDeclared.
// Interactivity will be of course possible but if IO is attempted, a warning
// will be issued.
int autoparsingOldval=gInterpreter->SetClassAutoparsing(false);
// Disable autoparsing which might be triggered by the use of ResolvedTypedef
// and the fallback new TClass() below.
currentRDClass = TClass::GetClass(element->GetName(), false /* Load */ );
if (!currentRDClass && !element->TestBit(TRealData::kTransient)) {
if (gDebug>1)
Info("FillTClass()",
"Cannot find TClass for %s; Creating an empty one in the kForwardDeclared state.",
element->GetName());
currentRDClass = new TClass(element->GetName(),1,TClass::kForwardDeclared, true /*silent*/);
}
gInterpreter->SetClassAutoparsing(autoparsingOldval);
} else {
if (!currentRDClass) continue;
TProtoRealData* prd = (TProtoRealData*)element;
if (TRealData* rd = prd->CreateRealData(currentRDClass, cl)) {
cl->fRealData->AddLast(rd);
}
}
}
}
cl->SetStreamerImpl();
fBase = 0;
fData = 0;
fEnums = 0;
if (fPRealData) fPRealData->Delete();
delete fPRealData;
fPRealData = 0;
return kTRUE;
}
//______________________________________________________________________________
TProtoClass::TProtoRealData::TProtoRealData(const TRealData* rd):
TNamed(rd->GetDataMember()->GetName(), rd->GetName()),
fOffset(rd->GetThisOffset())
{
// Initialize this from a TRealData object.
SetBit(kIsObject, rd->IsObject());
SetBit(TRealData::kTransient, rd->TestBit(TRealData::kTransient));
}
//______________________________________________________________________________
TProtoClass::TProtoRealData::~TProtoRealData()
{
// Destructor to pin vtable.
}
//______________________________________________________________________________
TRealData* TProtoClass::TProtoRealData::CreateRealData(TClass* dmClass,
TClass* parent) const
{
// Create a TRealData from this, with its data member coming from dmClass.
TDataMember* dm = (TDataMember*)dmClass->GetListOfDataMembers()->FindObject(GetName());
if (!dm && dmClass->GetState()!=TClass::kForwardDeclared) {
Error("CreateRealData",
"Cannot find data member %s::%s for parent %s!", dmClass->GetName(),
GetName(), parent->GetName());
return nullptr;
}
TRealData* rd = new TRealData(GetTitle(), fOffset, dm);
rd->SetIsObject(TestBit(kIsObject));
return rd;
}
<commit_msg>remove debugging leftover<commit_after>// @(#)root/meta:$
// Author: Axel Naumann 2014-05-02
/*************************************************************************
* Copyright (C) 1995-2014, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// Persistent version of a TClass. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TProtoClass.h"
#include "TBaseClass.h"
#include "TClass.h"
#include "TDataMember.h"
#include "TEnum.h"
#include "TInterpreter.h"
#include "TList.h"
#include "TListOfDataMembers.h"
#include "TListOfEnums.h"
#include "TRealData.h"
//______________________________________________________________________________
TProtoClass::TProtoClass(TClass* cl):
TNamed(*cl), fBase(cl->GetListOfBases()), fData(cl->GetListOfDataMembers()),
fEnums(cl->GetListOfEnums()), fSizeof(cl->Size()), fCanSplit(cl->fCanSplit),
fStreamerType(cl->fStreamerType), fProperty(cl->fProperty),
fClassProperty(cl->fClassProperty)
{
// Initialize a TProtoClass from a TClass.
if (cl->Property() & kIsNamespace){
fData=new TListOfDataMembers();
fEnums=nullptr;
fPRealData=nullptr;
fOffsetStreamer=0;
return;
}
fPRealData = new TList();
if (!cl->GetCollectionProxy()) {
// Build the list of RealData before we access it:
cl->BuildRealData(0, true /*isTransient*/);
// The data members are ordered as follows:
// - this class's data members,
// - foreach base: base class's data members.
// fPRealData encodes all TProtoRealData objects with a
// TObjString to signal a new class.
TClass* clCurrent = cl;
TRealData* precRd = nullptr;
for (auto realDataObj: *cl->GetListOfRealData()) {
TRealData *rd = (TRealData*)realDataObj;
if (!precRd) precRd = rd;
TClass* clRD = rd->GetDataMember()->GetClass();
if (clRD != clCurrent) {
clCurrent = clRD;
TObjString *clstr = new TObjString(clRD->GetName());
if (precRd->TestBit(TRealData::kTransient)) {
clstr->SetBit(TRealData::kTransient);
}
fPRealData->AddLast(clstr);
precRd = rd;
}
fPRealData->AddLast(new TProtoRealData(rd));
}
if (gDebug > 2) {
for (auto dataPtr : *fPRealData) {
const auto classType = dataPtr->IsA();
const auto dataPtrName = dataPtr->GetName();
if (classType == TProtoRealData::Class())
Info("TProtoClass","Data is a protorealdata: %s", dataPtrName);
if (classType == TObjString::Class())
Info("TProtoClass","Data is a objectstring: %s", dataPtrName);
if (dataPtr->TestBit(TRealData::kTransient))
Info("TProtoClass","And is transient");
}
}
}
cl->CalculateStreamerOffset();
fOffsetStreamer = cl->fOffsetStreamer;
}
//______________________________________________________________________________
TProtoClass::~TProtoClass()
{
// Destructor.
Delete();
}
//______________________________________________________________________________
void TProtoClass::Delete(Option_t* opt /*= ""*/) {
// Delete the containers that are usually owned by their TClass.
if (fPRealData) fPRealData->Delete(opt);
delete fPRealData; fPRealData = 0;
if (fBase) fBase->Delete(opt);
delete fBase; fBase = 0;
if (fData) fData->Delete(opt);
delete fData; fData = 0;
if (fEnums) fEnums->Delete(opt);
delete fEnums; fEnums = 0;
}
//______________________________________________________________________________
Bool_t TProtoClass::FillTClass(TClass* cl) {
// Move data from this TProtoClass into cl.
if (cl->fRealData || cl->fBase || cl->fData || cl->fEnums
|| cl->fSizeof != -1 || cl->fCanSplit >= 0
|| cl->fProperty != (-1) ) {
if (cl->fProperty & kIsNamespace){
if (gDebug>0) Info("FillTClass", "Returning w/o doing anything. %s is a namespace.",cl->GetName());
return kTRUE;
}
Error("FillTClass", "TClass %s already initialized!", cl->GetName());
return kFALSE;
}
if (gDebug > 1) Info("FillTClass","Loading TProtoClass for %s - %s",cl->GetName(),GetName());
if (fPRealData) {
// A first loop to retrieve the mother classes before starting to
// fill this TClass instance. This is done in order to avoid recursions
// for example in presence of daughter and mother class present in two
// dictionaries compiled in two different libraries which are not linked
// one with each other.
for (TObject* element: *fPRealData) {
if (element->IsA() == TObjString::Class()) {
if (gDebug > 1) Info("","Treating beforehand mother class %s",element->GetName());
int autoparsingOldval=gInterpreter->SetClassAutoparsing(false);
TClass::GetClass(element->GetName());
gInterpreter->SetClassAutoparsing(autoparsingOldval);
}
}
}
// Copy only the TClass bits.
// not bit 13 and below and not bit 24 and above, just Bits 14 - 23
UInt_t newbits = TestBits(0x00ffc000);
cl->ResetBit(0x00ffc000);
cl->SetBit(newbits);
cl->fName = this->fName;
cl->fTitle = this->fTitle;
cl->fBase = fBase;
cl->fData = (TListOfDataMembers*)fData;
// We need to fill enums one by one to initialise the internal map which is
// transient
cl->fEnums = new TListOfEnums();
for (TObject* enumAsTObj : *fEnums){
cl->fEnums->Add((TEnum*) enumAsTObj);
}
cl->fRealData = new TList(); // FIXME: this should really become a THashList!
cl->fSizeof = fSizeof;
cl->fCanSplit = fCanSplit;
cl->fProperty = fProperty;
cl->fClassProperty = fClassProperty;
cl->fStreamerType = fStreamerType;
// Update pointers to TClass
if (cl->fBase) {
for (auto base: *cl->fBase) {
((TBaseClass*)base)->SetClass(cl);
}
}
if (cl->fData) {
for (auto dm: *cl->fData) {
((TDataMember*)dm)->SetClass(cl);
}
((TListOfDataMembers*)cl->fData)->SetClass(cl);
}
if (cl->fEnums) {
for (auto en: *cl->fEnums) {
((TEnum*)en)->SetClass(cl);
}
((TListOfEnums*)cl->fEnums)->SetClass(cl);
}
TClass* currentRDClass = cl;
if (fPRealData) {
for (TObject* element: *fPRealData) {
if (element->IsA() == TObjString::Class()) {
// We now check for the TClass entry, w/o loading. Indeed we did that above.
// If the class is not found, it means that really it was not selected and we
// replace it with an empty placeholder with the status of kForwardDeclared.
// Interactivity will be of course possible but if IO is attempted, a warning
// will be issued.
int autoparsingOldval=gInterpreter->SetClassAutoparsing(false);
// Disable autoparsing which might be triggered by the use of ResolvedTypedef
// and the fallback new TClass() below.
currentRDClass = TClass::GetClass(element->GetName(), false /* Load */ );
if (!currentRDClass && !element->TestBit(TRealData::kTransient)) {
if (gDebug>1)
Info("FillTClass()",
"Cannot find TClass for %s; Creating an empty one in the kForwardDeclared state.",
element->GetName());
currentRDClass = new TClass(element->GetName(),1,TClass::kForwardDeclared, true /*silent*/);
}
gInterpreter->SetClassAutoparsing(autoparsingOldval);
} else {
if (!currentRDClass) continue;
TProtoRealData* prd = (TProtoRealData*)element;
if (TRealData* rd = prd->CreateRealData(currentRDClass, cl)) {
cl->fRealData->AddLast(rd);
}
}
}
}
cl->SetStreamerImpl();
fBase = 0;
fData = 0;
fEnums = 0;
if (fPRealData) fPRealData->Delete();
delete fPRealData;
fPRealData = 0;
return kTRUE;
}
//______________________________________________________________________________
TProtoClass::TProtoRealData::TProtoRealData(const TRealData* rd):
TNamed(rd->GetDataMember()->GetName(), rd->GetName()),
fOffset(rd->GetThisOffset())
{
// Initialize this from a TRealData object.
SetBit(kIsObject, rd->IsObject());
SetBit(TRealData::kTransient, rd->TestBit(TRealData::kTransient));
}
//______________________________________________________________________________
TProtoClass::TProtoRealData::~TProtoRealData()
{
// Destructor to pin vtable.
}
//______________________________________________________________________________
TRealData* TProtoClass::TProtoRealData::CreateRealData(TClass* dmClass,
TClass* parent) const
{
// Create a TRealData from this, with its data member coming from dmClass.
TDataMember* dm = (TDataMember*)dmClass->GetListOfDataMembers()->FindObject(GetName());
if (!dm && dmClass->GetState()!=TClass::kForwardDeclared) {
Error("CreateRealData",
"Cannot find data member %s::%s for parent %s!", dmClass->GetName(),
GetName(), parent->GetName());
return nullptr;
}
TRealData* rd = new TRealData(GetTitle(), fOffset, dm);
rd->SetIsObject(TestBit(kIsObject));
return rd;
}
<|endoftext|> |
<commit_before><commit_msg>Control : add revser_speed logic<commit_after><|endoftext|> |
<commit_before>/*
* PlaylistManager.cpp
*****************************************************************************
* Copyright © 2010 - 2011 Klagenfurt University
* 2015 VideoLAN and VLC Authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "PlaylistManager.h"
#include "SegmentTracker.hpp"
#include "playlist/AbstractPlaylist.hpp"
#include "playlist/BasePeriod.h"
#include "playlist/BaseAdaptationSet.h"
#include "playlist/BaseRepresentation.h"
#include "http/HTTPConnectionManager.h"
#include "logic/AlwaysBestAdaptationLogic.h"
#include "logic/RateBasedAdaptationLogic.h"
#include "logic/AlwaysLowestAdaptationLogic.hpp"
#include <vlc_stream.h>
#include <vlc_demux.h>
#include <ctime>
using namespace adaptative::http;
using namespace adaptative::logic;
using namespace adaptative;
PlaylistManager::PlaylistManager( demux_t *p_demux_,
AbstractPlaylist *pl,
AbstractStreamOutputFactory *factory,
AbstractAdaptationLogic::LogicType type ) :
conManager ( NULL ),
logicType ( type ),
playlist ( pl ),
streamOutputFactory( factory ),
p_demux ( p_demux_ ),
nextPlaylistupdate ( 0 ),
i_nzpcr ( 0 )
{
currentPeriod = playlist->getFirstPeriod();
}
PlaylistManager::~PlaylistManager ()
{
delete conManager;
delete streamOutputFactory;
unsetPeriod();
}
void PlaylistManager::unsetPeriod()
{
std::vector<Stream *>::iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
delete *it;
streams.clear();
}
bool PlaylistManager::setupPeriod()
{
if(!currentPeriod)
return false;
std::vector<BaseAdaptationSet*> sets = currentPeriod->getAdaptationSets();
std::vector<BaseAdaptationSet*>::iterator it;
for(it=sets.begin();it!=sets.end();++it)
{
BaseAdaptationSet *set = *it;
if(set)
{
Stream *st = new (std::nothrow) Stream(p_demux, set->getStreamFormat());
if(!st)
continue;
AbstractAdaptationLogic *logic = createLogic(logicType);
if(!logic)
{
delete st;
continue;
}
SegmentTracker *tracker = new (std::nothrow) SegmentTracker(logic, set);
try
{
if(!tracker || !streamOutputFactory)
{
delete tracker;
delete logic;
throw VLC_ENOMEM;
}
std::list<std::string> languages;
if(!set->getLang().empty())
{
languages = set->getLang();
}
else if(!set->getRepresentations().empty())
{
languages = set->getRepresentations().front()->getLang();
}
if(!languages.empty())
st->setLanguage(languages.front());
if(!set->description.Get().empty())
st->setDescription(set->description.Get());
st->create(logic, tracker, streamOutputFactory);
streams.push_back(st);
} catch (int) {
delete st;
}
}
}
return true;
}
bool PlaylistManager::start()
{
if(!setupPeriod())
return false;
conManager = new (std::nothrow) HTTPConnectionManager(VLC_OBJECT(p_demux->s));
if(!conManager)
return false;
playlist->playbackStart.Set(time(NULL));
nextPlaylistupdate = playlist->playbackStart.Get();
return true;
}
Stream::status PlaylistManager::demux(mtime_t nzdeadline, bool send)
{
Stream::status i_return = Stream::status_eof;
std::vector<Stream *>::iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
Stream *st = *it;
if (st->isDisabled())
{
if(st->isSelected() && !st->isEOF())
st->reactivate(getPCR());
else
continue;
}
Stream::status i_ret = st->demux(conManager, nzdeadline, send);
if(i_ret == Stream::status_buffering)
{
i_return = Stream::status_buffering;
}
else if(i_ret == Stream::status_demuxed &&
i_return != Stream::status_buffering)
{
i_return = Stream::status_demuxed;
}
}
/* might be end of current period */
if(i_return == Stream::status_eof && currentPeriod)
{
unsetPeriod();
currentPeriod = playlist->getNextPeriod(currentPeriod);
i_return = (setupPeriod()) ? Stream::status_eop : Stream::status_eof;
}
return i_return;
}
mtime_t PlaylistManager::getPCR() const
{
mtime_t pcr = VLC_TS_INVALID;
std::vector<Stream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
if ((*it)->isDisabled())
continue;
if(pcr == VLC_TS_INVALID || pcr > (*it)->getPCR())
pcr = (*it)->getPCR();
}
return pcr;
}
mtime_t PlaylistManager::getFirstDTS() const
{
mtime_t dts = VLC_TS_INVALID;
std::vector<Stream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
if ((*it)->isDisabled())
continue;
if(dts == VLC_TS_INVALID || dts > (*it)->getFirstDTS())
dts = (*it)->getFirstDTS();
}
return dts;
}
int PlaylistManager::esCount() const
{
int es = 0;
std::vector<Stream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
es += (*it)->esCount();
}
return es;
}
mtime_t PlaylistManager::getDuration() const
{
if (playlist->isLive())
return 0;
else
return playlist->duration.Get();
}
bool PlaylistManager::setPosition(mtime_t time)
{
bool ret = true;
for(int real = 0; real < 2; real++)
{
/* Always probe if we can seek first */
std::vector<Stream *>::iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
ret &= (*it)->setPosition(time, !real);
}
if(!ret)
break;
}
return ret;
}
bool PlaylistManager::seekAble() const
{
if(playlist->isLive())
return false;
std::vector<Stream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
if(!(*it)->seekAble())
return false;
}
return true;
}
bool PlaylistManager::updatePlaylist()
{
return true;
}
#define DEMUX_INCREMENT (CLOCK_FREQ / 20)
int PlaylistManager::demux_callback(demux_t *p_demux)
{
PlaylistManager *manager = reinterpret_cast<PlaylistManager *>(p_demux->p_sys);
return manager->doDemux(DEMUX_INCREMENT);
}
int PlaylistManager::doDemux(int64_t increment)
{
if(i_nzpcr == VLC_TS_INVALID)
{
if( Stream::status_eof == demux(i_nzpcr + increment, false) )
{
return VLC_DEMUXER_EOF;
}
i_nzpcr = getFirstDTS();
if(i_nzpcr == VLC_TS_INVALID)
i_nzpcr = getPCR();
}
Stream::status status = demux(i_nzpcr + increment, true);
switch(status)
{
case Stream::status_eof:
return VLC_DEMUXER_EOF;
case Stream::status_buffering:
break;
case Stream::status_eop:
i_nzpcr = VLC_TS_INVALID;
es_out_Control(p_demux->out, ES_OUT_RESET_PCR);
break;
case Stream::status_demuxed:
if( i_nzpcr != VLC_TS_INVALID )
{
i_nzpcr += increment;
es_out_Control(p_demux->out, ES_OUT_SET_GROUP_PCR, 0, VLC_TS_0 + i_nzpcr);
}
break;
}
if( !updatePlaylist() )
msg_Warn(p_demux, "Can't update MPD");
return VLC_DEMUXER_SUCCESS;
}
int PlaylistManager::control_callback(demux_t *p_demux, int i_query, va_list args)
{
PlaylistManager *manager = reinterpret_cast<PlaylistManager *>(p_demux->p_sys);
return manager->doControl(i_query, args);
}
int PlaylistManager::doControl(int i_query, va_list args)
{
switch (i_query)
{
case DEMUX_CAN_SEEK:
*(va_arg (args, bool *)) = seekAble();
break;
case DEMUX_CAN_CONTROL_PACE:
*(va_arg (args, bool *)) = true;
break;
case DEMUX_CAN_PAUSE:
*(va_arg (args, bool *)) = playlist->isLive();
break;
case DEMUX_GET_TIME:
*(va_arg (args, int64_t *)) = i_nzpcr;
break;
case DEMUX_GET_LENGTH:
*(va_arg (args, int64_t *)) = getDuration();
break;
case DEMUX_GET_POSITION:
if(!getDuration())
return VLC_EGENERIC;
*(va_arg (args, double *)) = (double) i_nzpcr
/ getDuration();
break;
case DEMUX_SET_POSITION:
{
int64_t time = getDuration() * va_arg(args, double);
if(playlist->isLive() ||
!getDuration() ||
!setPosition(time))
return VLC_EGENERIC;
i_nzpcr = VLC_TS_INVALID;
break;
}
case DEMUX_SET_TIME:
{
int64_t time = va_arg(args, int64_t);
if(playlist->isLive() ||
!setPosition(time))
return VLC_EGENERIC;
i_nzpcr = VLC_TS_INVALID;
break;
}
case DEMUX_GET_PTS_DELAY:
*va_arg (args, int64_t *) = INT64_C(1000) *
var_InheritInteger(p_demux, "network-caching");
break;
default:
return VLC_EGENERIC;
}
return VLC_SUCCESS;
}
AbstractAdaptationLogic *PlaylistManager::createLogic(AbstractAdaptationLogic::LogicType type)
{
switch(type)
{
case AbstractAdaptationLogic::AlwaysBest:
return new (std::nothrow) AlwaysBestAdaptationLogic();
case AbstractAdaptationLogic::FixedRate:
case AbstractAdaptationLogic::AlwaysLowest:
return new (std::nothrow) AlwaysLowestAdaptationLogic();
case AbstractAdaptationLogic::Default:
case AbstractAdaptationLogic::RateBased:
return new (std::nothrow) RateBasedAdaptationLogic(0, 0);
default:
return NULL;
}
}
<commit_msg>demux: adaptative: fix memory leak<commit_after>/*
* PlaylistManager.cpp
*****************************************************************************
* Copyright © 2010 - 2011 Klagenfurt University
* 2015 VideoLAN and VLC Authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "PlaylistManager.h"
#include "SegmentTracker.hpp"
#include "playlist/AbstractPlaylist.hpp"
#include "playlist/BasePeriod.h"
#include "playlist/BaseAdaptationSet.h"
#include "playlist/BaseRepresentation.h"
#include "http/HTTPConnectionManager.h"
#include "logic/AlwaysBestAdaptationLogic.h"
#include "logic/RateBasedAdaptationLogic.h"
#include "logic/AlwaysLowestAdaptationLogic.hpp"
#include <vlc_stream.h>
#include <vlc_demux.h>
#include <ctime>
using namespace adaptative::http;
using namespace adaptative::logic;
using namespace adaptative;
PlaylistManager::PlaylistManager( demux_t *p_demux_,
AbstractPlaylist *pl,
AbstractStreamOutputFactory *factory,
AbstractAdaptationLogic::LogicType type ) :
conManager ( NULL ),
logicType ( type ),
playlist ( pl ),
streamOutputFactory( factory ),
p_demux ( p_demux_ ),
nextPlaylistupdate ( 0 ),
i_nzpcr ( 0 )
{
currentPeriod = playlist->getFirstPeriod();
}
PlaylistManager::~PlaylistManager ()
{
delete conManager;
delete playlist;
delete streamOutputFactory;
unsetPeriod();
}
void PlaylistManager::unsetPeriod()
{
std::vector<Stream *>::iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
delete *it;
streams.clear();
}
bool PlaylistManager::setupPeriod()
{
if(!currentPeriod)
return false;
std::vector<BaseAdaptationSet*> sets = currentPeriod->getAdaptationSets();
std::vector<BaseAdaptationSet*>::iterator it;
for(it=sets.begin();it!=sets.end();++it)
{
BaseAdaptationSet *set = *it;
if(set)
{
Stream *st = new (std::nothrow) Stream(p_demux, set->getStreamFormat());
if(!st)
continue;
AbstractAdaptationLogic *logic = createLogic(logicType);
if(!logic)
{
delete st;
continue;
}
SegmentTracker *tracker = new (std::nothrow) SegmentTracker(logic, set);
try
{
if(!tracker || !streamOutputFactory)
{
delete tracker;
delete logic;
throw VLC_ENOMEM;
}
std::list<std::string> languages;
if(!set->getLang().empty())
{
languages = set->getLang();
}
else if(!set->getRepresentations().empty())
{
languages = set->getRepresentations().front()->getLang();
}
if(!languages.empty())
st->setLanguage(languages.front());
if(!set->description.Get().empty())
st->setDescription(set->description.Get());
st->create(logic, tracker, streamOutputFactory);
streams.push_back(st);
} catch (int) {
delete st;
}
}
}
return true;
}
bool PlaylistManager::start()
{
if(!setupPeriod())
return false;
conManager = new (std::nothrow) HTTPConnectionManager(VLC_OBJECT(p_demux->s));
if(!conManager)
return false;
playlist->playbackStart.Set(time(NULL));
nextPlaylistupdate = playlist->playbackStart.Get();
return true;
}
Stream::status PlaylistManager::demux(mtime_t nzdeadline, bool send)
{
Stream::status i_return = Stream::status_eof;
std::vector<Stream *>::iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
Stream *st = *it;
if (st->isDisabled())
{
if(st->isSelected() && !st->isEOF())
st->reactivate(getPCR());
else
continue;
}
Stream::status i_ret = st->demux(conManager, nzdeadline, send);
if(i_ret == Stream::status_buffering)
{
i_return = Stream::status_buffering;
}
else if(i_ret == Stream::status_demuxed &&
i_return != Stream::status_buffering)
{
i_return = Stream::status_demuxed;
}
}
/* might be end of current period */
if(i_return == Stream::status_eof && currentPeriod)
{
unsetPeriod();
currentPeriod = playlist->getNextPeriod(currentPeriod);
i_return = (setupPeriod()) ? Stream::status_eop : Stream::status_eof;
}
return i_return;
}
mtime_t PlaylistManager::getPCR() const
{
mtime_t pcr = VLC_TS_INVALID;
std::vector<Stream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
if ((*it)->isDisabled())
continue;
if(pcr == VLC_TS_INVALID || pcr > (*it)->getPCR())
pcr = (*it)->getPCR();
}
return pcr;
}
mtime_t PlaylistManager::getFirstDTS() const
{
mtime_t dts = VLC_TS_INVALID;
std::vector<Stream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
if ((*it)->isDisabled())
continue;
if(dts == VLC_TS_INVALID || dts > (*it)->getFirstDTS())
dts = (*it)->getFirstDTS();
}
return dts;
}
int PlaylistManager::esCount() const
{
int es = 0;
std::vector<Stream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
es += (*it)->esCount();
}
return es;
}
mtime_t PlaylistManager::getDuration() const
{
if (playlist->isLive())
return 0;
else
return playlist->duration.Get();
}
bool PlaylistManager::setPosition(mtime_t time)
{
bool ret = true;
for(int real = 0; real < 2; real++)
{
/* Always probe if we can seek first */
std::vector<Stream *>::iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
ret &= (*it)->setPosition(time, !real);
}
if(!ret)
break;
}
return ret;
}
bool PlaylistManager::seekAble() const
{
if(playlist->isLive())
return false;
std::vector<Stream *>::const_iterator it;
for(it=streams.begin(); it!=streams.end(); ++it)
{
if(!(*it)->seekAble())
return false;
}
return true;
}
bool PlaylistManager::updatePlaylist()
{
return true;
}
#define DEMUX_INCREMENT (CLOCK_FREQ / 20)
int PlaylistManager::demux_callback(demux_t *p_demux)
{
PlaylistManager *manager = reinterpret_cast<PlaylistManager *>(p_demux->p_sys);
return manager->doDemux(DEMUX_INCREMENT);
}
int PlaylistManager::doDemux(int64_t increment)
{
if(i_nzpcr == VLC_TS_INVALID)
{
if( Stream::status_eof == demux(i_nzpcr + increment, false) )
{
return VLC_DEMUXER_EOF;
}
i_nzpcr = getFirstDTS();
if(i_nzpcr == VLC_TS_INVALID)
i_nzpcr = getPCR();
}
Stream::status status = demux(i_nzpcr + increment, true);
switch(status)
{
case Stream::status_eof:
return VLC_DEMUXER_EOF;
case Stream::status_buffering:
break;
case Stream::status_eop:
i_nzpcr = VLC_TS_INVALID;
es_out_Control(p_demux->out, ES_OUT_RESET_PCR);
break;
case Stream::status_demuxed:
if( i_nzpcr != VLC_TS_INVALID )
{
i_nzpcr += increment;
es_out_Control(p_demux->out, ES_OUT_SET_GROUP_PCR, 0, VLC_TS_0 + i_nzpcr);
}
break;
}
if( !updatePlaylist() )
msg_Warn(p_demux, "Can't update MPD");
return VLC_DEMUXER_SUCCESS;
}
int PlaylistManager::control_callback(demux_t *p_demux, int i_query, va_list args)
{
PlaylistManager *manager = reinterpret_cast<PlaylistManager *>(p_demux->p_sys);
return manager->doControl(i_query, args);
}
int PlaylistManager::doControl(int i_query, va_list args)
{
switch (i_query)
{
case DEMUX_CAN_SEEK:
*(va_arg (args, bool *)) = seekAble();
break;
case DEMUX_CAN_CONTROL_PACE:
*(va_arg (args, bool *)) = true;
break;
case DEMUX_CAN_PAUSE:
*(va_arg (args, bool *)) = playlist->isLive();
break;
case DEMUX_GET_TIME:
*(va_arg (args, int64_t *)) = i_nzpcr;
break;
case DEMUX_GET_LENGTH:
*(va_arg (args, int64_t *)) = getDuration();
break;
case DEMUX_GET_POSITION:
if(!getDuration())
return VLC_EGENERIC;
*(va_arg (args, double *)) = (double) i_nzpcr
/ getDuration();
break;
case DEMUX_SET_POSITION:
{
int64_t time = getDuration() * va_arg(args, double);
if(playlist->isLive() ||
!getDuration() ||
!setPosition(time))
return VLC_EGENERIC;
i_nzpcr = VLC_TS_INVALID;
break;
}
case DEMUX_SET_TIME:
{
int64_t time = va_arg(args, int64_t);
if(playlist->isLive() ||
!setPosition(time))
return VLC_EGENERIC;
i_nzpcr = VLC_TS_INVALID;
break;
}
case DEMUX_GET_PTS_DELAY:
*va_arg (args, int64_t *) = INT64_C(1000) *
var_InheritInteger(p_demux, "network-caching");
break;
default:
return VLC_EGENERIC;
}
return VLC_SUCCESS;
}
AbstractAdaptationLogic *PlaylistManager::createLogic(AbstractAdaptationLogic::LogicType type)
{
switch(type)
{
case AbstractAdaptationLogic::AlwaysBest:
return new (std::nothrow) AlwaysBestAdaptationLogic();
case AbstractAdaptationLogic::FixedRate:
case AbstractAdaptationLogic::AlwaysLowest:
return new (std::nothrow) AlwaysLowestAdaptationLogic();
case AbstractAdaptationLogic::Default:
case AbstractAdaptationLogic::RateBased:
return new (std::nothrow) RateBasedAdaptationLogic(0, 0);
default:
return NULL;
}
}
<|endoftext|> |
<commit_before>/*
* DOMParser.cpp
*****************************************************************************
* Copyright (C) 2010 - 2011 Klagenfurt University
*
* Created on: Aug 10, 2010
* Authors: Christopher Mueller <christopher.mueller@itec.uni-klu.ac.at>
* Christian Timmerer <christian.timmerer@itec.uni-klu.ac.at>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "DOMParser.h"
#include <vector>
using namespace dash::xml;
using namespace dash::mpd;
DOMParser::DOMParser (stream_t *stream) :
root( NULL ),
stream( stream ),
vlc_xml( NULL ),
vlc_reader( NULL )
{
}
DOMParser::~DOMParser ()
{
delete this->root;
if(this->vlc_reader)
xml_ReaderDelete(this->vlc_reader);
if ( this->vlc_xml )
xml_Delete( this->vlc_xml );
}
Node* DOMParser::getRootNode ()
{
return this->root;
}
bool DOMParser::parse ()
{
this->vlc_xml = xml_Create(this->stream);
if(!this->vlc_xml)
return false;
this->vlc_reader = xml_ReaderCreate(this->vlc_xml, this->stream);
if(!this->vlc_reader)
return false;
this->root = this->processNode();
if ( this->root == NULL )
return false;
return true;
}
Node* DOMParser::processNode ()
{
const char *data;
int type = xml_ReaderNextNode(this->vlc_reader, &data);
if(type != -1 && type != XML_READER_NONE && type != XML_READER_ENDELEM)
{
Node *node = new Node();
node->setType( type );
if ( type != XML_READER_TEXT )
{
std::string name = data;
bool isEmpty = xml_ReaderIsEmptyElement(this->vlc_reader);
node->setName(name);
this->addAttributesToNode(node);
if(isEmpty)
return node;
Node *subnode = NULL;
while((subnode = this->processNode()) != NULL)
node->addSubNode(subnode);
}
else
node->setText( data );
return node;
}
return NULL;
}
void DOMParser::addAttributesToNode (Node *node)
{
const char *attrValue;
const char *attrName;
while((attrName = xml_ReaderNextAttr(this->vlc_reader, &attrValue)) != NULL)
{
std::string key = attrName;
std::string value = attrValue;
node->addAttribute(key, value);
}
}
void DOMParser::print (Node *node, int offset)
{
for(int i = 0; i < offset; i++)
msg_Dbg(this->stream, " ");
msg_Dbg(this->stream, "%s", node->getName().c_str());
std::vector<std::string> keys = node->getAttributeKeys();
for(size_t i = 0; i < keys.size(); i++)
msg_Dbg(this->stream, " %s=%s", keys.at(i).c_str(), node->getAttributeValue(keys.at(i)).c_str());
msg_Dbg(this->stream, "\n");
offset++;
for(size_t i = 0; i < node->getSubNodes().size(); i++)
{
this->print(node->getSubNodes().at(i), offset);
}
}
void DOMParser::print ()
{
this->print(this->root, 0);
}
bool DOMParser::isDash (stream_t *stream)
{
const char* psz_namespaceDIS = "urn:mpeg:mpegB:schema:DASH:MPD:DIS2011";
const char* psz_namespaceIS = "urn:mpeg:DASH:schema:MPD:2011";
const uint8_t *peek;
int peek_size = stream_Peek(stream, &peek, 1024);
if (peek_size < (int)strlen(psz_namespaceDIS))
return false;
std::string header((const char*)peek, peek_size);
return (header.find(psz_namespaceDIS) != std::string::npos) || (header.find(psz_namespaceIS) != std::string::npos);
}
Profile DOMParser::getProfile ()
{
if(this->root == NULL)
return dash::mpd::UnknownProfile;
const std::string profile = this->root->getAttributeValue("profiles");
if(profile.find("urn:mpeg:mpegB:profile:dash:isoff-basic-on-demand:cm") != std::string::npos)
return dash::mpd::BasicCM;
if(profile.find("urn:mpeg:dash:profile:isoff-main:2011") != std::string::npos)
return dash::mpd::IsoffMain;
return dash::mpd::UnknownProfile;
}
<commit_msg>dash: Handle multiple names for profile "urn:mpeg:dash:profile:isoff-on-demand:2011"<commit_after>/*
* DOMParser.cpp
*****************************************************************************
* Copyright (C) 2010 - 2011 Klagenfurt University
*
* Created on: Aug 10, 2010
* Authors: Christopher Mueller <christopher.mueller@itec.uni-klu.ac.at>
* Christian Timmerer <christian.timmerer@itec.uni-klu.ac.at>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "DOMParser.h"
#include <vector>
using namespace dash::xml;
using namespace dash::mpd;
DOMParser::DOMParser (stream_t *stream) :
root( NULL ),
stream( stream ),
vlc_xml( NULL ),
vlc_reader( NULL )
{
}
DOMParser::~DOMParser ()
{
delete this->root;
if(this->vlc_reader)
xml_ReaderDelete(this->vlc_reader);
if ( this->vlc_xml )
xml_Delete( this->vlc_xml );
}
Node* DOMParser::getRootNode ()
{
return this->root;
}
bool DOMParser::parse ()
{
this->vlc_xml = xml_Create(this->stream);
if(!this->vlc_xml)
return false;
this->vlc_reader = xml_ReaderCreate(this->vlc_xml, this->stream);
if(!this->vlc_reader)
return false;
this->root = this->processNode();
if ( this->root == NULL )
return false;
return true;
}
Node* DOMParser::processNode ()
{
const char *data;
int type = xml_ReaderNextNode(this->vlc_reader, &data);
if(type != -1 && type != XML_READER_NONE && type != XML_READER_ENDELEM)
{
Node *node = new Node();
node->setType( type );
if ( type != XML_READER_TEXT )
{
std::string name = data;
bool isEmpty = xml_ReaderIsEmptyElement(this->vlc_reader);
node->setName(name);
this->addAttributesToNode(node);
if(isEmpty)
return node;
Node *subnode = NULL;
while((subnode = this->processNode()) != NULL)
node->addSubNode(subnode);
}
else
node->setText( data );
return node;
}
return NULL;
}
void DOMParser::addAttributesToNode (Node *node)
{
const char *attrValue;
const char *attrName;
while((attrName = xml_ReaderNextAttr(this->vlc_reader, &attrValue)) != NULL)
{
std::string key = attrName;
std::string value = attrValue;
node->addAttribute(key, value);
}
}
void DOMParser::print (Node *node, int offset)
{
for(int i = 0; i < offset; i++)
msg_Dbg(this->stream, " ");
msg_Dbg(this->stream, "%s", node->getName().c_str());
std::vector<std::string> keys = node->getAttributeKeys();
for(size_t i = 0; i < keys.size(); i++)
msg_Dbg(this->stream, " %s=%s", keys.at(i).c_str(), node->getAttributeValue(keys.at(i)).c_str());
msg_Dbg(this->stream, "\n");
offset++;
for(size_t i = 0; i < node->getSubNodes().size(); i++)
{
this->print(node->getSubNodes().at(i), offset);
}
}
void DOMParser::print ()
{
this->print(this->root, 0);
}
bool DOMParser::isDash (stream_t *stream)
{
const char* psz_namespaceDIS = "urn:mpeg:mpegB:schema:DASH:MPD:DIS2011";
const char* psz_namespaceIS = "urn:mpeg:DASH:schema:MPD:2011";
const uint8_t *peek;
int peek_size = stream_Peek(stream, &peek, 1024);
if (peek_size < (int)strlen(psz_namespaceDIS))
return false;
std::string header((const char*)peek, peek_size);
return (header.find(psz_namespaceDIS) != std::string::npos) || (header.find(psz_namespaceIS) != std::string::npos);
}
Profile DOMParser::getProfile ()
{
if(this->root == NULL)
return dash::mpd::UnknownProfile;
const std::string profile = this->root->getAttributeValue("profiles");
if(profile.find("urn:mpeg:mpegB:profile:dash:isoff-basic-on-demand:cm") != std::string::npos ||
profile.find("urn:mpeg:dash:profile:isoff-ondemand:2011") != std::string::npos ||
profile.find("urn:mpeg:dash:profile:isoff-on-demand:2011") != std::string::npos)
return dash::mpd::BasicCM;
if(profile.find("urn:mpeg:dash:profile:isoff-main:2011") != std::string::npos)
return dash::mpd::IsoffMain;
return dash::mpd::UnknownProfile;
}
<|endoftext|> |
<commit_before>/*============================================================================*/
/*
Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
See the file GNU_GPL_v2.txt for full licensing terms.
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., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*============================================================================*/
FPUFlags FPUFlags::getCurrent ()
{
unsigned int currentControl;
const unsigned int newControl = 0;
const unsigned int mask = 0;
errno_t result = _controlfp_s (¤tControl, newControl, mask);
if (result != 0)
Throw (std::runtime_error ("error in _controlfp_s"));
FPUFlags flags;
flags.setMaskNaNs ((currentControl & _EM_INVALID) == _EM_INVALID);
flags.setMaskDenormals ((currentControl & _EM_DENORMAL) == _EM_DENORMAL);
flags.setMaskZeroDivides ((currentControl & _EM_ZERODIVIDE) == _EM_ZERODIVIDE);
flags.setMaskOverflows ((currentControl & _EM_OVERFLOW) == _EM_OVERFLOW);
flags.setMaskUnderflows ((currentControl & _EM_UNDERFLOW) == _EM_UNDERFLOW);
//flags.setMaskInexacts ((currentControl & _EM_INEXACT) == _EM_INEXACT);
flags.setFlushDenormals ((currentControl & _DN_FLUSH) == _DN_FLUSH);
flags.setInfinitySigned ((currentControl & _IC_AFFINE) == _IC_AFFINE);
Rounding rounding;
switch (currentControl & _MCW_RC)
{
case _RC_CHOP: rounding = roundChop; break;
case _RC_UP: rounding = roundUp; break;
case _RC_DOWN: rounding = roundDown; break;
case _RC_NEAR: rounding = roundNear; break;
default:
Throw (std::runtime_error ("unknown rounding in _controlfp_s"));
};
flags.setRounding (rounding);
Precision precision;
switch (currentControl & _MCW_PC )
{
case _PC_64: precision = bits64; break;
case _PC_53: precision = bits53; break;
case _PC_24: precision = bits24; break;
default:
Throw (std::runtime_error ("unknown precision in _controlfp_s"));
};
flags.setPrecision (precision);
return flags;
}
static void setControl (const FPUFlags::Flag& flag,
unsigned int& newControl,
unsigned int& mask,
unsigned int constant)
{
if (flag.is_set ())
{
mask |= constant;
if (flag.value ())
newControl |= constant;
}
}
void FPUFlags::setCurrent (const FPUFlags& flags)
{
unsigned int newControl = 0;
unsigned int mask = 0;
setControl (flags.getMaskNaNs(), newControl, mask, _EM_INVALID);
setControl (flags.getMaskDenormals(), newControl, mask, _EM_DENORMAL);
setControl (flags.getMaskZeroDivides(), newControl, mask, _EM_ZERODIVIDE);
setControl (flags.getMaskOverflows(), newControl, mask, _EM_OVERFLOW);
setControl (flags.getMaskUnderflows(), newControl, mask, _EM_UNDERFLOW);
//setControl (flags.getMaskInexacts(), newControl, mask, _EM_INEXACT);
setControl (flags.getFlushDenormals(), newControl, mask, _DN_FLUSH);
setControl (flags.getInfinitySigned(), newControl, mask, _IC_AFFINE);
if (flags.getRounding().is_set ())
{
Rounding rounding = flags.getRounding().value ();
switch (rounding)
{
case roundChop: mask |= _MCW_RC; newControl |= _RC_CHOP; break;
case roundUp: mask |= _MCW_RC; newControl |= _RC_UP; break;
case roundDown: mask |= _MCW_RC; newControl |= _RC_DOWN; break;
case roundNear: mask |= _MCW_RC; newControl |= _RC_NEAR; break;
}
}
if (flags.getPrecision().is_set ())
{
switch (flags.getPrecision().value ())
{
case bits64: mask |= _MCW_PC; newControl |= _PC_64; break;
case bits53: mask |= _MCW_PC; newControl |= _PC_53; break;
case bits24: mask |= _MCW_PC; newControl |= _PC_24; break;
}
}
unsigned int currentControl;
errno_t result = _controlfp_s (¤tControl, newControl, mask);
if (result != 0)
Throw (std::runtime_error ("error in _controlfp_s"));
}
<commit_msg>Fix warnings<commit_after>/*============================================================================*/
/*
Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
See the file GNU_GPL_v2.txt for full licensing terms.
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., 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*============================================================================*/
FPUFlags FPUFlags::getCurrent ()
{
unsigned int currentControl;
const unsigned int newControl = 0;
const unsigned int mask = 0;
errno_t result = _controlfp_s (¤tControl, newControl, mask);
if (result != 0)
Throw (std::runtime_error ("error in _controlfp_s"));
FPUFlags flags;
flags.setMaskNaNs ((currentControl & _EM_INVALID) == _EM_INVALID);
flags.setMaskDenormals ((currentControl & _EM_DENORMAL) == _EM_DENORMAL);
flags.setMaskZeroDivides ((currentControl & _EM_ZERODIVIDE) == _EM_ZERODIVIDE);
flags.setMaskOverflows ((currentControl & _EM_OVERFLOW) == _EM_OVERFLOW);
flags.setMaskUnderflows ((currentControl & _EM_UNDERFLOW) == _EM_UNDERFLOW);
//flags.setMaskInexacts ((currentControl & _EM_INEXACT) == _EM_INEXACT);
flags.setFlushDenormals ((currentControl & _DN_FLUSH) == _DN_FLUSH);
flags.setInfinitySigned ((currentControl & _IC_AFFINE) == _IC_AFFINE);
Rounding rounding = roundDown;
switch (currentControl & _MCW_RC)
{
case _RC_CHOP: rounding = roundChop; break;
case _RC_UP: rounding = roundUp; break;
case _RC_DOWN: rounding = roundDown; break;
case _RC_NEAR: rounding = roundNear; break;
default:
Throw (std::runtime_error ("unknown rounding in _controlfp_s"));
};
flags.setRounding (rounding);
Precision precision = bits64;
switch (currentControl & _MCW_PC )
{
case _PC_64: precision = bits64; break;
case _PC_53: precision = bits53; break;
case _PC_24: precision = bits24; break;
default:
Throw (std::runtime_error ("unknown precision in _controlfp_s"));
};
flags.setPrecision (precision);
return flags;
}
static void setControl (const FPUFlags::Flag& flag,
unsigned int& newControl,
unsigned int& mask,
unsigned int constant)
{
if (flag.is_set ())
{
mask |= constant;
if (flag.value ())
newControl |= constant;
}
}
void FPUFlags::setCurrent (const FPUFlags& flags)
{
unsigned int newControl = 0;
unsigned int mask = 0;
setControl (flags.getMaskNaNs(), newControl, mask, _EM_INVALID);
setControl (flags.getMaskDenormals(), newControl, mask, _EM_DENORMAL);
setControl (flags.getMaskZeroDivides(), newControl, mask, _EM_ZERODIVIDE);
setControl (flags.getMaskOverflows(), newControl, mask, _EM_OVERFLOW);
setControl (flags.getMaskUnderflows(), newControl, mask, _EM_UNDERFLOW);
//setControl (flags.getMaskInexacts(), newControl, mask, _EM_INEXACT);
setControl (flags.getFlushDenormals(), newControl, mask, _DN_FLUSH);
setControl (flags.getInfinitySigned(), newControl, mask, _IC_AFFINE);
if (flags.getRounding().is_set ())
{
Rounding rounding = flags.getRounding().value ();
switch (rounding)
{
case roundChop: mask |= _MCW_RC; newControl |= _RC_CHOP; break;
case roundUp: mask |= _MCW_RC; newControl |= _RC_UP; break;
case roundDown: mask |= _MCW_RC; newControl |= _RC_DOWN; break;
case roundNear: mask |= _MCW_RC; newControl |= _RC_NEAR; break;
}
}
if (flags.getPrecision().is_set ())
{
switch (flags.getPrecision().value ())
{
case bits64: mask |= _MCW_PC; newControl |= _PC_64; break;
case bits53: mask |= _MCW_PC; newControl |= _PC_53; break;
case bits24: mask |= _MCW_PC; newControl |= _PC_24; break;
}
}
unsigned int currentControl;
errno_t result = _controlfp_s (¤tControl, newControl, mask);
if (result != 0)
Throw (std::runtime_error ("error in _controlfp_s"));
}
<|endoftext|> |
<commit_before>#pragma once
#include "Structure.h"
class SerialComs {
public:
struct ReadResult {
bool status;
enum class TypeOfPacket {
HandShakePacket,
VesselData
} typeOfPacket;
union {
HandShakePacket handShakePacket;
VesselData vesselData;
};
ReadResult()
: status(false)
{
}
};
private:
uint8_t rx_len;
uint16_t * address;
byte buffer[256]; //address for temporary storage and parsing buffer
uint8_t structSize;
uint8_t rx_array_inx; //index for RX parsing buffer
uint8_t calc_CS; //calculated Chacksum
int id;
public:
//This shit contains stuff borrowed from EasyTransfer lib
inline ReadResult KSPBoardReceiveData() {
ReadResult result;
if ((rx_len == 0)&&(Serial.available()>3)){
while(Serial.read()!= 0xBE) {
if (Serial.available() == 0)
return result;
}
if (Serial.read() == 0xEF){
rx_len = Serial.read();
id = Serial.read();
rx_array_inx = 1;
switch(id) {
case 0:
structSize = sizeof(HandShakePacket);
address = reinterpret_cast<uint16_t*>(&result.handShakePacket);
break;
case 1:
structSize = sizeof(VesselData);
address = reinterpret_cast<uint16_t*>(&result.vesselData);
break;
}
}
//make sure the binary structs on both Arduinos are the same size.
if(rx_len != structSize){
rx_len = 0;
return result;
}
}
if(rx_len != 0){
while(Serial.available() && rx_array_inx <= rx_len){
buffer[rx_array_inx++] = Serial.read();
}
buffer[0] = id;
if(rx_len == (rx_array_inx-1)){
//seem to have got whole message
//last uint8_t is CS
calc_CS = rx_len;
for (int i = 0; i<rx_len; i++){
calc_CS^=buffer[i];
}
if(calc_CS == buffer[rx_array_inx-1]){//CS good
memcpy(address,buffer,structSize);
rx_len = 0;
rx_array_inx = 1;
// Success
result.status = true;
return result;
}
else{
//failed checksum, need to clear this out anyway
rx_len = 0;
rx_array_inx = 1;
return result;
}
}
}
return result;
}
inline void KSPBoardSendData(uint8_t * address, uint8_t len){
uint8_t CS = len;
Serial.write(0xBE);
Serial.write(0xEF);
Serial.write(len);
for(int i = 0; i<len; i++){
CS^=*(address+i);
Serial.write(*(address+i));
}
Serial.write(CS);
}
};
<commit_msg>Fixed the serial read problem with the state of the result<commit_after>#pragma once
#include "Structure.h"
class SerialComs {
public:
struct ReadResult {
bool status;
enum class TypeOfPacket {
HandShakePacket,
VesselData
} typeOfPacket;
union {
HandShakePacket handShakePacket;
VesselData vesselData;
};
ReadResult()
: status(false)
{
}
};
private:
uint8_t rx_len;
byte buffer[256]; //address for temporary storage and parsing buffer
uint8_t structSize;
uint8_t rx_array_inx; //index for RX parsing buffer
uint8_t calc_CS; //calculated Chacksum
int id;
ReadResult::TypeOfPacket typeOfPacketProcessed;
public:
//This shit contains stuff borrowed from EasyTransfer lib
inline ReadResult KSPBoardReceiveData() {
ReadResult result;
if ((rx_len == 0)&&(Serial.available()>3)){
while(Serial.read()!= 0xBE) {
if (Serial.available() == 0)
return result;
}
if (Serial.read() == 0xEF){
rx_len = Serial.read();
id = Serial.read();
rx_array_inx = 1;
switch(id) {
case 0:
typeOfPacketProcessed = ReadResult::TypeOfPacket::HandShakePacket;
structSize = sizeof(HandShakePacket);
break;
case 1:
typeOfPacketProcessed = ReadResult::TypeOfPacket::VesselData;
structSize = sizeof(VesselData);
break;
}
}
//make sure the binary structs on both Arduinos are the same size.
if(rx_len != structSize){
rx_len = 0;
return result;
}
}
if(rx_len != 0){
while(Serial.available() && rx_array_inx <= rx_len){
buffer[rx_array_inx++] = Serial.read();
}
buffer[0] = id;
if(rx_len == (rx_array_inx-1)){
//seem to have got whole message
//last uint8_t is CS
calc_CS = rx_len;
for (int i = 0; i<rx_len; i++){
calc_CS^=buffer[i];
}
if(calc_CS == buffer[rx_array_inx-1]){//CS good
uint16_t * address;
switch(typeOfPacketProcessed) {
case ReadResult::TypeOfPacket::HandShakePacket:
address = reinterpret_cast<uint16_t*>(&result.handShakePacket);
break;
case ReadResult::TypeOfPacket::VesselData:
address = reinterpret_cast<uint16_t*>(&result.vesselData);
break;
}
memcpy(address, buffer, structSize);
rx_len = 0;
rx_array_inx = 1;
// Success
result.status = true;
result.typeOfPacket = typeOfPacketProcessed;
return result;
}
else {
//failed checksum, need to clear this out anyway
rx_len = 0;
rx_array_inx = 1;
return result;
}
}
}
return result;
}
inline void KSPBoardSendData(uint8_t * address, uint8_t len){
uint8_t CS = len;
Serial.write(0xBE);
Serial.write(0xEF);
Serial.write(len);
for(int i = 0; i<len; i++){
CS^=*(address+i);
Serial.write(*(address+i));
}
Serial.write(CS);
}
};
<|endoftext|> |
<commit_before>/*
* Sparsifiers.cpp
*
* Created on: 24.07.2014
* Author: Gerd Lindner
*/
#include "Sparsifiers.h"
#include "../edgescores/ChibaNishizekiTriangleEdgeScore.h"
#include "../edgescores/PrefixJaccardScore.h"
#include "SimmelianOverlapScore.h"
#include "MultiscaleScore.h"
#include "LocalSimilarityScore.h"
#include "RandomEdgeScore.h"
#include "GlobalThresholdFilter.h"
#include "../auxiliary/Random.h"
namespace NetworKit {
Sparsifier::Sparsifier(const Graph& inputGraph) : inputGraph(inputGraph) {
}
Graph Sparsifier::getGraph() {
if (!hasOutput) throw std::runtime_error("Error: run must be called first");
hasOutput = false;
return std::move(outputGraph);
}
SimmelianSparsifierNonParametric::SimmelianSparsifierNonParametric(const Graph& graph, double threshold) :
Sparsifier(graph), threshold(threshold) {}
void SimmelianSparsifierNonParametric::run() {
ChibaNishizekiTriangleEdgeScore triangleEdgeScore(inputGraph);
triangleEdgeScore.run();
std::vector<count> triangles = triangleEdgeScore.scores();
PrefixJaccardScore<count> jaccardScore(inputGraph, triangles);
jaccardScore.run();
std::vector<double> jaccard = jaccardScore.scores();
GlobalThresholdFilter filter(inputGraph, jaccard, threshold, true);
outputGraph = filter.calculate();
hasOutput = true;
}
SimmelianSparsifierParametric::SimmelianSparsifierParametric(const Graph& graph, int maxRank, int minOverlap) :
Sparsifier(graph), maxRank(maxRank), minOverlap(minOverlap) {}
void SimmelianSparsifierParametric::run() {
ChibaNishizekiTriangleEdgeScore triangleEdgeScore(inputGraph);
triangleEdgeScore.run();
std::vector<count> triangles = triangleEdgeScore.scores();
SimmelianOverlapScore overlapScore(inputGraph, triangles, maxRank);
overlapScore.run();
std::vector<double> overlap = overlapScore.scores();
GlobalThresholdFilter filter(inputGraph, overlap, minOverlap, true);
outputGraph = filter.calculate();
hasOutput = true;
}
MultiscaleSparsifier::MultiscaleSparsifier(const Graph& graph, double alpha) :
Sparsifier(graph), alpha(alpha) {}
void MultiscaleSparsifier::run() {
std::vector<double> weight(inputGraph.upperEdgeIdBound());
inputGraph.forEdges([&](node u, node v, edgeid eid) {
weight[eid] = inputGraph.weight(u, v);
});
MultiscaleScore multiscaleScorer(inputGraph, weight);
multiscaleScorer.run();
std::vector<double> multiscale = multiscaleScorer.scores();
GlobalThresholdFilter filter(inputGraph, multiscale, alpha, true);
outputGraph = filter.calculate();
hasOutput = true;
}
LocalSimilaritySparsifier::LocalSimilaritySparsifier(const Graph& graph, double e) :
Sparsifier(graph), e(e) {}
void LocalSimilaritySparsifier::run() {
ChibaNishizekiTriangleEdgeScore triangleEdgeScore(inputGraph);
triangleEdgeScore.run();
std::vector<count> triangles = triangleEdgeScore.scores();
LocalSimilarityScore localSimScore(inputGraph, triangles);
localSimScore.run();
std::vector<double> minExponent = localSimScore.scores();
GlobalThresholdFilter filter(inputGraph, minExponent, e, true);
outputGraph = filter.calculate();
hasOutput = true;
}
SimmelianMultiscaleSparsifier::SimmelianMultiscaleSparsifier(const Graph& graph, double alpha) :
Sparsifier(graph), alpha(alpha) {}
void SimmelianMultiscaleSparsifier::run() {
ChibaNishizekiTriangleEdgeScore triangleEdgeScore(inputGraph);
triangleEdgeScore.run();
std::vector<count> triangles = triangleEdgeScore.scores();
std::vector<double> triangles_d = std::vector<double>(triangles.begin(), triangles.end());
MultiscaleScore multiscaleScorer (inputGraph, triangles_d);
multiscaleScorer.run();
std::vector<double> multiscale = multiscaleScorer.scores();
GlobalThresholdFilter filter(inputGraph, multiscale, alpha, true);
outputGraph = filter.calculate();
hasOutput = true;
}
RandomSparsifier::RandomSparsifier(const Graph& graph, double ratio) :
Sparsifier(graph), ratio(ratio) {}
void RandomSparsifier::run() {
RandomEdgeScore randomScorer (inputGraph);
randomScorer.run();
std::vector<double> random = randomScorer.scores();
GlobalThresholdFilter filter(inputGraph, random, ratio, true);
outputGraph = filter.calculate();
hasOutput = true;
}
} /* namespace NetworKit */
<commit_msg>Fix performance bug in MultiscaleSparsifier<commit_after>/*
* Sparsifiers.cpp
*
* Created on: 24.07.2014
* Author: Gerd Lindner
*/
#include "Sparsifiers.h"
#include "../edgescores/ChibaNishizekiTriangleEdgeScore.h"
#include "../edgescores/PrefixJaccardScore.h"
#include "SimmelianOverlapScore.h"
#include "MultiscaleScore.h"
#include "LocalSimilarityScore.h"
#include "RandomEdgeScore.h"
#include "GlobalThresholdFilter.h"
#include "../auxiliary/Random.h"
namespace NetworKit {
Sparsifier::Sparsifier(const Graph& inputGraph) : inputGraph(inputGraph) {
}
Graph Sparsifier::getGraph() {
if (!hasOutput) throw std::runtime_error("Error: run must be called first");
hasOutput = false;
return std::move(outputGraph);
}
SimmelianSparsifierNonParametric::SimmelianSparsifierNonParametric(const Graph& graph, double threshold) :
Sparsifier(graph), threshold(threshold) {}
void SimmelianSparsifierNonParametric::run() {
ChibaNishizekiTriangleEdgeScore triangleEdgeScore(inputGraph);
triangleEdgeScore.run();
std::vector<count> triangles = triangleEdgeScore.scores();
PrefixJaccardScore<count> jaccardScore(inputGraph, triangles);
jaccardScore.run();
std::vector<double> jaccard = jaccardScore.scores();
GlobalThresholdFilter filter(inputGraph, jaccard, threshold, true);
outputGraph = filter.calculate();
hasOutput = true;
}
SimmelianSparsifierParametric::SimmelianSparsifierParametric(const Graph& graph, int maxRank, int minOverlap) :
Sparsifier(graph), maxRank(maxRank), minOverlap(minOverlap) {}
void SimmelianSparsifierParametric::run() {
ChibaNishizekiTriangleEdgeScore triangleEdgeScore(inputGraph);
triangleEdgeScore.run();
std::vector<count> triangles = triangleEdgeScore.scores();
SimmelianOverlapScore overlapScore(inputGraph, triangles, maxRank);
overlapScore.run();
std::vector<double> overlap = overlapScore.scores();
GlobalThresholdFilter filter(inputGraph, overlap, minOverlap, true);
outputGraph = filter.calculate();
hasOutput = true;
}
MultiscaleSparsifier::MultiscaleSparsifier(const Graph& graph, double alpha) :
Sparsifier(graph), alpha(alpha) {}
void MultiscaleSparsifier::run() {
std::vector<double> weight(inputGraph.upperEdgeIdBound());
inputGraph.forEdges([&](node u, node v, edgeweight w, edgeid eid) {
weight[eid] = w;
});
MultiscaleScore multiscaleScorer(inputGraph, weight);
multiscaleScorer.run();
std::vector<double> multiscale = multiscaleScorer.scores();
GlobalThresholdFilter filter(inputGraph, multiscale, alpha, true);
outputGraph = filter.calculate();
hasOutput = true;
}
LocalSimilaritySparsifier::LocalSimilaritySparsifier(const Graph& graph, double e) :
Sparsifier(graph), e(e) {}
void LocalSimilaritySparsifier::run() {
ChibaNishizekiTriangleEdgeScore triangleEdgeScore(inputGraph);
triangleEdgeScore.run();
std::vector<count> triangles = triangleEdgeScore.scores();
LocalSimilarityScore localSimScore(inputGraph, triangles);
localSimScore.run();
std::vector<double> minExponent = localSimScore.scores();
GlobalThresholdFilter filter(inputGraph, minExponent, e, true);
outputGraph = filter.calculate();
hasOutput = true;
}
SimmelianMultiscaleSparsifier::SimmelianMultiscaleSparsifier(const Graph& graph, double alpha) :
Sparsifier(graph), alpha(alpha) {}
void SimmelianMultiscaleSparsifier::run() {
ChibaNishizekiTriangleEdgeScore triangleEdgeScore(inputGraph);
triangleEdgeScore.run();
std::vector<count> triangles = triangleEdgeScore.scores();
std::vector<double> triangles_d = std::vector<double>(triangles.begin(), triangles.end());
MultiscaleScore multiscaleScorer (inputGraph, triangles_d);
multiscaleScorer.run();
std::vector<double> multiscale = multiscaleScorer.scores();
GlobalThresholdFilter filter(inputGraph, multiscale, alpha, true);
outputGraph = filter.calculate();
hasOutput = true;
}
RandomSparsifier::RandomSparsifier(const Graph& graph, double ratio) :
Sparsifier(graph), ratio(ratio) {}
void RandomSparsifier::run() {
RandomEdgeScore randomScorer (inputGraph);
randomScorer.run();
std::vector<double> random = randomScorer.scores();
GlobalThresholdFilter filter(inputGraph, random, ratio, true);
outputGraph = filter.calculate();
hasOutput = true;
}
} /* namespace NetworKit */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013-2015 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "engineuwsgi.h"
#include <Cutelyst/application.h>
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QPluginLoader>
#include <QFileInfo>
#include <QDir>
#define CUTELYST_MODIFIER1 0
using namespace Cutelyst;
struct uwsgi_cutelyst {
char *app;
int reload;
} options;
static QList<uWSGI *> *coreEngines = nullptr;
void cuteOutput(QtMsgType, const QMessageLogContext &, const QString &);
void uwsgi_cutelyst_loop(void);
#ifdef UWSGI_GO_CHEAP_CODE
static void fsmon_reload(struct uwsgi_fsmon *fs);
#endif
/**
* This function is called as soon as
* the plugin is loaded
*/
void uwsgi_cutelyst_on_load()
{
uwsgi_register_loop( (char *) "CutelystQtLoop", uwsgi_cutelyst_loop);
// Get the uwsgi options
QVariantHash opts;
for (int i = 0; i < uwsgi.exported_opts_cnt; i++) {
const QString &key = QString::fromLatin1(uwsgi.exported_opts[i]->key);
if (uwsgi.exported_opts[i]->value == NULL) {
opts.insertMulti(key, QVariant());
} else {
opts.insertMulti(key, QString::fromLatin1(uwsgi.exported_opts[i]->value));
}
}
// if the path is relative build a path
// relative to the current working directory
QDir cwd(QString::fromLatin1(uwsgi.cwd));
// Set the configuration env
QVariantHash::ConstIterator it = opts.constFind(QStringLiteral("ini"));
if (it != opts.constEnd()) {
QString config = cwd.absoluteFilePath(it.value().toString());
qputenv("CUTELYST_CONFIG", config.toUtf8());
if (!qEnvironmentVariableIsSet("QT_LOGGING_CONF")) {
qputenv("QT_LOGGING_CONF", config.toUtf8());
}
}
QCoreApplication *app = new QCoreApplication(uwsgi.argc, uwsgi.argv);
app->setProperty("UWSGI_OPTS", opts);
if (qEnvironmentVariableIsSet("CUTELYST_UWSGI_LOG")) {
qInstallMessageHandler(cuteOutput);
}
if (qEnvironmentVariableIsEmpty("QT_MESSAGE_PATTERN")) {
qputenv("QT_MESSAGE_PATTERN",
"%{category}[%{if-debug}debug%{endif}%{if-info}info%{endif}%{if-warning}warn%{endif}%{if-critical}crit%{endif}%{if-fatal}fatal%{endif}] %{message}");
}
}
int uwsgi_cutelyst_init()
{
uwsgi_log("Initializing Cutelyst plugin\n");
// if the path is relative build a path
// relative to the current working directory
QDir cwd(QString::fromLocal8Bit(uwsgi.cwd));
QString path(QString::fromLocal8Bit(options.app));
if (path.isEmpty()) {
uwsgi_log("Cutelyst application name or path was not set\n");
exit(1);
}
path = cwd.absoluteFilePath(path);
#ifdef UWSGI_GO_CHEAP_CODE
if (options.reload) {
// Register application auto reload
char *file = qstrdup(path.toUtf8().constData());
uwsgi_register_fsmon(file, fsmon_reload, NULL);
}
#endif // UWSGI_GO_CHEAP_CODE
uwsgi.loop = (char *) "CutelystQtLoop";
coreEngines = new QList<uWSGI *>();
return 0;
}
void uwsgi_cutelyst_post_fork()
{
Q_FOREACH (uWSGI *engine, *coreEngines) {
engine->setWorkerId(uwsgi.mywid - 1);
if (engine->thread() != qApp->thread()) {
engine->thread()->start();
} else {
Q_EMIT engine->postFork();
}
}
}
int uwsgi_cutelyst_request(struct wsgi_request *wsgi_req)
{
// empty request ?
if (!wsgi_req->uh->pktsize) {
qCDebug(CUTELYST_UWSGI) << "Empty request. skip.";
return -1;
}
// get uwsgi variables
if (uwsgi_parse_vars(wsgi_req)) {
qCDebug(CUTELYST_UWSGI) << "Invalid request. skip.";
return -1;
}
coreEngines->at(wsgi_req->async_id)->processRequest(wsgi_req);
return UWSGI_OK;
}
#ifdef UWSGI_GO_CHEAP_CODE // Actually we only need uwsgi 2.0.1
static void fsmon_reload(struct uwsgi_fsmon *fs)
{
qCDebug(CUTELYST_UWSGI) << "Reloading application due to file change";
QFileInfo fileInfo(QString::fromLocal8Bit(fs->path));
int count = 0;
// Ugly hack to wait for 2 seconds for the file to be filled
while (fileInfo.size() == 0 && count < 10) {
++count;
qCDebug(CUTELYST_UWSGI) << "Sleeping as the application file is empty" << count;
usleep(200 * 1000);
fileInfo.refresh();
}
uwsgi_reload(uwsgi.argv);
}
#endif // UWSGI_GO_CHEAP_CODE
/**
* This function is called when the child process is exiting
*/
void uwsgi_cutelyst_atexit()
{
qCDebug(CUTELYST_UWSGI) << "Child process finishing:" << QCoreApplication::applicationPid();
Q_FOREACH (uWSGI *engine, *coreEngines) {
engine->stop();
}
qDeleteAll(*coreEngines);
delete coreEngines;
qCDebug(CUTELYST_UWSGI) << "Child process finished:" << QCoreApplication::applicationPid();
}
void uwsgi_cutelyst_init_apps()
{
const QString &applicationName = QCoreApplication::applicationName();
qCDebug(CUTELYST_UWSGI) << "Cutelyst loading application:" << options.app;
// if the path is relative build a path
// relative to the current working directory
QDir cwd(QString::fromLocal8Bit(uwsgi.cwd));
QString path = cwd.absoluteFilePath(QString::fromLocal8Bit(options.app));
QPluginLoader *loader = new QPluginLoader(path);
if (!loader->load()) {
qCCritical(CUTELYST_UWSGI) << "Could not load application:" << loader->errorString();
exit(1);
}
QObject *instance = loader->instance();
if (!instance) {
qCCritical(CUTELYST_UWSGI) << "Could not get a QObject instance: %s\n" << loader->errorString();
exit(1);
}
Application *app = qobject_cast<Application *>(instance);
if (!app) {
qCCritical(CUTELYST_UWSGI) << "Could not cast Cutelyst::Application from instance: %s\n" << loader->errorString();
exit(1);
}
// Sets the application name with the name from our library
if (QCoreApplication::applicationName() == applicationName) {
QCoreApplication::setApplicationName(QString::fromLatin1(app->metaObject()->className()));
}
qCDebug(CUTELYST_UWSGI) << "Loaded application:" << QCoreApplication::applicationName();
QVariantHash opts = qApp->property("UWSGI_OPTS").toHash();
uWSGI *mainEngine = new uWSGI(opts, app);
if (!mainEngine->initApplication(app, false)) {
qCCritical(CUTELYST_UWSGI) << "Failed to init application.";
exit(1);
}
uWSGI *engine = mainEngine;
for (int i = 0; i < uwsgi.cores; ++i) {
// Create the wsgi_request structure
struct wsgi_request *wsgi_req = new wsgi_request;
memset(wsgi_req, 0, sizeof(struct wsgi_request));
wsgi_req->async_id = i;
// Create the desired threads
// i > 0 the main thread counts as one thread
if (uwsgi.threads > 1) {
QThread *thread = new QThread(qApp);
// reuse the main engine
if (i != 0) {
// The engine can't have a parent otherwise
// we can't move it
engine = new uWSGI(opts, app);
}
// the request must be added before moving threads
engine->addUnusedRequest(wsgi_req);
// Move to the new thread
engine->setThread(thread);
if (i != 0) {
// Post fork might fail when on threaded mode
QObject::connect(engine, &uWSGI::engineDisabled,
mainEngine, &uWSGI::reuseEngineRequests, Qt::QueuedConnection);
}
} else {
engine->addUnusedRequest(wsgi_req);
}
engine->setWorkerCore(i);
if (!coreEngines->contains(engine)) {
coreEngines->append(engine);
}
}
// register a new app under a specific "mountpoint"
uwsgi_add_app(1, CUTELYST_MODIFIER1, (char *) "", 0, NULL, NULL);
delete loader;
if (uwsgi.lazy || uwsgi.lazy_apps) {
// Make sure we start listening on lazy mode
uwsgi_cutelyst_post_fork();
}
}
void uwsgi_cutelyst_watch_signal(int signalFD)
{
QSocketNotifier *socketNotifier = new QSocketNotifier(signalFD, QSocketNotifier::Read);
QObject::connect(socketNotifier, &QSocketNotifier::activated,
[=](int fd) {
socketNotifier->setEnabled(false);
uwsgi_receive_signal(fd, (char *) "worker", uwsgi.mywid);
socketNotifier->setEnabled(true);
});
}
void uwsgi_cutelyst_loop()
{
// ensure SIGPIPE is ignored
signal(SIGPIPE, SIG_IGN);
// FIX for some reason this is not being set by UWSGI
uwsgi.wait_read_hook = uwsgi_simple_wait_read_hook;
// monitor signals
if (uwsgi.signal_socket > -1) {
uwsgi_cutelyst_watch_signal(uwsgi.signal_socket);
uwsgi_cutelyst_watch_signal(uwsgi.my_signal_socket);
}
// start the qt event loop
qApp->exec();
}
void cuteOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
uwsgi_log("%s[debug] %s\n", context.category, localMsg.constData());
break;
case QtWarningMsg:
uwsgi_log("%s[warn] %s\n", context.category, localMsg.constData());
break;
case QtCriticalMsg:
uwsgi_log("%s[crit] %s\n", context.category, localMsg.constData());
break;
case QtFatalMsg:
uwsgi_log("%s[fatal] %s\n", context.category, localMsg.constData());
abort();
case QtInfoMsg:
uwsgi_log("%s[info] %s\n", context.category, localMsg.constData());
break;
}
}
struct uwsgi_option uwsgi_cutelyst_options[] = {
{const_cast<char *>("cutelyst-app"), required_argument, 0, const_cast<char *>("loads the Cutelyst Application"), uwsgi_opt_set_str, &options.app, 0},
{const_cast<char *>("cutelyst-reload"), no_argument, 0, const_cast<char *>("auto reloads the application when app file changes"), uwsgi_opt_true, &options.reload, 0},
{0, 0, 0, 0, 0, 0, 0},
};
struct uwsgi_plugin cutelyst_plugin = {
"cutelyst", // name
0, // alias
0, // modifier1
0, // data
uwsgi_cutelyst_on_load, // on_load
uwsgi_cutelyst_init, // init
0, // post_init
uwsgi_cutelyst_post_fork, // post_fork
uwsgi_cutelyst_options, // options
0, // enable threads
0, // init thread
uwsgi_cutelyst_request, // request
0, // after request
0, // pre init apps
uwsgi_cutelyst_init_apps, // init apps
0, // post init apps
0, // (*fixup) (void);
0, //void (*master_fixup) (int);
0, // master_cycle) (void);
0, //int (*mount_app) (char *, char *);
0, //int (*manage_udp) (char *, int, char *, int);
0, //void (*suspend) (struct wsgi_request *);
0, //void (*resume) (struct wsgi_request *);
0, //void (*harakiri) (int);
0, //void (*hijack_worker) (void);
0, //void (*spooler_init) (void);
uwsgi_cutelyst_atexit, // atexit
};
<commit_msg>uwsgi: Remove --cutelyst-reload option<commit_after>/*
* Copyright (C) 2013-2015 Daniel Nicoletti <dantti12@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "engineuwsgi.h"
#include <Cutelyst/application.h>
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QPluginLoader>
#include <QFileInfo>
#include <QDir>
#define CUTELYST_MODIFIER1 0
using namespace Cutelyst;
struct uwsgi_cutelyst {
char *app;
} options;
static QList<uWSGI *> *coreEngines = nullptr;
void cuteOutput(QtMsgType, const QMessageLogContext &, const QString &);
void uwsgi_cutelyst_loop(void);
/**
* This function is called as soon as
* the plugin is loaded
*/
void uwsgi_cutelyst_on_load()
{
uwsgi_register_loop( (char *) "CutelystQtLoop", uwsgi_cutelyst_loop);
// Get the uwsgi options
QVariantHash opts;
for (int i = 0; i < uwsgi.exported_opts_cnt; i++) {
const QString &key = QString::fromLatin1(uwsgi.exported_opts[i]->key);
if (uwsgi.exported_opts[i]->value == NULL) {
opts.insertMulti(key, QVariant());
} else {
opts.insertMulti(key, QString::fromLatin1(uwsgi.exported_opts[i]->value));
}
}
// if the path is relative build a path
// relative to the current working directory
QDir cwd(QString::fromLatin1(uwsgi.cwd));
// Set the configuration env
QVariantHash::ConstIterator it = opts.constFind(QStringLiteral("ini"));
if (it != opts.constEnd()) {
QString config = cwd.absoluteFilePath(it.value().toString());
qputenv("CUTELYST_CONFIG", config.toUtf8());
if (!qEnvironmentVariableIsSet("QT_LOGGING_CONF")) {
qputenv("QT_LOGGING_CONF", config.toUtf8());
}
}
QCoreApplication *app = new QCoreApplication(uwsgi.argc, uwsgi.argv);
app->setProperty("UWSGI_OPTS", opts);
if (qEnvironmentVariableIsSet("CUTELYST_UWSGI_LOG")) {
qInstallMessageHandler(cuteOutput);
}
if (qEnvironmentVariableIsEmpty("QT_MESSAGE_PATTERN")) {
qputenv("QT_MESSAGE_PATTERN",
"%{category}[%{if-debug}debug%{endif}%{if-info}info%{endif}%{if-warning}warn%{endif}%{if-critical}crit%{endif}%{if-fatal}fatal%{endif}] %{message}");
}
}
int uwsgi_cutelyst_init()
{
uwsgi_log("Initializing Cutelyst plugin\n");
// if the path is relative build a path
// relative to the current working directory
QDir cwd(QString::fromLocal8Bit(uwsgi.cwd));
QString path(QString::fromLocal8Bit(options.app));
if (path.isEmpty()) {
uwsgi_log("Cutelyst application name or path was not set\n");
exit(1);
}
path = cwd.absoluteFilePath(path);
uwsgi.loop = (char *) "CutelystQtLoop";
coreEngines = new QList<uWSGI *>();
return 0;
}
void uwsgi_cutelyst_post_fork()
{
Q_FOREACH (uWSGI *engine, *coreEngines) {
engine->setWorkerId(uwsgi.mywid - 1);
if (engine->thread() != qApp->thread()) {
engine->thread()->start();
} else {
Q_EMIT engine->postFork();
}
}
}
int uwsgi_cutelyst_request(struct wsgi_request *wsgi_req)
{
// empty request ?
if (!wsgi_req->uh->pktsize) {
qCDebug(CUTELYST_UWSGI) << "Empty request. skip.";
return -1;
}
// get uwsgi variables
if (uwsgi_parse_vars(wsgi_req)) {
qCDebug(CUTELYST_UWSGI) << "Invalid request. skip.";
return -1;
}
coreEngines->at(wsgi_req->async_id)->processRequest(wsgi_req);
return UWSGI_OK;
}
/**
* This function is called when the child process is exiting
*/
void uwsgi_cutelyst_atexit()
{
qCDebug(CUTELYST_UWSGI) << "Child process finishing:" << QCoreApplication::applicationPid();
Q_FOREACH (uWSGI *engine, *coreEngines) {
engine->stop();
}
qDeleteAll(*coreEngines);
delete coreEngines;
qCDebug(CUTELYST_UWSGI) << "Child process finished:" << QCoreApplication::applicationPid();
}
void uwsgi_cutelyst_init_apps()
{
const QString &applicationName = QCoreApplication::applicationName();
qCDebug(CUTELYST_UWSGI) << "Cutelyst loading application:" << options.app;
// if the path is relative build a path
// relative to the current working directory
QDir cwd(QString::fromLocal8Bit(uwsgi.cwd));
QString path = cwd.absoluteFilePath(QString::fromLocal8Bit(options.app));
QPluginLoader *loader = new QPluginLoader(path);
if (!loader->load()) {
qCCritical(CUTELYST_UWSGI) << "Could not load application:" << loader->errorString();
exit(1);
}
QObject *instance = loader->instance();
if (!instance) {
qCCritical(CUTELYST_UWSGI) << "Could not get a QObject instance: %s\n" << loader->errorString();
exit(1);
}
Application *app = qobject_cast<Application *>(instance);
if (!app) {
qCCritical(CUTELYST_UWSGI) << "Could not cast Cutelyst::Application from instance: %s\n" << loader->errorString();
exit(1);
}
// Sets the application name with the name from our library
if (QCoreApplication::applicationName() == applicationName) {
QCoreApplication::setApplicationName(QString::fromLatin1(app->metaObject()->className()));
}
qCDebug(CUTELYST_UWSGI) << "Loaded application:" << QCoreApplication::applicationName();
QVariantHash opts = qApp->property("UWSGI_OPTS").toHash();
uWSGI *mainEngine = new uWSGI(opts, app);
if (!mainEngine->initApplication(app, false)) {
qCCritical(CUTELYST_UWSGI) << "Failed to init application.";
exit(1);
}
uWSGI *engine = mainEngine;
for (int i = 0; i < uwsgi.cores; ++i) {
// Create the wsgi_request structure
struct wsgi_request *wsgi_req = new wsgi_request;
memset(wsgi_req, 0, sizeof(struct wsgi_request));
wsgi_req->async_id = i;
// Create the desired threads
// i > 0 the main thread counts as one thread
if (uwsgi.threads > 1) {
QThread *thread = new QThread(qApp);
// reuse the main engine
if (i != 0) {
// The engine can't have a parent otherwise
// we can't move it
engine = new uWSGI(opts, app);
}
// the request must be added before moving threads
engine->addUnusedRequest(wsgi_req);
// Move to the new thread
engine->setThread(thread);
if (i != 0) {
// Post fork might fail when on threaded mode
QObject::connect(engine, &uWSGI::engineDisabled,
mainEngine, &uWSGI::reuseEngineRequests, Qt::QueuedConnection);
}
} else {
engine->addUnusedRequest(wsgi_req);
}
engine->setWorkerCore(i);
if (!coreEngines->contains(engine)) {
coreEngines->append(engine);
}
}
// register a new app under a specific "mountpoint"
uwsgi_add_app(1, CUTELYST_MODIFIER1, (char *) "", 0, NULL, NULL);
delete loader;
if (uwsgi.lazy || uwsgi.lazy_apps) {
// Make sure we start listening on lazy mode
uwsgi_cutelyst_post_fork();
}
}
void uwsgi_cutelyst_watch_signal(int signalFD)
{
QSocketNotifier *socketNotifier = new QSocketNotifier(signalFD, QSocketNotifier::Read);
QObject::connect(socketNotifier, &QSocketNotifier::activated,
[=](int fd) {
socketNotifier->setEnabled(false);
uwsgi_receive_signal(fd, (char *) "worker", uwsgi.mywid);
socketNotifier->setEnabled(true);
});
}
void uwsgi_cutelyst_loop()
{
// ensure SIGPIPE is ignored
signal(SIGPIPE, SIG_IGN);
// FIX for some reason this is not being set by UWSGI
uwsgi.wait_read_hook = uwsgi_simple_wait_read_hook;
// monitor signals
if (uwsgi.signal_socket > -1) {
uwsgi_cutelyst_watch_signal(uwsgi.signal_socket);
uwsgi_cutelyst_watch_signal(uwsgi.my_signal_socket);
}
// start the qt event loop
qApp->exec();
}
void cuteOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
uwsgi_log("%s[debug] %s\n", context.category, localMsg.constData());
break;
case QtWarningMsg:
uwsgi_log("%s[warn] %s\n", context.category, localMsg.constData());
break;
case QtCriticalMsg:
uwsgi_log("%s[crit] %s\n", context.category, localMsg.constData());
break;
case QtFatalMsg:
uwsgi_log("%s[fatal] %s\n", context.category, localMsg.constData());
abort();
case QtInfoMsg:
uwsgi_log("%s[info] %s\n", context.category, localMsg.constData());
break;
}
}
struct uwsgi_option uwsgi_cutelyst_options[] = {
{const_cast<char *>("cutelyst-app"), required_argument, 0, const_cast<char *>("loads the Cutelyst Application"), uwsgi_opt_set_str, &options.app, 0},
{0, 0, 0, 0, 0, 0, 0},
};
struct uwsgi_plugin cutelyst_plugin = {
"cutelyst", // name
0, // alias
0, // modifier1
0, // data
uwsgi_cutelyst_on_load, // on_load
uwsgi_cutelyst_init, // init
0, // post_init
uwsgi_cutelyst_post_fork, // post_fork
uwsgi_cutelyst_options, // options
0, // enable threads
0, // init thread
uwsgi_cutelyst_request, // request
0, // after request
0, // pre init apps
uwsgi_cutelyst_init_apps, // init apps
0, // post init apps
0, // (*fixup) (void);
0, //void (*master_fixup) (int);
0, // master_cycle) (void);
0, //int (*mount_app) (char *, char *);
0, //int (*manage_udp) (char *, int, char *, int);
0, //void (*suspend) (struct wsgi_request *);
0, //void (*resume) (struct wsgi_request *);
0, //void (*harakiri) (int);
0, //void (*hijack_worker) (void);
0, //void (*spooler_init) (void);
uwsgi_cutelyst_atexit, // atexit
};
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_OPERATORS_RX_OBSERVE_ON_HPP)
#define RXCPP_OPERATORS_RX_OBSERVE_ON_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace operators {
namespace detail {
template<class T, class Coordination>
struct observe_on
{
typedef typename std::decay<T>::type source_value_type;
typedef typename std::decay<Coordination>::type coordination_type;
typedef typename coordination_type::coordinator_type coordinator_type;
coordination_type coordination;
observe_on(coordination_type cn)
: coordination(std::move(cn))
{
}
template<class Subscriber>
struct observe_on_observer : public observer_base<source_value_type>
{
typedef observe_on_observer<Subscriber> this_type;
typedef observer_base<source_value_type> base_type;
typedef typename base_type::value_type value_type;
typedef typename std::decay<Subscriber>::type dest_type;
typedef observer<value_type, this_type> observer_type;
typedef rxn::notification<T> notification_type;
typedef typename notification_type::type base_notification_type;
typedef std::queue<base_notification_type> queue_type;
struct mode
{
enum type {
Invalid = 0,
Processing,
Empty,
Disposed
};
};
struct observe_on_state : std::enable_shared_from_this<observe_on_state>
{
mutable std::mutex lock;
mutable queue_type queue;
mutable queue_type drain_queue;
composite_subscription lifetime;
rxsc::worker processor;
mutable typename mode::type current;
coordinator_type coordinator;
dest_type destination;
observe_on_state(dest_type d, coordinator_type coor, composite_subscription cs)
: lifetime(std::move(cs))
, current(mode::Empty)
, coordinator(std::move(coor))
, destination(std::move(d))
{
}
void ensure_processing(std::unique_lock<std::mutex>& guard) const {
if (!guard.owns_lock()) {
abort();
}
if (current == mode::Empty) {
current = mode::Processing;
auto keepAlive = this->shared_from_this();
auto drain = [keepAlive, this](const rxsc::schedulable& self){
try {
if (drain_queue.empty() || !destination.is_subscribed()) {
std::unique_lock<std::mutex> guard(lock);
if (!destination.is_subscribed() ||
(!lifetime.is_subscribed() && queue.empty())) {
current = mode::Disposed;
using std::swap;
queue_type expired;
swap(expired, queue);
guard.unlock();
lifetime.unsubscribe();
destination.unsubscribe();
return;
}
if (queue.empty()) {
current = mode::Empty;
return;
}
using std::swap;
swap(queue, drain_queue);
}
auto notification = std::move(drain_queue.front());
drain_queue.pop();
notification->accept(destination);
self();
} catch(...) {
destination.on_error(std::current_exception());
std::unique_lock<std::mutex> guard(lock);
current = mode::Empty;
}
};
auto selectedDrain = on_exception(
[&](){return coordinator.act(drain);},
destination);
if (selectedDrain.empty()) {
return;
}
auto processor = coordinator.get_worker();
processor.schedule(lifetime, selectedDrain.get());
}
}
};
std::shared_ptr<observe_on_state> state;
observe_on_observer(dest_type d, coordinator_type coor, composite_subscription cs)
: state(std::make_shared<observe_on_state>(std::move(d), std::move(coor), std::move(cs)))
{
}
void on_next(source_value_type v) const {
if (state->lifetime.is_subscribed()) {
std::unique_lock<std::mutex> guard(state->lock);
state->queue.push(notification_type::on_next(std::move(v)));
state->ensure_processing(guard);
}
}
void on_error(std::exception_ptr e) const {
if (state->lifetime.is_subscribed()) {
std::unique_lock<std::mutex> guard(state->lock);
state->queue.push(notification_type::on_error(e));
state->ensure_processing(guard);
}
}
void on_completed() const {
if (state->lifetime.is_subscribed()) {
std::unique_lock<std::mutex> guard(state->lock);
state->queue.push(notification_type::on_completed());
state->ensure_processing(guard);
}
}
static subscriber<value_type, this_type> make(dest_type d, coordination_type cn, composite_subscription cs = composite_subscription()) {
auto coor = cn.create_coordinator(d.get_subscription());
d.add(cs);
this_type o(d, std::move(coor), cs);
auto keepAlive = o.state;
cs.add([keepAlive](){
std::unique_lock<std::mutex> guard(keepAlive->lock);
keepAlive->ensure_processing(guard);
});
return make_subscriber<value_type>(cs, std::move(o));
}
};
template<class Subscriber>
auto operator()(Subscriber dest) const
-> decltype(observe_on_observer<decltype(dest.as_dynamic())>::make(dest.as_dynamic(), coordination)) {
return observe_on_observer<decltype(dest.as_dynamic())>::make(dest.as_dynamic(), coordination);
}
};
template<class Coordination>
class observe_on_factory
{
typedef typename std::decay<Coordination>::type coordination_type;
coordination_type coordination;
public:
observe_on_factory(coordination_type cn) : coordination(std::move(cn)) {}
template<class Observable>
auto operator()(Observable&& source)
-> decltype(source.lift(observe_on<typename std::decay<Observable>::type::value_type, coordination_type>(coordination))) {
return source.lift(observe_on<typename std::decay<Observable>::type::value_type, coordination_type>(coordination));
}
};
}
template<class Coordination>
auto observe_on(Coordination cn)
-> detail::observe_on_factory<Coordination> {
return detail::observe_on_factory<Coordination>(std::move(cn));
}
}
class observe_on_one_worker : public coordination_base
{
rxsc::scheduler factory;
class input_type
{
rxsc::worker controller;
rxsc::scheduler factory;
identity_one_worker coordination;
public:
explicit input_type(rxsc::worker w)
: controller(w)
, factory(rxsc::make_same_worker(w))
, coordination(factory)
{
}
inline rxsc::worker get_worker() const {
return controller;
}
inline rxsc::scheduler get_scheduler() const {
return factory;
}
inline rxsc::scheduler::clock_type::time_point now() const {
return factory.now();
}
template<class Observable>
auto in(Observable o) const
-> decltype(o.observe_on(coordination)) {
return o.observe_on(coordination);
}
template<class Subscriber>
auto out(Subscriber s) const
-> Subscriber {
return std::move(s);
}
template<class F>
auto act(F f) const
-> F {
return std::move(f);
}
};
public:
explicit observe_on_one_worker(rxsc::scheduler sc) : factory(sc) {}
typedef coordinator<input_type> coordinator_type;
inline rxsc::scheduler::clock_type::time_point now() const {
return factory.now();
}
inline coordinator_type create_coordinator(composite_subscription cs = composite_subscription()) const {
auto w = factory.create_worker(std::move(cs));
return coordinator_type(input_type(std::move(w)));
}
};
inline observe_on_one_worker observe_on_event_loop() {
static observe_on_one_worker r(rxsc::make_event_loop());
return r;
}
inline observe_on_one_worker observe_on_new_thread() {
static observe_on_one_worker r(rxsc::make_new_thread());
return r;
}
}
#endif
<commit_msg>fix deadlock, error and dispose<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_OPERATORS_RX_OBSERVE_ON_HPP)
#define RXCPP_OPERATORS_RX_OBSERVE_ON_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace operators {
namespace detail {
template<class T, class Coordination>
struct observe_on
{
typedef typename std::decay<T>::type source_value_type;
typedef typename std::decay<Coordination>::type coordination_type;
typedef typename coordination_type::coordinator_type coordinator_type;
coordination_type coordination;
observe_on(coordination_type cn)
: coordination(std::move(cn))
{
}
template<class Subscriber>
struct observe_on_observer : public observer_base<source_value_type>
{
typedef observe_on_observer<Subscriber> this_type;
typedef observer_base<source_value_type> base_type;
typedef typename base_type::value_type value_type;
typedef typename std::decay<Subscriber>::type dest_type;
typedef observer<value_type, this_type> observer_type;
typedef rxn::notification<T> notification_type;
typedef typename notification_type::type base_notification_type;
typedef std::queue<base_notification_type> queue_type;
struct mode
{
enum type {
Invalid = 0,
Processing,
Empty,
Disposed,
Errored
};
};
struct observe_on_state : std::enable_shared_from_this<observe_on_state>
{
mutable std::mutex lock;
mutable queue_type queue;
mutable queue_type drain_queue;
composite_subscription lifetime;
rxsc::worker processor;
mutable typename mode::type current;
coordinator_type coordinator;
dest_type destination;
observe_on_state(dest_type d, coordinator_type coor, composite_subscription cs)
: lifetime(std::move(cs))
, current(mode::Empty)
, coordinator(std::move(coor))
, destination(std::move(d))
{
}
void ensure_processing(std::unique_lock<std::mutex>& guard) const {
if (!guard.owns_lock()) {
abort();
}
if (current == mode::Empty) {
current = mode::Processing;
auto keepAlive = this->shared_from_this();
auto drain = [keepAlive, this](const rxsc::schedulable& self){
using std::swap;
try {
if (drain_queue.empty() || !destination.is_subscribed()) {
std::unique_lock<std::mutex> guard(lock);
if (!destination.is_subscribed() ||
(!lifetime.is_subscribed() && queue.empty() && drain_queue.empty())) {
current = mode::Disposed;
queue_type expired;
swap(expired, queue);
guard.unlock();
lifetime.unsubscribe();
destination.unsubscribe();
return;
}
if (drain_queue.empty()) {
if (queue.empty()) {
current = mode::Empty;
return;
}
swap(queue, drain_queue);
}
}
auto notification = std::move(drain_queue.front());
drain_queue.pop();
notification->accept(destination);
self();
} catch(...) {
destination.on_error(std::current_exception());
std::unique_lock<std::mutex> guard(lock);
current = mode::Errored;
queue_type expired;
swap(expired, queue);
}
};
auto selectedDrain = on_exception(
[&](){return coordinator.act(drain);},
destination);
if (selectedDrain.empty()) {
std::unique_lock<std::mutex> guard(lock);
current = mode::Errored;
using std::swap;
queue_type expired;
swap(expired, queue);
return;
}
auto processor = coordinator.get_worker();
RXCPP_UNWIND_AUTO([&](){guard.lock();});
guard.unlock();
processor.schedule(selectedDrain.get());
}
}
};
std::shared_ptr<observe_on_state> state;
observe_on_observer(dest_type d, coordinator_type coor, composite_subscription cs)
: state(std::make_shared<observe_on_state>(std::move(d), std::move(coor), std::move(cs)))
{
}
void on_next(source_value_type v) const {
std::unique_lock<std::mutex> guard(state->lock);
state->queue.push(notification_type::on_next(std::move(v)));
state->ensure_processing(guard);
}
void on_error(std::exception_ptr e) const {
std::unique_lock<std::mutex> guard(state->lock);
state->queue.push(notification_type::on_error(e));
state->ensure_processing(guard);
}
void on_completed() const {
std::unique_lock<std::mutex> guard(state->lock);
state->queue.push(notification_type::on_completed());
state->ensure_processing(guard);
}
static subscriber<value_type, this_type> make(dest_type d, coordination_type cn, composite_subscription cs = composite_subscription()) {
auto coor = cn.create_coordinator(d.get_subscription());
d.add(cs);
this_type o(d, std::move(coor), cs);
auto keepAlive = o.state;
cs.add([keepAlive](){
std::unique_lock<std::mutex> guard(keepAlive->lock);
if (keepAlive->queue.empty() && keepAlive->current == mode::Empty && keepAlive->destination.is_subscribed()) {
keepAlive->current = mode::Disposed;
keepAlive->destination.unsubscribe();
}
});
return make_subscriber<value_type>(cs, std::move(o));
}
};
template<class Subscriber>
auto operator()(Subscriber dest) const
-> decltype(observe_on_observer<decltype(dest.as_dynamic())>::make(dest.as_dynamic(), coordination)) {
return observe_on_observer<decltype(dest.as_dynamic())>::make(dest.as_dynamic(), coordination);
}
};
template<class Coordination>
class observe_on_factory
{
typedef typename std::decay<Coordination>::type coordination_type;
coordination_type coordination;
public:
observe_on_factory(coordination_type cn) : coordination(std::move(cn)) {}
template<class Observable>
auto operator()(Observable&& source)
-> decltype(source.lift(observe_on<typename std::decay<Observable>::type::value_type, coordination_type>(coordination))) {
return source.lift(observe_on<typename std::decay<Observable>::type::value_type, coordination_type>(coordination));
}
};
}
template<class Coordination>
auto observe_on(Coordination cn)
-> detail::observe_on_factory<Coordination> {
return detail::observe_on_factory<Coordination>(std::move(cn));
}
}
class observe_on_one_worker : public coordination_base
{
rxsc::scheduler factory;
class input_type
{
rxsc::worker controller;
rxsc::scheduler factory;
identity_one_worker coordination;
public:
explicit input_type(rxsc::worker w)
: controller(w)
, factory(rxsc::make_same_worker(w))
, coordination(factory)
{
}
inline rxsc::worker get_worker() const {
return controller;
}
inline rxsc::scheduler get_scheduler() const {
return factory;
}
inline rxsc::scheduler::clock_type::time_point now() const {
return factory.now();
}
template<class Observable>
auto in(Observable o) const
-> decltype(o.observe_on(coordination)) {
return o.observe_on(coordination);
}
template<class Subscriber>
auto out(Subscriber s) const
-> Subscriber {
return std::move(s);
}
template<class F>
auto act(F f) const
-> F {
return std::move(f);
}
};
public:
explicit observe_on_one_worker(rxsc::scheduler sc) : factory(sc) {}
typedef coordinator<input_type> coordinator_type;
inline rxsc::scheduler::clock_type::time_point now() const {
return factory.now();
}
inline coordinator_type create_coordinator(composite_subscription cs = composite_subscription()) const {
auto w = factory.create_worker(std::move(cs));
return coordinator_type(input_type(std::move(w)));
}
};
inline observe_on_one_worker observe_on_event_loop() {
static observe_on_one_worker r(rxsc::make_event_loop());
return r;
}
inline observe_on_one_worker observe_on_new_thread() {
static observe_on_one_worker r(rxsc::make_new_thread());
return r;
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/lib/main/aw_main_delegate.h"
#include "android_webview/browser/aw_content_browser_client.h"
#include "android_webview/browser/browser_view_renderer.h"
#include "android_webview/browser/gpu_memory_buffer_factory_impl.h"
#include "android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h"
#include "android_webview/lib/aw_browser_dependency_factory_impl.h"
#include "android_webview/native/aw_quota_manager_bridge_impl.h"
#include "android_webview/native/aw_web_contents_view_delegate.h"
#include "android_webview/native/aw_web_preferences_populater_impl.h"
#include "android_webview/native/external_video_surface_container_impl.h"
#include "android_webview/renderer/aw_content_renderer_client.h"
#include "base/command_line.h"
#include "base/cpu.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/client/gl_in_process_context.h"
#include "gpu/command_buffer/service/in_process_command_buffer.h"
#include "media/base/media_switches.h"
#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
namespace android_webview {
namespace {
// TODO(boliu): Remove this global Allow once the underlying issues are
// resolved - http://crbug.com/240453. See AwMainDelegate::RunProcess below.
base::LazyInstance<scoped_ptr<ScopedAllowWaitForLegacyWebViewApi> >
g_allow_wait_in_ui_thread = LAZY_INSTANCE_INITIALIZER;
}
AwMainDelegate::AwMainDelegate()
: gpu_memory_buffer_factory_(new GpuMemoryBufferFactoryImpl) {
}
AwMainDelegate::~AwMainDelegate() {
}
bool AwMainDelegate::BasicStartupComplete(int* exit_code) {
content::SetContentClient(&content_client_);
gpu::InProcessCommandBuffer::SetGpuMemoryBufferFactory(
gpu_memory_buffer_factory_.get());
BrowserViewRenderer::CalculateTileMemoryPolicy();
CommandLine* cl = CommandLine::ForCurrentProcess();
cl->AppendSwitch(switches::kEnableBeginFrameScheduling);
cl->AppendSwitch(switches::kEnableZeroCopy);
cl->AppendSwitch(switches::kEnableImplSidePainting);
// WebView uses the Android system's scrollbars and overscroll glow.
cl->AppendSwitch(switches::kDisableOverscrollEdgeEffect);
// Not yet supported in single-process mode.
cl->AppendSwitch(switches::kDisableSharedWorkers);
// File system API not supported (requires some new API; internal bug 6930981)
cl->AppendSwitch(switches::kDisableFileSystem);
// Fullscreen video with subtitle is not yet supported.
cl->AppendSwitch(switches::kDisableOverlayFullscreenVideoSubtitle);
#if defined(VIDEO_HOLE)
// Support EME/L1 with hole-punching.
cl->AppendSwitch(switches::kMediaDrmEnableNonCompositing);
#endif
// WebRTC hardware decoding is not supported, internal bug 15075307
cl->AppendSwitch(switches::kDisableWebRtcHWDecoding);
return false;
}
void AwMainDelegate::PreSandboxStartup() {
// TODO(torne): When we have a separate renderer process, we need to handle
// being passed open FDs for the resource paks here.
#if defined(ARCH_CPU_ARM_FAMILY)
// Create an instance of the CPU class to parse /proc/cpuinfo and cache
// cpu_brand info.
base::CPU cpu_info;
#endif
}
void AwMainDelegate::SandboxInitialized(const std::string& process_type) {
// TODO(torne): Adjust linux OOM score here.
}
int AwMainDelegate::RunProcess(
const std::string& process_type,
const content::MainFunctionParams& main_function_params) {
if (process_type.empty()) {
AwBrowserDependencyFactoryImpl::InstallInstance();
browser_runner_.reset(content::BrowserMainRunner::Create());
int exit_code = browser_runner_->Initialize(main_function_params);
DCHECK(exit_code < 0);
g_allow_wait_in_ui_thread.Get().reset(
new ScopedAllowWaitForLegacyWebViewApi);
// Return 0 so that we do NOT trigger the default behavior. On Android, the
// UI message loop is managed by the Java application.
return 0;
}
return -1;
}
void AwMainDelegate::ProcessExiting(const std::string& process_type) {
// TODO(torne): Clean up resources when we handle them.
logging::CloseLogFile();
}
content::ContentBrowserClient*
AwMainDelegate::CreateContentBrowserClient() {
content_browser_client_.reset(new AwContentBrowserClient(this));
return content_browser_client_.get();
}
content::ContentRendererClient*
AwMainDelegate::CreateContentRendererClient() {
content_renderer_client_.reset(new AwContentRendererClient());
return content_renderer_client_.get();
}
scoped_refptr<AwQuotaManagerBridge> AwMainDelegate::CreateAwQuotaManagerBridge(
AwBrowserContext* browser_context) {
return AwQuotaManagerBridgeImpl::Create(browser_context);
}
content::WebContentsViewDelegate* AwMainDelegate::CreateViewDelegate(
content::WebContents* web_contents) {
return AwWebContentsViewDelegate::Create(web_contents);
}
AwWebPreferencesPopulater* AwMainDelegate::CreateWebPreferencesPopulater() {
return new AwWebPreferencesPopulaterImpl();
}
#if defined(VIDEO_HOLE)
content::ExternalVideoSurfaceContainer*
AwMainDelegate::CreateExternalVideoSurfaceContainer(
content::WebContents* web_contents) {
return new ExternalVideoSurfaceContainerImpl(web_contents);
}
#endif
} // namespace android_webview
<commit_msg>[Android WebView] Enable html controls for fullscreen video.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/lib/main/aw_main_delegate.h"
#include "android_webview/browser/aw_content_browser_client.h"
#include "android_webview/browser/browser_view_renderer.h"
#include "android_webview/browser/gpu_memory_buffer_factory_impl.h"
#include "android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h"
#include "android_webview/lib/aw_browser_dependency_factory_impl.h"
#include "android_webview/native/aw_quota_manager_bridge_impl.h"
#include "android_webview/native/aw_web_contents_view_delegate.h"
#include "android_webview/native/aw_web_preferences_populater_impl.h"
#include "android_webview/native/external_video_surface_container_impl.h"
#include "android_webview/renderer/aw_content_renderer_client.h"
#include "base/command_line.h"
#include "base/cpu.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/client/gl_in_process_context.h"
#include "gpu/command_buffer/service/in_process_command_buffer.h"
#include "media/base/media_switches.h"
#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h"
namespace android_webview {
namespace {
// TODO(boliu): Remove this global Allow once the underlying issues are
// resolved - http://crbug.com/240453. See AwMainDelegate::RunProcess below.
base::LazyInstance<scoped_ptr<ScopedAllowWaitForLegacyWebViewApi> >
g_allow_wait_in_ui_thread = LAZY_INSTANCE_INITIALIZER;
}
AwMainDelegate::AwMainDelegate()
: gpu_memory_buffer_factory_(new GpuMemoryBufferFactoryImpl) {
}
AwMainDelegate::~AwMainDelegate() {
}
bool AwMainDelegate::BasicStartupComplete(int* exit_code) {
content::SetContentClient(&content_client_);
gpu::InProcessCommandBuffer::SetGpuMemoryBufferFactory(
gpu_memory_buffer_factory_.get());
BrowserViewRenderer::CalculateTileMemoryPolicy();
CommandLine* cl = CommandLine::ForCurrentProcess();
cl->AppendSwitch(switches::kEnableBeginFrameScheduling);
cl->AppendSwitch(switches::kEnableZeroCopy);
cl->AppendSwitch(switches::kEnableImplSidePainting);
// WebView uses the Android system's scrollbars and overscroll glow.
cl->AppendSwitch(switches::kDisableOverscrollEdgeEffect);
// Not yet supported in single-process mode.
cl->AppendSwitch(switches::kDisableSharedWorkers);
// File system API not supported (requires some new API; internal bug 6930981)
cl->AppendSwitch(switches::kDisableFileSystem);
#if defined(VIDEO_HOLE)
// Support EME/L1 with hole-punching.
cl->AppendSwitch(switches::kMediaDrmEnableNonCompositing);
#endif
// WebRTC hardware decoding is not supported, internal bug 15075307
cl->AppendSwitch(switches::kDisableWebRtcHWDecoding);
return false;
}
void AwMainDelegate::PreSandboxStartup() {
// TODO(torne): When we have a separate renderer process, we need to handle
// being passed open FDs for the resource paks here.
#if defined(ARCH_CPU_ARM_FAMILY)
// Create an instance of the CPU class to parse /proc/cpuinfo and cache
// cpu_brand info.
base::CPU cpu_info;
#endif
}
void AwMainDelegate::SandboxInitialized(const std::string& process_type) {
// TODO(torne): Adjust linux OOM score here.
}
int AwMainDelegate::RunProcess(
const std::string& process_type,
const content::MainFunctionParams& main_function_params) {
if (process_type.empty()) {
AwBrowserDependencyFactoryImpl::InstallInstance();
browser_runner_.reset(content::BrowserMainRunner::Create());
int exit_code = browser_runner_->Initialize(main_function_params);
DCHECK(exit_code < 0);
g_allow_wait_in_ui_thread.Get().reset(
new ScopedAllowWaitForLegacyWebViewApi);
// Return 0 so that we do NOT trigger the default behavior. On Android, the
// UI message loop is managed by the Java application.
return 0;
}
return -1;
}
void AwMainDelegate::ProcessExiting(const std::string& process_type) {
// TODO(torne): Clean up resources when we handle them.
logging::CloseLogFile();
}
content::ContentBrowserClient*
AwMainDelegate::CreateContentBrowserClient() {
content_browser_client_.reset(new AwContentBrowserClient(this));
return content_browser_client_.get();
}
content::ContentRendererClient*
AwMainDelegate::CreateContentRendererClient() {
content_renderer_client_.reset(new AwContentRendererClient());
return content_renderer_client_.get();
}
scoped_refptr<AwQuotaManagerBridge> AwMainDelegate::CreateAwQuotaManagerBridge(
AwBrowserContext* browser_context) {
return AwQuotaManagerBridgeImpl::Create(browser_context);
}
content::WebContentsViewDelegate* AwMainDelegate::CreateViewDelegate(
content::WebContents* web_contents) {
return AwWebContentsViewDelegate::Create(web_contents);
}
AwWebPreferencesPopulater* AwMainDelegate::CreateWebPreferencesPopulater() {
return new AwWebPreferencesPopulaterImpl();
}
#if defined(VIDEO_HOLE)
content::ExternalVideoSurfaceContainer*
AwMainDelegate::CreateExternalVideoSurfaceContainer(
content::WebContents* web_contents) {
return new ExternalVideoSurfaceContainerImpl(web_contents);
}
#endif
} // namespace android_webview
<|endoftext|> |
<commit_before>// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// 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 <wigwag/listenable.hpp>
#include <wigwag/signal.hpp>
#include <wigwag/thread_task_executor.hpp>
#include <wigwag/threadless_task_executor.hpp>
#include <wigwag/token_pool.hpp>
using namespace wigwag;
template < int >
class constructor_tag
{ };
class observable_int
{
private:
int _value;
signal<void(int)> _on_changed;
public:
observable_int(constructor_tag<1>)
: _value(0), _on_changed(std::bind(&observable_int::on_changed_populator, this, std::placeholders::_1))
{ }
observable_int(constructor_tag<2>)
: _value(0), _on_changed([&](const std::function<void(int)>& h){ h(this->_value); })
{ }
observable_int(constructor_tag<3>)
: _value(0), _on_changed([&](const std::function<void(int)>& h){ h(_value); })
{ }
signal_connector<void(int)> on_changed() const
{ return _on_changed.connector(); }
const signal<void(int)>& on_changed_ref() const
{ return _on_changed; }
void set_value(int value)
{
std::lock_guard<decltype(_on_changed.lock_primitive())> l(_on_changed.lock_primitive());
_value = value;
_on_changed(_value);
}
private:
void on_changed_populator(const std::function<void(int)>& handler)
{ handler(_value); }
};
class int_observer
{
private:
mutable std::mutex _mutex { };
int _value { };
token_pool _tokens { };
std::shared_ptr<task_executor> _worker { std::make_shared<thread_task_executor>() };
public:
int_observer(const observable_int& i)
{
_tokens += i.on_changed().connect(_worker, std::bind(&int_observer::int_changed_async_handler, this, std::placeholders::_1));
_tokens += i.on_changed().connect(std::bind(&int_observer::int_changed_sync_handler, this, std::placeholders::_1));
}
private:
void int_changed_async_handler(int i)
{
std::lock_guard<std::mutex> l(_mutex);
_value = i;
}
void int_changed_sync_handler(int)
{ }
};
<commit_msg>Some crazy signals compilation tests<commit_after>// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// 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 <wigwag/listenable.hpp>
#include <wigwag/signal.hpp>
#include <wigwag/thread_task_executor.hpp>
#include <wigwag/threadless_task_executor.hpp>
#include <wigwag/token_pool.hpp>
using namespace wigwag;
template < int >
class constructor_tag
{ };
class observable_int
{
private:
int _value;
signal<void(int)> _on_changed;
public:
observable_int(constructor_tag<1>)
: _value(0), _on_changed(std::bind(&observable_int::on_changed_populator, this, std::placeholders::_1))
{ }
observable_int(constructor_tag<2>)
: _value(0), _on_changed([&](const std::function<void(int)>& h){ h(this->_value); })
{ }
observable_int(constructor_tag<3>)
: _value(0), _on_changed([&](const std::function<void(int)>& h){ h(_value); })
{ }
signal_connector<void(int)> on_changed() const
{ return _on_changed.connector(); }
const signal<void(int)>& on_changed_ref() const
{ return _on_changed; }
void set_value(int value)
{
std::lock_guard<decltype(_on_changed.lock_primitive())> l(_on_changed.lock_primitive());
_value = value;
_on_changed(_value);
}
private:
void on_changed_populator(const std::function<void(int)>& handler)
{ handler(_value); }
};
class int_observer
{
private:
mutable std::mutex _mutex { };
int _value { };
token_pool _tokens { };
std::shared_ptr<task_executor> _worker { std::make_shared<thread_task_executor>() };
public:
int_observer(const observable_int& i)
{
_tokens += i.on_changed().connect(_worker, std::bind(&int_observer::int_changed_async_handler, this, std::placeholders::_1));
_tokens += i.on_changed().connect(std::bind(&int_observer::int_changed_sync_handler, this, std::placeholders::_1));
}
private:
void int_changed_async_handler(int i)
{
std::lock_guard<std::mutex> l(_mutex);
_value = i;
}
void int_changed_sync_handler(int)
{ }
};
class crazy_signals
{
public:
signal<void(const std::function<void(int)>& f)> on_func;
signal<void(std::string& s)> on_string_ref;
void test_connect()
{
std::shared_ptr<task_executor> worker = std::make_shared<thread_task_executor>();
token_pool tp;
tp += on_func.connect(std::bind(&crazy_signals::func_handler, this, std::placeholders::_1));
tp += on_string_ref.connect(std::bind(&crazy_signals::string_ref_handler, this, std::placeholders::_1));
tp += on_func.connect(worker, std::bind(&crazy_signals::func_handler, this, std::placeholders::_1));
tp += on_string_ref.connect(worker, std::bind(&crazy_signals::string_ref_handler, this, std::placeholders::_1));
}
void test_invoke()
{
std::string s;
on_func([](int){ });
on_func(std::bind([](const std::string&, int){ }, "qwe", std::placeholders::_1));
on_string_ref(s);
on_string_ref(std::ref(s));
}
private:
void func_handler(const std::function<void(int)>& f) { f(42); }
void string_ref_handler(std::string& s) { s = "qwe"; }
};
<|endoftext|> |
<commit_before>/*
Copyright (C) 2015 Andreas Hartmetz <ahartmetz@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LGPL. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Alternatively, this file is available under the Mozilla Public License
Version 1.1. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
*/
#include "ipsocket.h"
#include "connectaddress.h"
#ifdef __unix__
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
typedef SSIZE_T ssize_t;
#endif
#include <errno.h>
#include <cassert>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <iostream>
static bool setNonBlocking(int fd)
{
#ifdef _WIN32
unsigned long value = 1; // 0 blocking, != 0 non-blocking
if (ioctlsocket(fd, FIONBIO, &value) != NO_ERROR) {
return false;
}
#else
// don't let forks inherit the file descriptor - that can cause confusion...
fcntl(fd, F_SETFD, FD_CLOEXEC);
// To be able to use the same send() and recv() calls as Windows, also set the non-blocking
// property on the socket descriptor here instead of passing MSG_DONTWAIT to send() and recv().
const int oldFlags = fcntl(fd, F_GETFL);
if (oldFlags == -1) {
return false;
}
fcntl(fd, F_SETFL, oldFlags | O_NONBLOCK);
#endif
return true;
}
static int sendFlags()
{
#ifdef _WIN32
return 0;
#else
return MSG_NOSIGNAL;
#endif
}
static void closeSocket(int fd)
{
#ifdef _WIN32
closesocket(fd);
#else
::close(fd);
#endif
}
// TODO implement address family (IPv4 / IPv6) support
IpSocket::IpSocket(const ConnectAddress &ca)
: m_fd(-1)
{
assert(ca.type() == ConnectAddress::Type::Tcp);
#ifdef _WIN32
WSAData wsadata;
// IPv6 requires Winsock v2.0 or better (but we're not using IPv6 - yet!)
if (WSAStartup(MAKEWORD(2, 0), &wsadata) != 0) {
std::cerr << "IpSocket contruction failed A.\n";
return;
}
#endif
const FileDescriptor fd = socket(AF_INET, SOCK_STREAM, 0);
if (!isValidFileDescriptor(fd)) {
std::cerr << "IpSocket contruction failed B.\n";
return;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(ca.port());
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
bool ok = connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0;
// only make it non-blocking after connect() because Winsock returns
// WSAEWOULDBLOCK when connecting a non-blocking socket
ok = ok && setNonBlocking(fd);
if (ok) {
m_fd = fd;
} else {
closeSocket(fd);
}
}
IpSocket::IpSocket(FileDescriptor fd)
: m_fd(fd)
{
if (!setNonBlocking(m_fd)) {
closeSocket(fd);
m_fd = -1;
}
}
IpSocket::~IpSocket()
{
close();
#ifdef _WIN32
WSACleanup();
#endif
}
void IpSocket::platformClose()
{
if (isValidFileDescriptor(m_fd)) {
closeSocket(m_fd);
m_fd = InvalidFileDescriptor;
}
}
IO::Result IpSocket::write(chunk a)
{
IO::Result ret;
if (!isValidFileDescriptor(m_fd)) {
std::cerr << "\nIpSocket::write() failed A.\n\n";
ret.status = IO::Status::InternalError;
return ret;
}
const uint32 initialLength = a.length;
while (a.length > 0) {
ssize_t nbytes = send(m_fd, reinterpret_cast<char *>(a.ptr), a.length, sendFlags());
if (nbytes < 0) {
if (errno == EINTR) {
continue;
}
// see EAGAIN comment in LocalSocket::read()
if (errno == EAGAIN) {
break;
}
close();
ret.status = IO::Status::InternalError;
return ret;
} else if (nbytes == 0) {
break;
}
a.ptr += nbytes;
a.length -= uint32(nbytes);
}
ret.length = initialLength - a.length;
return ret;
}
uint32 IpSocket::availableBytesForReading()
{
#ifdef _WIN32
u_long available = 0;
if (ioctlsocket(m_fd, FIONREAD, &available) != NO_ERROR) {
#else
uint32 available = 0;
if (ioctl(m_fd, FIONREAD, &available) < 0) {
#endif
available = 0;
}
return uint32(available);
}
IO::Result IpSocket::read(byte *buffer, uint32 maxSize)
{
IO::Result ret;
if (maxSize <= 0) {
std::cerr << "\nIpSocket::read() failed A.\n\n";
ret.status = IO::Status::InternalError;
return ret;
}
while (maxSize > 0) {
ssize_t nbytes = recv(m_fd, reinterpret_cast<char *>(buffer), maxSize, 0);
if (nbytes < 0) {
if (errno == EINTR) {
continue;
}
// see comment in LocalSocket for rationale of EAGAIN behavior
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
close();
ret.status = IO::Status::RemoteClosed;
break;
} else if (nbytes == 0) {
// orderly shutdown
close();
ret.status = IO::Status::RemoteClosed;
break;
}
ret.length += uint32(nbytes);
buffer += nbytes;
maxSize -= uint32(nbytes);
}
return ret;
}
bool IpSocket::isOpen()
{
return isValidFileDescriptor(m_fd);
}
FileDescriptor IpSocket::fileDescriptor() const
{
return m_fd;
}
<commit_msg>When checking for EAGAIN, always check for EWOULDBLOCK, too<commit_after>/*
Copyright (C) 2015 Andreas Hartmetz <ahartmetz@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LGPL. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Alternatively, this file is available under the Mozilla Public License
Version 1.1. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
*/
#include "ipsocket.h"
#include "connectaddress.h"
#ifdef __unix__
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
typedef SSIZE_T ssize_t;
#endif
#include <errno.h>
#include <cassert>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <iostream>
static bool setNonBlocking(int fd)
{
#ifdef _WIN32
unsigned long value = 1; // 0 blocking, != 0 non-blocking
if (ioctlsocket(fd, FIONBIO, &value) != NO_ERROR) {
return false;
}
#else
// don't let forks inherit the file descriptor - that can cause confusion...
fcntl(fd, F_SETFD, FD_CLOEXEC);
// To be able to use the same send() and recv() calls as Windows, also set the non-blocking
// property on the socket descriptor here instead of passing MSG_DONTWAIT to send() and recv().
const int oldFlags = fcntl(fd, F_GETFL);
if (oldFlags == -1) {
return false;
}
fcntl(fd, F_SETFL, oldFlags | O_NONBLOCK);
#endif
return true;
}
static int sendFlags()
{
#ifdef _WIN32
return 0;
#else
return MSG_NOSIGNAL;
#endif
}
static void closeSocket(int fd)
{
#ifdef _WIN32
closesocket(fd);
#else
::close(fd);
#endif
}
// TODO implement address family (IPv4 / IPv6) support
IpSocket::IpSocket(const ConnectAddress &ca)
: m_fd(-1)
{
assert(ca.type() == ConnectAddress::Type::Tcp);
#ifdef _WIN32
WSAData wsadata;
// IPv6 requires Winsock v2.0 or better (but we're not using IPv6 - yet!)
if (WSAStartup(MAKEWORD(2, 0), &wsadata) != 0) {
std::cerr << "IpSocket contruction failed A.\n";
return;
}
#endif
const FileDescriptor fd = socket(AF_INET, SOCK_STREAM, 0);
if (!isValidFileDescriptor(fd)) {
std::cerr << "IpSocket contruction failed B.\n";
return;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(ca.port());
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
bool ok = connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0;
// only make it non-blocking after connect() because Winsock returns
// WSAEWOULDBLOCK when connecting a non-blocking socket
ok = ok && setNonBlocking(fd);
if (ok) {
m_fd = fd;
} else {
closeSocket(fd);
}
}
IpSocket::IpSocket(FileDescriptor fd)
: m_fd(fd)
{
if (!setNonBlocking(m_fd)) {
closeSocket(fd);
m_fd = -1;
}
}
IpSocket::~IpSocket()
{
close();
#ifdef _WIN32
WSACleanup();
#endif
}
void IpSocket::platformClose()
{
if (isValidFileDescriptor(m_fd)) {
closeSocket(m_fd);
m_fd = InvalidFileDescriptor;
}
}
IO::Result IpSocket::write(chunk a)
{
IO::Result ret;
if (!isValidFileDescriptor(m_fd)) {
std::cerr << "\nIpSocket::write() failed A.\n\n";
ret.status = IO::Status::InternalError;
return ret;
}
const uint32 initialLength = a.length;
while (a.length > 0) {
ssize_t nbytes = send(m_fd, reinterpret_cast<char *>(a.ptr), a.length, sendFlags());
if (nbytes < 0) {
if (errno == EINTR) {
continue;
}
// see EAGAIN comment in LocalSocket::read()
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
close();
ret.status = IO::Status::InternalError;
return ret;
} else if (nbytes == 0) {
break;
}
a.ptr += nbytes;
a.length -= uint32(nbytes);
}
ret.length = initialLength - a.length;
return ret;
}
uint32 IpSocket::availableBytesForReading()
{
#ifdef _WIN32
u_long available = 0;
if (ioctlsocket(m_fd, FIONREAD, &available) != NO_ERROR) {
#else
uint32 available = 0;
if (ioctl(m_fd, FIONREAD, &available) < 0) {
#endif
available = 0;
}
return uint32(available);
}
IO::Result IpSocket::read(byte *buffer, uint32 maxSize)
{
IO::Result ret;
if (maxSize <= 0) {
std::cerr << "\nIpSocket::read() failed A.\n\n";
ret.status = IO::Status::InternalError;
return ret;
}
while (maxSize > 0) {
ssize_t nbytes = recv(m_fd, reinterpret_cast<char *>(buffer), maxSize, 0);
if (nbytes < 0) {
if (errno == EINTR) {
continue;
}
// see comment in LocalSocket for rationale of EAGAIN behavior
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
close();
ret.status = IO::Status::RemoteClosed;
break;
} else if (nbytes == 0) {
// orderly shutdown
close();
ret.status = IO::Status::RemoteClosed;
break;
}
ret.length += uint32(nbytes);
buffer += nbytes;
maxSize -= uint32(nbytes);
}
return ret;
}
bool IpSocket::isOpen()
{
return isValidFileDescriptor(m_fd);
}
FileDescriptor IpSocket::fileDescriptor() const
{
return m_fd;
}
<|endoftext|> |
<commit_before>// Example of the usage of the TRolke class
#include "TROOT.h"
#include "TSystem.h"
#include "TRolke.h"
#include "Riostream.h"
void Rolke()
{
//////////////////////////////////////////////////////////
//
// The TRolke class computes the profile likelihood
// confidence limits for 7 different model assumptions
// on systematic/statistical uncertainties
//
// Author : Jan Conrad (CERN) <jan.conrad@cern.ch> 2004
// Johan Lundberg (CERN) <johan.lundberg@cern.ch> 2009
//
// Please read TRolke.cxx and TRolke.h for more docs.
// ---------- --------
//
//////////////////////////////////////////////////////
gSystem->Load("libPhysics.so");
gSystem->Load("libTRolke.so");
/* variables used throughout the example */
Double_t bm;
Double_t tau;
Int_t mid;
Int_t m;
Int_t z;
Int_t y;
Int_t x;
Double_t e;
Double_t em;
Double_t sde;
Double_t sdb;
Double_t b;
Double_t alpha; //Confidence Level
// make TRolke objects
TRolke tr; //
Double_t ul ; // upper limit
Double_t ll ; // lower limit
/////////////////////////////////////////////////////////////
// Model 1 assumes:
//
// Poisson uncertainty in the background estimate
// Binomial uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =1;
x = 5; // events in the signal region
y = 10; // events observed in the background region
tau = 2.5; // ratio between size of signal/background region
m = 100; // MC events have been produced (signal)
z = 50; // MC events have been observed (signal)
alpha=0.9; //Confidence Level
tr.SetCL(alpha);
tr.SetPoissonBkgBinomEff(x,y,z,tau,m);
tr.GetLimits(ll,ul);
cout << "For model 1: Poisson / Binomial" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
/////////////////////////////////////////////////////////////
// Model 2 assumes:
//
// Poisson uncertainty in the background estimate
// Gaussian uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =2;
y = 3 ; // events observed in the background region
x = 10 ; // events in the signal region
tau = 2.5; // ratio between size of signal/background region
em = 0.9; // measured efficiency
sde = 0.05; // standard deviation of efficiency
alpha =0.95; // Confidence L evel
tr.SetCL(alpha);
tr.SetPoissonBkgGaussEff(x,y,em,tau,sde);
tr.GetLimits(ll,ul);
cout << "For model 2 : Poisson / Gaussian" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
/////////////////////////////////////////////////////////////
// Model 3 assumes:
//
// Gaussian uncertainty in the background estimate
// Gaussian uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =3;
bm = 5; // expected background
x = 10; // events in the signal region
sdb = 0.5; // standard deviation in background estimate
em = 0.9; // measured efficiency
sde = 0.05; // standard deviation of efficiency
alpha =0.99; // Confidence Level
tr.SetCL(alpha);
tr.SetGaussBkgGaussEff(x,bm,em,sde,sdb);
tr.GetLimits(ll,ul);
cout << "For model 3 : Gaussian / Gaussian" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
cout << "***************************************" << endl;
cout << "* some more example's for gauss/gauss *" << endl;
cout << "* *" << endl;
Double_t slow,shigh;
tr.GetSensitivity(slow,shigh);
cout << "sensitivity:" << endl;
cout << "[" << slow << "," << shigh << "]" << endl;
int outx;
tr.GetLimitsQuantile(slow,shigh,outx,0.5);
cout << "median limit:" << endl;
cout << "[" << slow << "," << shigh << "] @ x =" << outx <<endl;
tr.GetLimitsML(slow,shigh,outx);
cout << "ML limit:" << endl;
cout << "[" << slow << "," << shigh << "] @ x =" << outx <<endl;
tr.GetSensitivity(slow,shigh);
cout << "sensitivity:" << endl;
cout << "[" << slow << "," << shigh << "]" << endl;
tr.GetLimits(ll,ul);
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
Int_t ncrt;
tr.GetCriticalNumber(ncrt);
cout << "critical number: " << ncrt << endl;
tr.SetCLSigmas(5);
tr.GetCriticalNumber(ncrt);
cout << "critical number for 5 sigma: " << ncrt << endl;
cout << "***************************************" << endl;
/////////////////////////////////////////////////////////////
// Model 4 assumes:
//
// Poisson uncertainty in the background estimate
// known efficiency
//
cout << endl<<" ======================================================== " <<endl;
mid =4;
y = 7; // events observed in the background region
x = 1; // events in the signal region
tau = 5; // ratio between size of signal/background region
e = 0.25; // efficiency
alpha =0.68; // Confidence L evel
tr.SetCL(alpha);
tr.SetPoissonBkgKnownEff(x,y,tau,e);
tr.GetLimits(ll,ul);
cout << "For model 4 : Poissonian / Known" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
////////////////////////////////////////////////////////
// Model 5 assumes:
//
// Gaussian uncertainty in the background estimate
// Known efficiency
//
cout << endl<<" ======================================================== " <<endl;
mid =5;
bm = 0; // measured background expectation
x = 1 ; // events in the signal region
e = 0.65; // known eff
sdb = 1.0; // standard deviation of background estimate
alpha =0.799999; // Confidence Level
tr.SetCL(alpha);
tr.SetGaussBkgKnownEff(x,bm,sdb,e);
tr.GetLimits(ll,ul);
cout << "For model 5 : Gaussian / Known" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
////////////////////////////////////////////////////////
// Model 6 assumes:
//
// Known background
// Binomial uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =6;
b = 10; // known background
x = 25; // events in the signal region
z = 500; // Number of observed signal MC events
m = 750; // Number of produced MC signal events
alpha =0.9; // Confidence L evel
tr.SetCL(alpha);
tr.SetKnownBkgBinomEff(x, z,m,b);
tr.GetLimits(ll,ul);
cout << "For model 6 : Known / Binomial" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
////////////////////////////////////////////////////////
// Model 7 assumes:
//
// Known Background
// Gaussian uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =7;
x = 15; // events in the signal region
em = 0.77; // measured efficiency
sde = 0.15; // standard deviation of efficiency estimate
b = 10; // known background
alpha =0.95; // Confidence L evel
y = 1;
tr.SetCL(alpha);
tr.SetKnownBkgGaussEff(x,em,sde,b);
tr.GetLimits(ll,ul);
cout << "For model 7 : Known / Gaussian " << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
////////////////////////////////////////////////////////
// Example of bounded and unbounded likelihood
// Example for Model 1
///////////////////////////////////////////////////////
bm = 0.0;
tau = 5;
mid = 1;
m = 100;
z = 90;
y = 15;
x = 0;
alpha = 0.90;
tr.SetCL(alpha);
tr.SetPoissonBkgBinomEff(x,y,z,tau,m);
tr.SetBounding(true); //bounded
tr.GetLimits(ll,ul);
cout << "Example of the effect of bounded vs unbounded, For model 1" << endl;
cout << "the BOUNDED Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
tr.SetBounding(false); //unbounded
tr.GetLimits(ll,ul);
cout << "the UNBOUNDED Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
}
<commit_msg>remove loading of libraries which is not needed<commit_after>// Example of the usage of the TRolke class
#include "TROOT.h"
#include "TSystem.h"
#include "TRolke.h"
#include "Riostream.h"
void Rolke()
{
//////////////////////////////////////////////////////////
//
// The TRolke class computes the profile likelihood
// confidence limits for 7 different model assumptions
// on systematic/statistical uncertainties
//
// Author : Jan Conrad (CERN) <jan.conrad@cern.ch> 2004
// Johan Lundberg (CERN) <johan.lundberg@cern.ch> 2009
//
// Please read TRolke.cxx and TRolke.h for more docs.
// ---------- --------
//
//////////////////////////////////////////////////////
/* variables used throughout the example */
Double_t bm;
Double_t tau;
Int_t mid;
Int_t m;
Int_t z;
Int_t y;
Int_t x;
Double_t e;
Double_t em;
Double_t sde;
Double_t sdb;
Double_t b;
Double_t alpha; //Confidence Level
// make TRolke objects
TRolke tr; //
Double_t ul ; // upper limit
Double_t ll ; // lower limit
/////////////////////////////////////////////////////////////
// Model 1 assumes:
//
// Poisson uncertainty in the background estimate
// Binomial uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =1;
x = 5; // events in the signal region
y = 10; // events observed in the background region
tau = 2.5; // ratio between size of signal/background region
m = 100; // MC events have been produced (signal)
z = 50; // MC events have been observed (signal)
alpha=0.9; //Confidence Level
tr.SetCL(alpha);
tr.SetPoissonBkgBinomEff(x,y,z,tau,m);
tr.GetLimits(ll,ul);
cout << "For model 1: Poisson / Binomial" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
/////////////////////////////////////////////////////////////
// Model 2 assumes:
//
// Poisson uncertainty in the background estimate
// Gaussian uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =2;
y = 3 ; // events observed in the background region
x = 10 ; // events in the signal region
tau = 2.5; // ratio between size of signal/background region
em = 0.9; // measured efficiency
sde = 0.05; // standard deviation of efficiency
alpha =0.95; // Confidence L evel
tr.SetCL(alpha);
tr.SetPoissonBkgGaussEff(x,y,em,tau,sde);
tr.GetLimits(ll,ul);
cout << "For model 2 : Poisson / Gaussian" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
/////////////////////////////////////////////////////////////
// Model 3 assumes:
//
// Gaussian uncertainty in the background estimate
// Gaussian uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =3;
bm = 5; // expected background
x = 10; // events in the signal region
sdb = 0.5; // standard deviation in background estimate
em = 0.9; // measured efficiency
sde = 0.05; // standard deviation of efficiency
alpha =0.99; // Confidence Level
tr.SetCL(alpha);
tr.SetGaussBkgGaussEff(x,bm,em,sde,sdb);
tr.GetLimits(ll,ul);
cout << "For model 3 : Gaussian / Gaussian" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
cout << "***************************************" << endl;
cout << "* some more example's for gauss/gauss *" << endl;
cout << "* *" << endl;
Double_t slow,shigh;
tr.GetSensitivity(slow,shigh);
cout << "sensitivity:" << endl;
cout << "[" << slow << "," << shigh << "]" << endl;
int outx;
tr.GetLimitsQuantile(slow,shigh,outx,0.5);
cout << "median limit:" << endl;
cout << "[" << slow << "," << shigh << "] @ x =" << outx <<endl;
tr.GetLimitsML(slow,shigh,outx);
cout << "ML limit:" << endl;
cout << "[" << slow << "," << shigh << "] @ x =" << outx <<endl;
tr.GetSensitivity(slow,shigh);
cout << "sensitivity:" << endl;
cout << "[" << slow << "," << shigh << "]" << endl;
tr.GetLimits(ll,ul);
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
Int_t ncrt;
tr.GetCriticalNumber(ncrt);
cout << "critical number: " << ncrt << endl;
tr.SetCLSigmas(5);
tr.GetCriticalNumber(ncrt);
cout << "critical number for 5 sigma: " << ncrt << endl;
cout << "***************************************" << endl;
/////////////////////////////////////////////////////////////
// Model 4 assumes:
//
// Poisson uncertainty in the background estimate
// known efficiency
//
cout << endl<<" ======================================================== " <<endl;
mid =4;
y = 7; // events observed in the background region
x = 1; // events in the signal region
tau = 5; // ratio between size of signal/background region
e = 0.25; // efficiency
alpha =0.68; // Confidence L evel
tr.SetCL(alpha);
tr.SetPoissonBkgKnownEff(x,y,tau,e);
tr.GetLimits(ll,ul);
cout << "For model 4 : Poissonian / Known" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
////////////////////////////////////////////////////////
// Model 5 assumes:
//
// Gaussian uncertainty in the background estimate
// Known efficiency
//
cout << endl<<" ======================================================== " <<endl;
mid =5;
bm = 0; // measured background expectation
x = 1 ; // events in the signal region
e = 0.65; // known eff
sdb = 1.0; // standard deviation of background estimate
alpha =0.799999; // Confidence Level
tr.SetCL(alpha);
tr.SetGaussBkgKnownEff(x,bm,sdb,e);
tr.GetLimits(ll,ul);
cout << "For model 5 : Gaussian / Known" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
////////////////////////////////////////////////////////
// Model 6 assumes:
//
// Known background
// Binomial uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =6;
b = 10; // known background
x = 25; // events in the signal region
z = 500; // Number of observed signal MC events
m = 750; // Number of produced MC signal events
alpha =0.9; // Confidence L evel
tr.SetCL(alpha);
tr.SetKnownBkgBinomEff(x, z,m,b);
tr.GetLimits(ll,ul);
cout << "For model 6 : Known / Binomial" << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
////////////////////////////////////////////////////////
// Model 7 assumes:
//
// Known Background
// Gaussian uncertainty in the efficiency estimate
//
cout << endl<<" ======================================================== " <<endl;
mid =7;
x = 15; // events in the signal region
em = 0.77; // measured efficiency
sde = 0.15; // standard deviation of efficiency estimate
b = 10; // known background
alpha =0.95; // Confidence L evel
y = 1;
tr.SetCL(alpha);
tr.SetKnownBkgGaussEff(x,em,sde,b);
tr.GetLimits(ll,ul);
cout << "For model 7 : Known / Gaussian " << endl;
cout << "the Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
////////////////////////////////////////////////////////
// Example of bounded and unbounded likelihood
// Example for Model 1
///////////////////////////////////////////////////////
bm = 0.0;
tau = 5;
mid = 1;
m = 100;
z = 90;
y = 15;
x = 0;
alpha = 0.90;
tr.SetCL(alpha);
tr.SetPoissonBkgBinomEff(x,y,z,tau,m);
tr.SetBounding(true); //bounded
tr.GetLimits(ll,ul);
cout << "Example of the effect of bounded vs unbounded, For model 1" << endl;
cout << "the BOUNDED Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
tr.SetBounding(false); //unbounded
tr.GetLimits(ll,ul);
cout << "the UNBOUNDED Profile Likelihood interval is :" << endl;
cout << "[" << ll << "," << ul << "]" << endl;
}
<|endoftext|> |
<commit_before>#include <time.h>
timeonaxis()
{
// This macro illustrates the use of the time mode on the axis
// with different time intervals and time formats. It's result can
// be seen begin_html <a href="gif/timeonaxis.gif">here</a> end_html
// Through all this script, the time is expressed in UTC. some
// information about this format (and others like GPS) may be found at
// begin_html <a href="http://tycho.usno.navy.mil/systime.html">http://tycho.usno.navy.mil/systime.html</a> end_html
// or
// begin_html <a href="http://www.topology.org/sci/time.html">http://www.topology.org/sci/time.html</a> end_html
gROOT->Reset();
// The start time is : almost NOW (the time at which the script is executed)
// actualy, the nearest preceeding hour beginning.
// The time is in general expressed in UTC time with the C time() function
// This will obviously most of the time not be the time displayed on your watch
// since it is universal time. See the C time functions for converting this time
// into more useful structures.
time_t script_time;
script_time = time(0);
script_time = 3600*(int)(script_time/3600);
// The time offset is the one that will be used by all graphs.
// If one changes it, it will be changed even on the graphs already defined
gStyle->SetTimeOffset(script_time);
ct = new TCanvas("ct","Time on axis",10,10,700,900);
ct->Divide(1,3);
ct->SetFillColor(28);
int i;
//======= Build a signal : noisy damped sine ======
// Time interval : 30 minutes
gStyle->SetTitleH(0.08);
float noise;
ht = new TH1F("ht","Love at first sight",3000,0.,2000.);
for (i=1;i<3000;i++) {
noise = gRandom->Gaus(0,120);
if (i>700) {
noise += 1000*sin((i-700)*6.28/30)*exp((double)(700-i)/300);
}
ht->SetBinContent(i,noise);
}
ct->cd(1);
ct_1->SetFillColor(41);
ct_1->SetFrameFillColor(33);
ht->SetLineColor(2);
ht->GetXaxis()->SetLabelSize(0.05);
ht->Draw();
// Sets time on the X axis
// The time used is the one set as time offset added to the value
// of the axis. This is converted into day/month/year hour:min:sec and
// a reasonnable tick interval value is chosen.
ht->GetXaxis()->SetTimeDisplay(1);
//======= Build a simple graph beginning at a different time ======
// Time interval : 5 seconds
float x[100], t[100];
for (i=0;i<100;i++) {
x[i] = sin(i*4*3.1415926/50)*exp(-(double)i/20);
t[i] = 6000+(double)i/20;
}
gt = new TGraph(100,t,x);
gt->SetTitle("Politics");
ct->cd(2);
ct_2->SetFillColor(41);
ct_2->SetFrameFillColor(33);
gt->SetFillColor(19);
gt->SetLineColor(5);
gt->SetLineWidth(2);
gt->Draw("AL");
gt->GetXaxis()->SetLabelSize(0.05);
// Sets time on the X axis
gt->GetXaxis()->SetTimeDisplay(1);
gPad->Modified();
//======= Build a second simple graph for a very long time interval ======
// Time interval : a few years
float x2[10], t2[10];
for (i=0;i<10;i++) {
x2[i] = gRandom->Gaus(500,100)*i;
t2[i] = i*365*86400;
}
gt2 = new TGraph(10,t2,x2);
gt2->SetTitle("Number of monkeys on the moon");
ct->cd(3);
ct_3->SetFillColor(41);
ct_3->SetFrameFillColor(33);
gt2->SetFillColor(19);
gt2->SetMarkerColor(4);
gt2->SetMarkerStyle(29);
gt2->SetMarkerSize(1.3);
gt2->Draw("AP");
gt2->GetXaxis()->SetLabelSize(0.05);
// Sets time on the X axis
gt2->GetXaxis()->SetTimeDisplay(1);
//
// One can choose a different time format than the one chosen by default
// The time format is the same as the one of the C strftime() function
// It's a string containing the following formats :
// for date :
// %a abbreviated weekday name
// %b abbreviated month name
// %d day of the month (01-31)
// %m month (01-12)
// %y year without century
// %Y year with century
//
// for time :
// %H hour (24-hour clock)
// %I hour (12-hour clock)
// %p local equivalent of AM or PM
// %M minute (00-59)
// %S seconds (00-61)
// %% %
// The other characters are output as is.
gt2->GetXaxis()->SetTimeFormat("y. %Y");
gPad->Modified();
}
<commit_msg>Remove call to gROOT->Reset in timeonaxis.C<commit_after>#include <time.h>
void timeonaxis()
{
// This macro illustrates the use of the time mode on the axis
// with different time intervals and time formats. It's result can
// be seen begin_html <a href="gif/timeonaxis.gif">here</a> end_html
// Through all this script, the time is expressed in UTC. some
// information about this format (and others like GPS) may be found at
// begin_html <a href="http://tycho.usno.navy.mil/systime.html">http://tycho.usno.navy.mil/systime.html</a> end_html
// or
// begin_html <a href="http://www.topology.org/sci/time.html">http://www.topology.org/sci/time.html</a> end_html
//
// The start time is : almost NOW (the time at which the script is executed)
// actualy, the nearest preceeding hour beginning.
// The time is in general expressed in UTC time with the C time() function
// This will obviously most of the time not be the time displayed on your watch
// since it is universal time. See the C time functions for converting this time
// into more useful structures.
time_t script_time;
script_time = time(0);
script_time = 3600*(int)(script_time/3600);
// The time offset is the one that will be used by all graphs.
// If one changes it, it will be changed even on the graphs already defined
gStyle->SetTimeOffset(script_time);
ct = new TCanvas("ct","Time on axis",10,10,700,900);
ct->Divide(1,3);
ct->SetFillColor(28);
int i;
//======= Build a signal : noisy damped sine ======
// Time interval : 30 minutes
gStyle->SetTitleH(0.08);
float noise;
ht = new TH1F("ht","Love at first sight",3000,0.,2000.);
for (i=1;i<3000;i++) {
noise = gRandom->Gaus(0,120);
if (i>700) {
noise += 1000*sin((i-700)*6.28/30)*exp((double)(700-i)/300);
}
ht->SetBinContent(i,noise);
}
ct->cd(1);
ct_1->SetFillColor(41);
ct_1->SetFrameFillColor(33);
ht->SetLineColor(2);
ht->GetXaxis()->SetLabelSize(0.05);
ht->Draw();
// Sets time on the X axis
// The time used is the one set as time offset added to the value
// of the axis. This is converted into day/month/year hour:min:sec and
// a reasonnable tick interval value is chosen.
ht->GetXaxis()->SetTimeDisplay(1);
//======= Build a simple graph beginning at a different time ======
// Time interval : 5 seconds
float x[100], t[100];
for (i=0;i<100;i++) {
x[i] = sin(i*4*3.1415926/50)*exp(-(double)i/20);
t[i] = 6000+(double)i/20;
}
gt = new TGraph(100,t,x);
gt->SetTitle("Politics");
ct->cd(2);
ct_2->SetFillColor(41);
ct_2->SetFrameFillColor(33);
gt->SetFillColor(19);
gt->SetLineColor(5);
gt->SetLineWidth(2);
gt->Draw("AL");
gt->GetXaxis()->SetLabelSize(0.05);
// Sets time on the X axis
gt->GetXaxis()->SetTimeDisplay(1);
gPad->Modified();
//======= Build a second simple graph for a very long time interval ======
// Time interval : a few years
float x2[10], t2[10];
for (i=0;i<10;i++) {
x2[i] = gRandom->Gaus(500,100)*i;
t2[i] = i*365*86400;
}
gt2 = new TGraph(10,t2,x2);
gt2->SetTitle("Number of monkeys on the moon");
ct->cd(3);
ct_3->SetFillColor(41);
ct_3->SetFrameFillColor(33);
gt2->SetFillColor(19);
gt2->SetMarkerColor(4);
gt2->SetMarkerStyle(29);
gt2->SetMarkerSize(1.3);
gt2->Draw("AP");
gt2->GetXaxis()->SetLabelSize(0.05);
// Sets time on the X axis
gt2->GetXaxis()->SetTimeDisplay(1);
//
// One can choose a different time format than the one chosen by default
// The time format is the same as the one of the C strftime() function
// It's a string containing the following formats :
// for date :
// %a abbreviated weekday name
// %b abbreviated month name
// %d day of the month (01-31)
// %m month (01-12)
// %y year without century
// %Y year with century
//
// for time :
// %H hour (24-hour clock)
// %I hour (12-hour clock)
// %p local equivalent of AM or PM
// %M minute (00-59)
// %S seconds (00-61)
// %% %
// The other characters are output as is.
gt2->GetXaxis()->SetTimeFormat("y. %Y");
gPad->Modified();
}
<|endoftext|> |
<commit_before>
#include <Hord/aux.hpp>
#include <Hord/utility.hpp>
#include <Hord/Log.hpp>
#include <Hord/Data/Defs.hpp>
#include <Hord/Data/Metadata.hpp>
#include <Hord/IO/Defs.hpp>
#include <Hord/IO/Prop.hpp>
#include <Hord/Object/Defs.hpp>
#include <Hord/Cmd/Data.hpp>
#include <Hord/System/Driver.hpp>
#include <Hord/System/Context.hpp>
#include <exception>
#include <Hord/detail/gr_core.hpp>
namespace Hord {
namespace Cmd {
namespace Data {
#define HORD_SCOPE_CLASS Cmd::Data::SetMetaField
#define HORD_SCOPE_FUNC set_value
void
set_value(
Object::Unit& object,
Hord::Data::FieldValue& value,
Hord::Data::FieldValue const& new_value
) {
if (new_value.type != value.type) {
value = new_value;
} else {
switch (new_value.type) {
case Hord::Data::FieldType::Text:
if (new_value.str == value.str) {
return;
}
value.str = new_value.str;
break;
case Hord::Data::FieldType::Number:
if (new_value.num == value.num) {
return;
}
value.num = new_value.num;
break;
case Hord::Data::FieldType::Boolean:
if (new_value.bin == value.bin) {
return;
}
value.bin = new_value.bin;
break;
}
}
object.get_prop_states().assign(
IO::PropType::metadata,
IO::PropState::modified
);
}
#undef HORD_SCOPE_FUNC
#define HORD_SCOPE_FUNC exec // pseudo
HORD_SCOPE_CLASS::result_type
HORD_SCOPE_CLASS::operator()(
Object::Unit& object,
unsigned const index,
Hord::Data::FieldValue const& new_value
) noexcept try {
m_created = false;
auto& fields = object.get_metadata().fields;
if (fields.size() <= index) {
return commit("out-of-bounds field index");
}
set_value(object, fields[index].value, new_value);
return commit();
} catch (...) {
Log::acquire(Log::error)
<< DUCT_GR_MSG_FQN("error initializing:\n")
;
Log::report_error_ptr(std::current_exception());
return commit("unknown error");
}
#undef HORD_SCOPE_FUNC
#define HORD_SCOPE_FUNC exec // pseudo
HORD_SCOPE_CLASS::result_type
HORD_SCOPE_CLASS::operator()(
Object::Unit& object,
String const& name,
Hord::Data::FieldValue const& new_value,
bool const create
) noexcept try {
m_created = false;
if (name.empty()) {
return commit("empty name");
}
auto& fields = object.get_metadata().fields;
for (auto it = fields.begin(); fields.end() != it; ++it) {
if (name == it->name) {
set_value(object, it->value, new_value);
return commit();
}
}
if (create) {
fields.push_back(Hord::Data::MetaField{name, new_value});
object.get_prop_states().assign(
IO::PropType::metadata,
IO::PropState::modified
);
m_created = true;
return commit();
}
return commit("name not found");
} catch (...) {
Log::acquire(Log::error)
<< DUCT_GR_MSG_FQN("error initializing:\n")
;
Log::report_error_ptr(std::current_exception());
return commit("unknown error");
}
#undef HORD_SCOPE_FUNC
} // namespace Data
} // namespace Cmd
} // namespace Hord
<commit_msg>Cmd::Data::SetMetaField: reworded errors; inclusion tidy.<commit_after>
#include <Hord/aux.hpp>
#include <Hord/utility.hpp>
#include <Hord/Log.hpp>
#include <Hord/Data/Defs.hpp>
#include <Hord/Data/Metadata.hpp>
#include <Hord/IO/Defs.hpp>
#include <Hord/Object/Defs.hpp>
#include <Hord/Cmd/Data.hpp>
#include <exception>
#include <Hord/detail/gr_core.hpp>
namespace Hord {
namespace Cmd {
namespace Data {
#define HORD_SCOPE_CLASS Cmd::Data::SetMetaField
#define HORD_SCOPE_FUNC set_value
void
set_value(
Object::Unit& object,
Hord::Data::FieldValue& value,
Hord::Data::FieldValue const& new_value
) {
if (new_value.type != value.type) {
value = new_value;
} else {
switch (new_value.type) {
case Hord::Data::FieldType::Text:
if (new_value.str == value.str) {
return;
}
value.str = new_value.str;
break;
case Hord::Data::FieldType::Number:
if (new_value.num == value.num) {
return;
}
value.num = new_value.num;
break;
case Hord::Data::FieldType::Boolean:
if (new_value.bin == value.bin) {
return;
}
value.bin = new_value.bin;
break;
}
}
object.get_prop_states().assign(
IO::PropType::metadata,
IO::PropState::modified
);
}
#undef HORD_SCOPE_FUNC
#define HORD_SCOPE_FUNC exec // pseudo
HORD_SCOPE_CLASS::result_type
HORD_SCOPE_CLASS::operator()(
Object::Unit& object,
unsigned const index,
Hord::Data::FieldValue const& new_value
) noexcept try {
m_created = false;
auto& fields = object.get_metadata().fields;
if (fields.size() <= index) {
return commit("field index is out-of-bounds");
}
set_value(object, fields[index].value, new_value);
return commit();
} catch (...) {
Log::acquire(Log::error)
<< DUCT_GR_MSG_FQN("error initializing:\n")
;
Log::report_error_ptr(std::current_exception());
return commit("unknown error");
}
#undef HORD_SCOPE_FUNC
#define HORD_SCOPE_FUNC exec // pseudo
HORD_SCOPE_CLASS::result_type
HORD_SCOPE_CLASS::operator()(
Object::Unit& object,
String const& name,
Hord::Data::FieldValue const& new_value,
bool const create
) noexcept try {
m_created = false;
if (name.empty()) {
return commit("empty name");
}
auto& fields = object.get_metadata().fields;
for (auto it = fields.begin(); fields.end() != it; ++it) {
if (name == it->name) {
set_value(object, it->value, new_value);
return commit();
}
}
if (create) {
fields.push_back(Hord::Data::MetaField{name, new_value});
object.get_prop_states().assign(
IO::PropType::metadata,
IO::PropState::modified
);
m_created = true;
return commit();
}
return commit("field does not exist");
} catch (...) {
Log::acquire(Log::error)
<< DUCT_GR_MSG_FQN("error initializing:\n")
;
Log::report_error_ptr(std::current_exception());
return commit("unknown error");
}
#undef HORD_SCOPE_FUNC
} // namespace Data
} // namespace Cmd
} // namespace Hord
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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 "IECoreMaya/NumericTraits.h"
#include "IECoreMaya/ToMayaObjectConverter.h"
#include "IECoreMaya/FromMayaObjectConverter.h"
#include "IECoreMaya/ObjectParameterHandler.h"
#include "IECoreMaya/ObjectData.h"
#include "IECore/ObjectParameter.h"
#include "IECore/MeshPrimitive.h"
#include "maya/MFnGenericAttribute.h"
#include "maya/MPlug.h"
#include "maya/MFnPluginData.h"
using namespace IECoreMaya;
using namespace Imath;
using namespace boost;
static ParameterHandler::Description< ObjectParameterHandler > registrar( IECore::ObjectParameter::staticTypeId() );
MStatus ObjectParameterHandler::doUpdate( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
IECore::ConstObjectParameterPtr p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter );
if( !p )
{
return MS::kFailure;
}
MObject attribute = plug.attribute();
MFnGenericAttribute fnGAttr( attribute );
if( !fnGAttr.hasObj( attribute ) )
{
return MS::kFailure;
}
fnGAttr.addAccept( ObjectData::id );
for (IECore::ObjectParameter::TypeIdSet::const_iterator it = p->validTypes().begin(); it != p->validTypes().end(); ++it)
{
ConstParameterHandlerPtr h = ParameterHandler::create( *it );
if (h)
{
if ( !h->doUpdate( parameter, plug ) )
{
return MS::kFailure;
}
}
}
return MS::kSuccess;
}
MPlug ObjectParameterHandler::doCreate( IECore::ConstParameterPtr parameter, const MString &plugName, MObject &node ) const
{
IECore::ConstObjectParameterPtr p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter );
if( !p )
{
return MPlug();
}
MFnGenericAttribute fnGAttr;
MObject attribute = fnGAttr.create( plugName, plugName );
MPlug result = finishCreating( parameter, attribute, node );
doUpdate( parameter, result );
return result;
}
MStatus ObjectParameterHandler::doSetValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
IECore::ConstObjectParameterPtr p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter );
if( !p )
{
return MS::kFailure;
}
// Keep trying all the available handlers until we find one that works.
/// \todo Investigate whether we can do a parameter->getValue() here and just get the handler which represents it
for (IECore::ObjectParameter::TypeIdSet::const_iterator it = p->validTypes().begin(); it != p->validTypes().end(); ++it)
{
ConstParameterHandlerPtr h = ParameterHandler::create( *it );
if (h)
{
if ( h->setValue( parameter, plug) )
{
return MS::kSuccess;
}
}
}
MStatus s;
MFnPluginData fnData;
MObject plugData = fnData.create( ObjectData::id );
assert( plugData != MObject::kNullObj );
s = fnData.setObject( plugData );
assert(s);
ObjectData* data = dynamic_cast<ObjectData *>( fnData.data(&s) );
assert(s);
assert(data);
data->setObject( p->getValue()->copy() );
return plug.setValue( plugData );
}
MStatus ObjectParameterHandler::doSetValue( const MPlug &plug, IECore::ParameterPtr parameter ) const
{
IECore::ObjectParameterPtr p = IECore::runTimeCast<IECore::ObjectParameter>( parameter );
if( !p )
{
return MS::kFailure;
}
/// Keep trying all the available handlers until we find one that works
for (IECore::ObjectParameter::TypeIdSet::const_iterator it = p->validTypes().begin(); it != p->validTypes().end(); ++it)
{
ConstParameterHandlerPtr h = ParameterHandler::create( *it );
if (h)
{
if ( h->setValue( plug, parameter ) )
{
return MS::kSuccess;
}
}
}
MStatus s;
MObject plugData;
s = plug.getValue( plugData );
if (!s)
{
return MS::kFailure;
}
MFnPluginData fnData( plugData, &s );
if (!s)
{
return MS::kFailure;
}
ObjectData *data = dynamic_cast<ObjectData *>( fnData.data( &s ) );
if (!data || !s)
{
return MS::kFailure;
}
parameter->setValue( data->getObject() );
return MS::kSuccess;
}
<commit_msg>Fixing infinite loops caused by calling the static set* methods instead of the the doSet* methods.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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 "IECoreMaya/NumericTraits.h"
#include "IECoreMaya/ToMayaObjectConverter.h"
#include "IECoreMaya/FromMayaObjectConverter.h"
#include "IECoreMaya/ObjectParameterHandler.h"
#include "IECoreMaya/ObjectData.h"
#include "IECore/ObjectParameter.h"
#include "IECore/MeshPrimitive.h"
#include "maya/MFnGenericAttribute.h"
#include "maya/MPlug.h"
#include "maya/MFnPluginData.h"
using namespace IECoreMaya;
using namespace Imath;
using namespace boost;
static ParameterHandler::Description< ObjectParameterHandler > registrar( IECore::ObjectParameter::staticTypeId() );
MStatus ObjectParameterHandler::doUpdate( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
IECore::ConstObjectParameterPtr p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter );
if( !p )
{
return MS::kFailure;
}
MObject attribute = plug.attribute();
MFnGenericAttribute fnGAttr( attribute );
if( !fnGAttr.hasObj( attribute ) )
{
return MS::kFailure;
}
fnGAttr.addAccept( ObjectData::id );
for (IECore::ObjectParameter::TypeIdSet::const_iterator it = p->validTypes().begin(); it != p->validTypes().end(); ++it)
{
ConstParameterHandlerPtr h = ParameterHandler::create( *it );
if (h)
{
if ( !h->doUpdate( parameter, plug ) )
{
return MS::kFailure;
}
}
}
return MS::kSuccess;
}
MPlug ObjectParameterHandler::doCreate( IECore::ConstParameterPtr parameter, const MString &plugName, MObject &node ) const
{
IECore::ConstObjectParameterPtr p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter );
if( !p )
{
return MPlug();
}
MFnGenericAttribute fnGAttr;
MObject attribute = fnGAttr.create( plugName, plugName );
MPlug result = finishCreating( parameter, attribute, node );
doUpdate( parameter, result );
return result;
}
MStatus ObjectParameterHandler::doSetValue( IECore::ConstParameterPtr parameter, MPlug &plug ) const
{
IECore::ConstObjectParameterPtr p = IECore::runTimeCast<const IECore::ObjectParameter>( parameter );
if( !p )
{
return MS::kFailure;
}
// Keep trying all the available handlers until we find one that works.
/// \todo Investigate whether we can do a parameter->getValue() here and just get the handler which represents it
for (IECore::ObjectParameter::TypeIdSet::const_iterator it = p->validTypes().begin(); it != p->validTypes().end(); ++it)
{
ConstParameterHandlerPtr h = ParameterHandler::create( *it );
if (h)
{
if ( h->doSetValue( parameter, plug) )
{
return MS::kSuccess;
}
}
}
MStatus s;
MFnPluginData fnData;
MObject plugData = fnData.create( ObjectData::id );
assert( plugData != MObject::kNullObj );
s = fnData.setObject( plugData );
assert(s);
ObjectData* data = dynamic_cast<ObjectData *>( fnData.data(&s) );
assert(s);
assert(data);
data->setObject( p->getValue()->copy() );
return plug.setValue( plugData );
}
MStatus ObjectParameterHandler::doSetValue( const MPlug &plug, IECore::ParameterPtr parameter ) const
{
IECore::ObjectParameterPtr p = IECore::runTimeCast<IECore::ObjectParameter>( parameter );
if( !p )
{
return MS::kFailure;
}
/// Keep trying all the available handlers until we find one that works
for (IECore::ObjectParameter::TypeIdSet::const_iterator it = p->validTypes().begin(); it != p->validTypes().end(); ++it)
{
ConstParameterHandlerPtr h = ParameterHandler::create( *it );
if (h)
{
if ( h->doSetValue( plug, parameter ) )
{
return MS::kSuccess;
}
}
}
MStatus s;
MObject plugData;
s = plug.getValue( plugData );
if (!s)
{
return MS::kFailure;
}
MFnPluginData fnData( plugData, &s );
if (!s)
{
return MS::kFailure;
}
ObjectData *data = dynamic_cast<ObjectData *>( fnData.data( &s ) );
if (!data || !s)
{
return MS::kFailure;
}
parameter->setValue( data->getObject() );
return MS::kSuccess;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: datasourceconnector.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:12:48 $
*
* 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 _DBAUI_DATASOURCECONNECTOR_HXX_
#include "datasourceconnector.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef SVTOOLS_FILENOTATION_HXX
#include <svtools/filenotation.hxx>
#endif
#ifndef _DBU_MISC_HRC_
#include "dbu_misc.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::dbtools;
using ::svt::OFileNotation;
//=====================================================================
//= ODatasourceConnector
//=====================================================================
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector(const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent)
:m_xORB(_rxORB)
,m_pErrorMessageParent(_pMessageParent)
{
implConstruct();
}
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector( const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent,
const ::rtl::OUString& _rContextInformation, const ::rtl::OUString& _rContextDetails )
:m_xORB(_rxORB)
,m_pErrorMessageParent(_pMessageParent)
,m_sContextInformation( _rContextInformation )
,m_sContextDetails( _rContextDetails )
{
implConstruct();
}
//---------------------------------------------------------------------
void ODatasourceConnector::implConstruct()
{
OSL_ENSURE(m_xORB.is(), "ODatasourceConnector::implConstruct: invalid ORB!");
if (m_xORB.is())
{
try
{
Reference< XInterface > xContext = m_xORB->createInstance(SERVICE_SDB_DATABASECONTEXT);
OSL_ENSURE(xContext.is(), "ODatasourceConnector::implConstruct: got no data source context!");
m_xDatabaseContext.set(xContext,UNO_QUERY);
OSL_ENSURE(m_xDatabaseContext.is() || !xContext.is(), "ODatasourceConnector::ODatasourceConnector: missing the XNameAccess interface on the data source context!");
}
catch(const Exception&)
{
OSL_ENSURE(sal_False, "ODatasourceConnector::implConstruct: caught an exception while creating the data source context!");
}
}
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect(const ::rtl::OUString& _rDataSourceName, sal_Bool _bShowError) const
{
Reference< XConnection > xConnection;
OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!");
if (!isValid())
return xConnection;
// get the data source
Reference< XDataSource > xDatasource(
getDataSourceByName_displayError( m_xDatabaseContext, _rDataSourceName, m_pErrorMessageParent, m_xORB, _bShowError ),
UNO_QUERY
);
if ( xDatasource.is() )
xConnection = connect( xDatasource, _bShowError );
return xConnection;
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect(const Reference< XDataSource>& _xDataSource, sal_Bool _bShowError) const
{
Reference< XConnection > xConnection;
OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!");
if (!isValid())
return xConnection;
if (!_xDataSource.is())
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: could not retrieve the data source!");
return xConnection;
}
// get user/password
::rtl::OUString sPassword, sUser;
sal_Bool bPwdRequired = sal_False;
Reference<XPropertySet> xProp(_xDataSource,UNO_QUERY);
try
{
xProp->getPropertyValue(PROPERTY_PASSWORD) >>= sPassword;
xProp->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED) >>= bPwdRequired;
xProp->getPropertyValue(PROPERTY_USER) >>= sUser;
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: error while retrieving data source properties!");
}
// try to connect
SQLExceptionInfo aInfo;
try
{
if (bPwdRequired && !sPassword.getLength())
{ // password required, but empty -> connect using an interaction handler
Reference< XCompletedConnection > xConnectionCompletion(_xDataSource, UNO_QUERY);
if (!xConnectionCompletion.is())
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: missing an interface ... need an error message here!");
}
else
{ // instantiate the default SDB interaction handler
Reference< XInteractionHandler > xHandler(m_xORB->createInstance(SERVICE_SDB_INTERACTION_HANDLER), UNO_QUERY);
if (!xHandler.is())
{
ShowServiceNotAvailableError(m_pErrorMessageParent, String(SERVICE_SDB_INTERACTION_HANDLER), sal_True);
}
else
{
xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
}
}
}
else
{
xConnection = _xDataSource->getConnection(sUser, sPassword);
}
}
catch(SQLContext& e) { aInfo = SQLExceptionInfo(e); }
catch(SQLWarning& e) { aInfo = SQLExceptionInfo(e); }
catch(SQLException& e) { aInfo = SQLExceptionInfo(e); }
catch(Exception&) { OSL_ENSURE(sal_False, "SbaTableQueryBrowser::OnExpandEntry: could not connect - unknown exception!"); }
// display the error (if any)
if ( _bShowError && aInfo.isValid() )
{
if ( m_sContextInformation.getLength() )
{
SQLContext aContext;
aContext.Message = m_sContextInformation;
aContext.Details = m_sContextDetails;
aContext.NextException = aInfo.get();
aInfo = aContext;
}
showError(aInfo, m_pErrorMessageParent, m_xORB);
}
return xConnection;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS warnings01 (1.7.50); FILE MERGED 2006/03/24 15:36:23 fs 1.7.50.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: datasourceconnector.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2006-06-20 03:23: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
*
************************************************************************/
#ifndef _DBAUI_DATASOURCECONNECTOR_HXX_
#include "datasourceconnector.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XCOMPLETEDCONNECTION_HPP_
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_
#include <com/sun/star/sdb/SQLContext.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef SVTOOLS_FILENOTATION_HXX
#include <svtools/filenotation.hxx>
#endif
#ifndef _DBU_MISC_HRC_
#include "dbu_misc.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::dbtools;
using ::svt::OFileNotation;
//=====================================================================
//= ODatasourceConnector
//=====================================================================
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector(const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent)
:m_pErrorMessageParent(_pMessageParent)
,m_xORB(_rxORB)
{
implConstruct();
}
//---------------------------------------------------------------------
ODatasourceConnector::ODatasourceConnector( const Reference< XMultiServiceFactory >& _rxORB, Window* _pMessageParent,
const ::rtl::OUString& _rContextInformation, const ::rtl::OUString& _rContextDetails )
:m_pErrorMessageParent(_pMessageParent)
,m_xORB(_rxORB)
,m_sContextInformation( _rContextInformation )
,m_sContextDetails( _rContextDetails )
{
implConstruct();
}
//---------------------------------------------------------------------
void ODatasourceConnector::implConstruct()
{
OSL_ENSURE(m_xORB.is(), "ODatasourceConnector::implConstruct: invalid ORB!");
if (m_xORB.is())
{
try
{
Reference< XInterface > xContext = m_xORB->createInstance(SERVICE_SDB_DATABASECONTEXT);
OSL_ENSURE(xContext.is(), "ODatasourceConnector::implConstruct: got no data source context!");
m_xDatabaseContext.set(xContext,UNO_QUERY);
OSL_ENSURE(m_xDatabaseContext.is() || !xContext.is(), "ODatasourceConnector::ODatasourceConnector: missing the XNameAccess interface on the data source context!");
}
catch(const Exception&)
{
OSL_ENSURE(sal_False, "ODatasourceConnector::implConstruct: caught an exception while creating the data source context!");
}
}
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect(const ::rtl::OUString& _rDataSourceName, sal_Bool _bShowError) const
{
Reference< XConnection > xConnection;
OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!");
if (!isValid())
return xConnection;
// get the data source
Reference< XDataSource > xDatasource(
getDataSourceByName_displayError( m_xDatabaseContext, _rDataSourceName, m_pErrorMessageParent, m_xORB, _bShowError ),
UNO_QUERY
);
if ( xDatasource.is() )
xConnection = connect( xDatasource, _bShowError );
return xConnection;
}
//---------------------------------------------------------------------
Reference< XConnection > ODatasourceConnector::connect(const Reference< XDataSource>& _xDataSource, sal_Bool _bShowError) const
{
Reference< XConnection > xConnection;
OSL_ENSURE(isValid(), "ODatasourceConnector::connect: invalid object!");
if (!isValid())
return xConnection;
if (!_xDataSource.is())
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: could not retrieve the data source!");
return xConnection;
}
// get user/password
::rtl::OUString sPassword, sUser;
sal_Bool bPwdRequired = sal_False;
Reference<XPropertySet> xProp(_xDataSource,UNO_QUERY);
try
{
xProp->getPropertyValue(PROPERTY_PASSWORD) >>= sPassword;
xProp->getPropertyValue(PROPERTY_ISPASSWORDREQUIRED) >>= bPwdRequired;
xProp->getPropertyValue(PROPERTY_USER) >>= sUser;
}
catch(Exception&)
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: error while retrieving data source properties!");
}
// try to connect
SQLExceptionInfo aInfo;
try
{
if (bPwdRequired && !sPassword.getLength())
{ // password required, but empty -> connect using an interaction handler
Reference< XCompletedConnection > xConnectionCompletion(_xDataSource, UNO_QUERY);
if (!xConnectionCompletion.is())
{
OSL_ENSURE(sal_False, "ODatasourceConnector::connect: missing an interface ... need an error message here!");
}
else
{ // instantiate the default SDB interaction handler
Reference< XInteractionHandler > xHandler(m_xORB->createInstance(SERVICE_SDB_INTERACTION_HANDLER), UNO_QUERY);
if (!xHandler.is())
{
ShowServiceNotAvailableError(m_pErrorMessageParent, String(SERVICE_SDB_INTERACTION_HANDLER), sal_True);
}
else
{
xConnection = xConnectionCompletion->connectWithCompletion(xHandler);
}
}
}
else
{
xConnection = _xDataSource->getConnection(sUser, sPassword);
}
}
catch(SQLContext& e) { aInfo = SQLExceptionInfo(e); }
catch(SQLWarning& e) { aInfo = SQLExceptionInfo(e); }
catch(SQLException& e) { aInfo = SQLExceptionInfo(e); }
catch(Exception&) { OSL_ENSURE(sal_False, "SbaTableQueryBrowser::OnExpandEntry: could not connect - unknown exception!"); }
// display the error (if any)
if ( _bShowError && aInfo.isValid() )
{
if ( m_sContextInformation.getLength() )
{
SQLContext aContext;
aContext.Message = m_sContextInformation;
aContext.Details = m_sContextDetails;
aContext.NextException = aInfo.get();
aInfo = aContext;
}
showError(aInfo, m_pErrorMessageParent, m_xORB);
}
return xConnection;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|> |
<commit_before>#include "encode_jpeg.h"
#include "common_jpeg.h"
namespace vision {
namespace image {
#if !JPEG_FOUND
torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
TORCH_CHECK(
false, "encode_jpeg: torchvision not compiled with libjpeg support");
}
#else
// For libjpeg version <= 9b, the out_size parameter in jpeg_mem_dest() is
// defined as unsigned long, whereas in later version, it is defined as size_t.
// For windows backward compatibility, we define JpegSizeType as different types
// according to the libjpeg version used, in order to prevent compilation
// errors.
#if defined(_WIN32) || !defined(JPEG_LIB_VERSION_MAJOR) || \
JPEG_LIB_VERSION_MAJOR < 9 || \
(JPEG_LIB_VERSION_MAJOR == 9 && JPEG_LIB_VERSION_MINOR <= 2)
using JpegSizeType = unsigned long;
#else
using JpegSizeType = size_t;
#endif
using namespace detail;
torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
// Define compression structures and error handling
struct jpeg_compress_struct cinfo {};
struct torch_jpeg_error_mgr jerr {};
// Define buffer to write JPEG information to and its size
JpegSizeType jpegSize = 0;
uint8_t* jpegBuf = nullptr;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = torch_jpeg_error_exit;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(jerr.setjmp_buffer)) {
/* If we get here, the JPEG code has signaled an error.
* We need to clean up the JPEG object and the buffer.
*/
jpeg_destroy_compress(&cinfo);
if (jpegBuf != nullptr) {
free(jpegBuf);
}
TORCH_CHECK(false, (const char*)jerr.jpegLastErrorMsg);
}
// Check that the input tensor is on CPU
TORCH_CHECK(data.device() == torch::kCPU, "Input tensor should be on CPU");
// Check that the input tensor dtype is uint8
TORCH_CHECK(data.dtype() == torch::kU8, "Input tensor dtype should be uint8");
// Check that the input tensor is 3-dimensional
TORCH_CHECK(data.dim() == 3, "Input data should be a 3-dimensional tensor");
// Get image info
int channels = data.size(0);
int height = data.size(1);
int width = data.size(2);
auto input = data.permute({1, 2, 0}).contiguous();
TORCH_CHECK(
channels == 1 || channels == 3,
"The number of channels should be 1 or 3, got: ",
channels);
// Initialize JPEG structure
jpeg_create_compress(&cinfo);
// Set output image information
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = channels;
cinfo.in_color_space = channels == 1 ? JCS_GRAYSCALE : JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE);
// Save JPEG output to a buffer
jpeg_mem_dest(&cinfo, &jpegBuf, &jpegSize);
// Start JPEG compression
jpeg_start_compress(&cinfo, TRUE);
auto stride = width * channels;
auto ptr = input.data_ptr<uint8_t>();
// Encode JPEG file
while (cinfo.next_scanline < cinfo.image_height) {
jpeg_write_scanlines(&cinfo, &ptr, 1);
ptr += stride;
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
torch::TensorOptions options = torch::TensorOptions{torch::kU8};
auto out_tensor =
torch::from_blob(jpegBuf, {(long)jpegSize}, ::free, options);
jpegBuf = nullptr;
return out_tensor;
}
#endif
} // namespace image
} // namespace vision
<commit_msg>Fix size_t issues across JPEG versions and platforms (#4439)<commit_after>#include "encode_jpeg.h"
#include "common_jpeg.h"
namespace vision {
namespace image {
#if !JPEG_FOUND
torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
TORCH_CHECK(
false, "encode_jpeg: torchvision not compiled with libjpeg support");
}
#else
// For libjpeg version <= 9b, the out_size parameter in jpeg_mem_dest() is
// defined as unsigned long, whereas in later version, it is defined as size_t.
#if !defined(JPEG_LIB_VERSION_MAJOR) || JPEG_LIB_VERSION_MAJOR < 9 || \
(JPEG_LIB_VERSION_MAJOR == 9 && JPEG_LIB_VERSION_MINOR <= 2)
using JpegSizeType = unsigned long;
#else
using JpegSizeType = size_t;
#endif
using namespace detail;
torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
// Define compression structures and error handling
struct jpeg_compress_struct cinfo {};
struct torch_jpeg_error_mgr jerr {};
// Define buffer to write JPEG information to and its size
JpegSizeType jpegSize = 0;
uint8_t* jpegBuf = nullptr;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = torch_jpeg_error_exit;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(jerr.setjmp_buffer)) {
/* If we get here, the JPEG code has signaled an error.
* We need to clean up the JPEG object and the buffer.
*/
jpeg_destroy_compress(&cinfo);
if (jpegBuf != nullptr) {
free(jpegBuf);
}
TORCH_CHECK(false, (const char*)jerr.jpegLastErrorMsg);
}
// Check that the input tensor is on CPU
TORCH_CHECK(data.device() == torch::kCPU, "Input tensor should be on CPU");
// Check that the input tensor dtype is uint8
TORCH_CHECK(data.dtype() == torch::kU8, "Input tensor dtype should be uint8");
// Check that the input tensor is 3-dimensional
TORCH_CHECK(data.dim() == 3, "Input data should be a 3-dimensional tensor");
// Get image info
int channels = data.size(0);
int height = data.size(1);
int width = data.size(2);
auto input = data.permute({1, 2, 0}).contiguous();
TORCH_CHECK(
channels == 1 || channels == 3,
"The number of channels should be 1 or 3, got: ",
channels);
// Initialize JPEG structure
jpeg_create_compress(&cinfo);
// Set output image information
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = channels;
cinfo.in_color_space = channels == 1 ? JCS_GRAYSCALE : JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE);
// Save JPEG output to a buffer
jpeg_mem_dest(&cinfo, &jpegBuf, &jpegSize);
// Start JPEG compression
jpeg_start_compress(&cinfo, TRUE);
auto stride = width * channels;
auto ptr = input.data_ptr<uint8_t>();
// Encode JPEG file
while (cinfo.next_scanline < cinfo.image_height) {
jpeg_write_scanlines(&cinfo, &ptr, 1);
ptr += stride;
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
torch::TensorOptions options = torch::TensorOptions{torch::kU8};
auto out_tensor =
torch::from_blob(jpegBuf, {(long)jpegSize}, ::free, options);
jpegBuf = nullptr;
return out_tensor;
}
#endif
} // namespace image
} // namespace vision
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Class header file...
#include "XalanOutputStream.hpp"
#include <xercesc/util/TransService.hpp>
#include "XalanTranscodingServices.hpp"
XALAN_CPP_NAMESPACE_BEGIN
const XalanDOMChar XalanOutputStream::s_nlString[] =
{
XalanUnicode::charLF,
0
};
const XalanDOMChar XalanOutputStream::s_nlCRString[] =
{
XalanUnicode::charCR,
XalanUnicode::charLF,
0
};
const XalanDOMString::size_type XalanOutputStream::s_nlStringLength =
sizeof(s_nlString) / sizeof(s_nlString[0]) - 1;
const XalanDOMString::size_type XalanOutputStream::s_nlCRStringLength =
sizeof(s_nlCRString) / sizeof(s_nlCRString[0]) - 1;
XalanOutputStream::XalanOutputStream(
BufferType::size_type theBufferSize,
TranscodeVectorType::size_type theTranscoderBlockSize,
bool fThrowTranscodeException) :
m_transcoderBlockSize(theTranscoderBlockSize),
m_transcoder(0),
m_bufferSize(theBufferSize),
m_buffer(),
m_encoding(),
m_writeAsUTF16(false),
m_throwTranscodeException(fThrowTranscodeException),
m_transcodingBuffer()
{
if (m_bufferSize == 0)
{
m_bufferSize = 1;
}
m_buffer.reserve(theBufferSize + 1);
}
XalanOutputStream::~XalanOutputStream()
{
XalanTranscodingServices::destroyTranscoder(m_transcoder);
}
void
XalanOutputStream::write(
const XalanDOMChar* theBuffer,
size_t theBufferLength)
{
assert(theBuffer != 0);
if (theBufferLength + m_buffer.size() > m_bufferSize)
{
flushBuffer();
}
if (theBufferLength > m_bufferSize)
{
doWrite(theBuffer, theBufferLength);
}
else
{
m_buffer.insert(m_buffer.end(),
theBuffer,
theBuffer + theBufferLength);
}
}
void
XalanOutputStream::transcode(
const XalanDOMChar* theBuffer,
size_t theBufferLength,
TranscodeVectorType& theDestination)
{
if (m_transcoder == 0)
{
if (TranscodeToLocalCodePage(
theBuffer,
theBufferLength,
theDestination) == false)
{
if (m_throwTranscodeException == true)
{
throw TranscodingException();
}
else
{
}
}
}
else
{
bool fDone = false;
// Keep track of the total bytes we've added to the
// destination vector, and the total bytes we've
// eaten from theBuffer.
size_t theTotalBytesFilled = 0;
size_t theTotalBytesEaten = 0;
// Keep track of the current position in the input buffer,
// and amount remaining in the buffer, since we may not be
// able to transcode it all at once.
const XalanDOMChar* theBufferPosition = theBuffer;
size_t theRemainingBufferLength = theBufferLength;
// Keep track of the destination size, and the target size, which is
// the size of the destination that has not yet been filled with
// transcoded characters. Double the buffer size, in case we're
// transcoding to a 16-bit encoding.
// $$$ ToDo: We need to know the size of an encoding, so we can
// do the right thing with the destination size.
size_t theDestinationSize = theBufferLength * 2;
size_t theTargetSize = theDestinationSize;
do
{
// Resize the buffer...
theDestination.resize(theDestinationSize + 1);
size_t theSourceBytesEaten = 0;
size_t theTargetBytesEaten = 0;
XalanTranscodingServices::eCode theResult =
m_transcoder->transcode(
theBufferPosition,
theRemainingBufferLength,
#if defined(XALAN_OLD_STYLE_CASTS)
(XMLByte*)&theDestination[0] + theTotalBytesFilled,
#else
reinterpret_cast<XMLByte*>(&theDestination[0]) + theTotalBytesFilled,
#endif
theTargetSize,
theSourceBytesEaten,
theTargetBytesEaten);
if(theResult != XalanTranscodingServices::OK)
{
if (m_throwTranscodeException == true)
{
throw TranscodingException();
}
else
{
}
}
theTotalBytesFilled += theTargetBytesEaten;
theTotalBytesEaten += theSourceBytesEaten;
if (theTotalBytesEaten == theBufferLength)
{
fDone = true;
}
else
{
assert(theTotalBytesEaten < theBufferLength);
// Update everything...
theBufferPosition += theSourceBytesEaten;
theRemainingBufferLength -= theSourceBytesEaten;
// The new target size will always be the
// current destination size, since we
// grow by a factor of 2. This will
// need to change if the factor is
// every changed.
theTargetSize = theDestinationSize;
// Grow the destination by a factor of
// two 2. See the previous comment if
// you want to change this.
theDestinationSize = theDestinationSize * 2;
}
} while(fDone == false);
// Resize things, if there are any extra bytes...
if (theDestination.size() != theTotalBytesFilled)
{
theDestination.resize(theTotalBytesFilled);
}
}
}
void
XalanOutputStream::setOutputEncoding(const XalanDOMString& theEncoding)
{
// Flush, just in case. This should probably be an error...
flushBuffer();
XalanTranscodingServices::destroyTranscoder(m_transcoder);
XalanTranscodingServices::eCode theCode = XalanTranscodingServices::OK;
// This turns on an optimization that we can only do if
// XalanDOMChar == sizeof(ushort). See doWrite().
#if !defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
if (XalanTranscodingServices::encodingIsUTF16(theEncoding) == true)
{
m_writeAsUTF16 = true;
}
else
#endif
{
m_transcoder = XalanTranscodingServices::makeNewTranscoder(
theEncoding,
theCode,
m_transcoderBlockSize);
if (theCode == XalanTranscodingServices::UnsupportedEncoding)
{
throw UnsupportedEncodingException(theEncoding);
}
else if (theCode != XalanTranscodingServices::OK)
{
throw TranscoderInternalFailureException(theEncoding);
}
assert(m_transcoder != 0);
}
m_encoding = theEncoding;
const XalanTranscodingServices::XalanXMLByte* theProlog =
XalanTranscodingServices::getStreamProlog(theEncoding);
assert(theProlog != 0);
const size_t theLength = XalanTranscodingServices::length(theProlog);
if (theLength > 0)
{
#if defined(XALAN_OLD_STYLE_CASTS)
write((const char*)theProlog, theLength);
#else
write(reinterpret_cast<const char*>(theProlog), theLength);
#endif
}
}
bool
XalanOutputStream::canTranscodeTo(unsigned int theChar) const
{
if (m_transcoder != 0)
{
return m_transcoder->canTranscodeTo(theChar);
}
else
{
// We'll always return true here, since an exception will be
// thrown when we try to transcode. We'ed like to enable the
// commented out line, if we can ever figure out how to see
// if a character can be encoded.
return true;
// return XalanTranscodingServices::canTranscodeToLocalCodePage(theChar);
}
}
void
XalanOutputStream::flushBuffer()
{
if (m_buffer.empty() == false)
{
doWrite(&*m_buffer.begin(), m_buffer.size());
m_buffer.clear();
}
}
void
XalanOutputStream::doWrite(
const XalanDOMChar* theBuffer,
size_t theBufferLength)
{
assert(theBuffer != 0);
try
{
if (m_writeAsUTF16 == true)
{
assert(sizeof(XalanDOMChar) == sizeof(char) * 2);
// This is a hack to write UTF-16 through as if it
// were just chars. Saves lots of time "transcoding."
#if defined(XALAN_OLD_STYLE_CASTS)
writeData((const char*)theBuffer, theBufferLength * 2);
#else
writeData(reinterpret_cast<const char*>(theBuffer), theBufferLength * 2);
#endif
}
else
{
transcode(theBuffer, theBufferLength, m_transcodingBuffer);
assert(&m_transcodingBuffer[0] != 0);
writeData(&m_transcodingBuffer[0],
m_transcodingBuffer.size());
}
}
catch(const XalanOutputStreamException&)
{
// Have to catch this error and flush any output remaining...
m_buffer.clear();
throw;
}
}
void
XalanOutputStream::setBufferSize(BufferType::size_type theBufferSize)
{
flushBuffer();
if (theBufferSize == 0)
{
m_bufferSize = 1;
}
else
{
m_bufferSize = theBufferSize;
}
if (m_buffer.size() < m_bufferSize)
{
// Enlarge the buffer...
m_buffer.reserve(theBufferSize + 1);
}
else if (m_buffer.size() > m_bufferSize)
{
// Shrink the buffer.
// Create a temp buffer and make it
// the correct size.
BufferType temp;
temp.reserve(theBufferSize + 1);
// Swap temp with m_buffer so that
// m_buffer is now the correct size.
temp.swap(m_buffer);
}
}
void
XalanOutputStream::newline()
{
// We've had requests to make this a run-time switch, but for now,
// it's compile time only...
#if defined(XALAN_NEWLINE_IS_CRLF)
write(s_nlCRString, s_nlCRStringLength);
#else
write(s_nlString, s_nlStringLength);
#endif
}
const XalanDOMChar*
XalanOutputStream::getNewlineString() const
{
// We've had requests to make this a run-time switch, but for now,
// it's compile time only...
#if defined(XALAN_NEWLINE_IS_CRLF)
return s_nlCRString;
#else
return s_nlString;
#endif
}
XalanOutputStream::XalanOutputStreamException::XalanOutputStreamException(
const XalanDOMString& theMessage,
const XalanDOMString& theType) :
XSLException(theMessage, theType)
{
}
XalanOutputStream::XalanOutputStreamException::~XalanOutputStreamException()
{
}
XalanOutputStream::UnknownEncodingException::UnknownEncodingException() :
XalanOutputStreamException(
TranscodeFromLocalCodePage("Unknown error occurred while transcoding!"),
TranscodeFromLocalCodePage("UnknownEncodingException"))
{
}
XalanOutputStream::UnknownEncodingException::~UnknownEncodingException()
{
}
XalanOutputStream::UnsupportedEncodingException::UnsupportedEncodingException(const XalanDOMString& theEncoding) :
XalanOutputStreamException(
TranscodeFromLocalCodePage("Unsupported encoding: ") + theEncoding,
TranscodeFromLocalCodePage("UnsupportedEncodingException")),
m_encoding(theEncoding)
{
}
XalanOutputStream::UnsupportedEncodingException::~UnsupportedEncodingException()
{
}
XalanOutputStream::TranscoderInternalFailureException::TranscoderInternalFailureException(const XalanDOMString& theEncoding) :
XalanOutputStreamException(
TranscodeFromLocalCodePage("Unknown error occurred while transcoding to ") +
theEncoding +
TranscodeFromLocalCodePage("!"),
TranscodeFromLocalCodePage("TranscoderInternalFailureException")),
m_encoding(theEncoding)
{
}
XalanOutputStream::TranscoderInternalFailureException::~TranscoderInternalFailureException()
{
}
XalanOutputStream::TranscodingException::TranscodingException() :
XalanOutputStreamException(
TranscodeFromLocalCodePage("An error occurred while transcoding!"),
TranscodeFromLocalCodePage("TranscodingException"))
{
}
XalanOutputStream::TranscodingException::~TranscodingException()
{
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Added guard to ensure m_buffer is cleared. Removed unnecessary try/catch block.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Class header file...
#include "XalanOutputStream.hpp"
#include <xercesc/util/TransService.hpp>
#include "Include/STLHelper.hpp"
#include "XalanTranscodingServices.hpp"
XALAN_CPP_NAMESPACE_BEGIN
const XalanDOMChar XalanOutputStream::s_nlString[] =
{
XalanUnicode::charLF,
0
};
const XalanDOMChar XalanOutputStream::s_nlCRString[] =
{
XalanUnicode::charCR,
XalanUnicode::charLF,
0
};
const XalanDOMString::size_type XalanOutputStream::s_nlStringLength =
sizeof(s_nlString) / sizeof(s_nlString[0]) - 1;
const XalanDOMString::size_type XalanOutputStream::s_nlCRStringLength =
sizeof(s_nlCRString) / sizeof(s_nlCRString[0]) - 1;
XalanOutputStream::XalanOutputStream(
BufferType::size_type theBufferSize,
TranscodeVectorType::size_type theTranscoderBlockSize,
bool fThrowTranscodeException) :
m_transcoderBlockSize(theTranscoderBlockSize),
m_transcoder(0),
m_bufferSize(theBufferSize),
m_buffer(),
m_encoding(),
m_writeAsUTF16(false),
m_throwTranscodeException(fThrowTranscodeException),
m_transcodingBuffer()
{
if (m_bufferSize == 0)
{
m_bufferSize = 1;
}
m_buffer.reserve(theBufferSize + 1);
}
XalanOutputStream::~XalanOutputStream()
{
XalanTranscodingServices::destroyTranscoder(m_transcoder);
}
void
XalanOutputStream::write(
const XalanDOMChar* theBuffer,
size_t theBufferLength)
{
assert(theBuffer != 0);
if (theBufferLength + m_buffer.size() > m_bufferSize)
{
flushBuffer();
}
if (theBufferLength > m_bufferSize)
{
assert(m_buffer.size() == 0);
doWrite(theBuffer, theBufferLength);
}
else
{
m_buffer.insert(m_buffer.end(),
theBuffer,
theBuffer + theBufferLength);
}
}
void
XalanOutputStream::transcode(
const XalanDOMChar* theBuffer,
size_t theBufferLength,
TranscodeVectorType& theDestination)
{
if (m_transcoder == 0)
{
if (TranscodeToLocalCodePage(
theBuffer,
theBufferLength,
theDestination) == false)
{
if (m_throwTranscodeException == true)
{
throw TranscodingException();
}
else
{
}
}
}
else
{
bool fDone = false;
// Keep track of the total bytes we've added to the
// destination vector, and the total bytes we've
// eaten from theBuffer.
size_t theTotalBytesFilled = 0;
size_t theTotalBytesEaten = 0;
// Keep track of the current position in the input buffer,
// and amount remaining in the buffer, since we may not be
// able to transcode it all at once.
const XalanDOMChar* theBufferPosition = theBuffer;
size_t theRemainingBufferLength = theBufferLength;
// Keep track of the destination size, and the target size, which is
// the size of the destination that has not yet been filled with
// transcoded characters. Double the buffer size, in case we're
// transcoding to a 16-bit encoding.
// $$$ ToDo: We need to know the size of an encoding, so we can
// do the right thing with the destination size.
size_t theDestinationSize = theBufferLength * 2;
size_t theTargetSize = theDestinationSize;
do
{
// Resize the buffer...
theDestination.resize(theDestinationSize + 1);
size_t theSourceBytesEaten = 0;
size_t theTargetBytesEaten = 0;
XalanTranscodingServices::eCode theResult =
m_transcoder->transcode(
theBufferPosition,
theRemainingBufferLength,
#if defined(XALAN_OLD_STYLE_CASTS)
(XMLByte*)&theDestination[0] + theTotalBytesFilled,
#else
reinterpret_cast<XMLByte*>(&theDestination[0]) + theTotalBytesFilled,
#endif
theTargetSize,
theSourceBytesEaten,
theTargetBytesEaten);
if(theResult != XalanTranscodingServices::OK)
{
if (m_throwTranscodeException == true)
{
throw TranscodingException();
}
else
{
}
}
theTotalBytesFilled += theTargetBytesEaten;
theTotalBytesEaten += theSourceBytesEaten;
if (theTotalBytesEaten == theBufferLength)
{
fDone = true;
}
else
{
assert(theTotalBytesEaten < theBufferLength);
// Update everything...
theBufferPosition += theSourceBytesEaten;
theRemainingBufferLength -= theSourceBytesEaten;
// The new target size will always be the
// current destination size, since we
// grow by a factor of 2. This will
// need to change if the factor is
// every changed.
theTargetSize = theDestinationSize;
// Grow the destination by a factor of
// two 2. See the previous comment if
// you want to change this.
theDestinationSize = theDestinationSize * 2;
}
} while(fDone == false);
// Resize things, if there are any extra bytes...
if (theDestination.size() != theTotalBytesFilled)
{
theDestination.resize(theTotalBytesFilled);
}
}
}
void
XalanOutputStream::setOutputEncoding(const XalanDOMString& theEncoding)
{
// Flush, just in case. This should probably be an error...
flushBuffer();
XalanTranscodingServices::destroyTranscoder(m_transcoder);
XalanTranscodingServices::eCode theCode = XalanTranscodingServices::OK;
// This turns on an optimization that we can only do if
// XalanDOMChar == sizeof(ushort). See doWrite().
#if !defined(XALAN_XALANDOMCHAR_USHORT_MISMATCH)
if (XalanTranscodingServices::encodingIsUTF16(theEncoding) == true)
{
m_writeAsUTF16 = true;
}
else
#endif
{
m_transcoder = XalanTranscodingServices::makeNewTranscoder(
theEncoding,
theCode,
m_transcoderBlockSize);
if (theCode == XalanTranscodingServices::UnsupportedEncoding)
{
throw UnsupportedEncodingException(theEncoding);
}
else if (theCode != XalanTranscodingServices::OK)
{
throw TranscoderInternalFailureException(theEncoding);
}
assert(m_transcoder != 0);
}
m_encoding = theEncoding;
const XalanTranscodingServices::XalanXMLByte* theProlog =
XalanTranscodingServices::getStreamProlog(theEncoding);
assert(theProlog != 0);
const size_t theLength = XalanTranscodingServices::length(theProlog);
if (theLength > 0)
{
#if defined(XALAN_OLD_STYLE_CASTS)
write((const char*)theProlog, theLength);
#else
write(reinterpret_cast<const char*>(theProlog), theLength);
#endif
}
}
bool
XalanOutputStream::canTranscodeTo(unsigned int theChar) const
{
if (m_transcoder != 0)
{
return m_transcoder->canTranscodeTo(theChar);
}
else
{
// We'll always return true here, since an exception will be
// thrown when we try to transcode. We'ed like to enable the
// commented out line, if we can ever figure out how to see
// if a character can be encoded.
return true;
// return XalanTranscodingServices::canTranscodeToLocalCodePage(theChar);
}
}
void
XalanOutputStream::flushBuffer()
{
if (m_buffer.empty() == false)
{
CollectionClearGuard<BufferType> theGuard(m_buffer);
doWrite(&*m_buffer.begin(), m_buffer.size());
}
assert(m_buffer.empty() == true);
}
void
XalanOutputStream::doWrite(
const XalanDOMChar* theBuffer,
size_t theBufferLength)
{
assert(theBuffer != 0);
if (m_writeAsUTF16 == true)
{
assert(sizeof(XalanDOMChar) == sizeof(char) * 2);
// This is a hack to write UTF-16 through as if it
// were just chars. Saves lots of time "transcoding."
#if defined(XALAN_OLD_STYLE_CASTS)
writeData((const char*)theBuffer, theBufferLength * 2);
#else
writeData(reinterpret_cast<const char*>(theBuffer), theBufferLength * 2);
#endif
}
else
{
transcode(theBuffer, theBufferLength, m_transcodingBuffer);
assert(&m_transcodingBuffer[0] != 0);
writeData(
&m_transcodingBuffer[0],
m_transcodingBuffer.size());
}
}
void
XalanOutputStream::setBufferSize(BufferType::size_type theBufferSize)
{
flushBuffer();
if (theBufferSize == 0)
{
m_bufferSize = 1;
}
else
{
m_bufferSize = theBufferSize;
}
if (m_buffer.size() < m_bufferSize)
{
// Enlarge the buffer...
m_buffer.reserve(theBufferSize + 1);
}
else if (m_buffer.size() > m_bufferSize)
{
// Shrink the buffer.
// Create a temp buffer and make it
// the correct size.
BufferType temp;
temp.reserve(theBufferSize + 1);
// Swap temp with m_buffer so that
// m_buffer is now the correct size.
temp.swap(m_buffer);
}
}
void
XalanOutputStream::newline()
{
// We've had requests to make this a run-time switch, but for now,
// it's compile time only...
#if defined(XALAN_NEWLINE_IS_CRLF)
write(s_nlCRString, s_nlCRStringLength);
#else
write(s_nlString, s_nlStringLength);
#endif
}
const XalanDOMChar*
XalanOutputStream::getNewlineString() const
{
// We've had requests to make this a run-time switch, but for now,
// it's compile time only...
#if defined(XALAN_NEWLINE_IS_CRLF)
return s_nlCRString;
#else
return s_nlString;
#endif
}
XalanOutputStream::XalanOutputStreamException::XalanOutputStreamException(
const XalanDOMString& theMessage,
const XalanDOMString& theType) :
XSLException(theMessage, theType)
{
}
XalanOutputStream::XalanOutputStreamException::~XalanOutputStreamException()
{
}
XalanOutputStream::UnknownEncodingException::UnknownEncodingException() :
XalanOutputStreamException(
TranscodeFromLocalCodePage("Unknown error occurred while transcoding!"),
TranscodeFromLocalCodePage("UnknownEncodingException"))
{
}
XalanOutputStream::UnknownEncodingException::~UnknownEncodingException()
{
}
XalanOutputStream::UnsupportedEncodingException::UnsupportedEncodingException(const XalanDOMString& theEncoding) :
XalanOutputStreamException(
TranscodeFromLocalCodePage("Unsupported encoding: ") + theEncoding,
TranscodeFromLocalCodePage("UnsupportedEncodingException")),
m_encoding(theEncoding)
{
}
XalanOutputStream::UnsupportedEncodingException::~UnsupportedEncodingException()
{
}
XalanOutputStream::TranscoderInternalFailureException::TranscoderInternalFailureException(const XalanDOMString& theEncoding) :
XalanOutputStreamException(
TranscodeFromLocalCodePage("Unknown error occurred while transcoding to ") +
theEncoding +
TranscodeFromLocalCodePage("!"),
TranscodeFromLocalCodePage("TranscoderInternalFailureException")),
m_encoding(theEncoding)
{
}
XalanOutputStream::TranscoderInternalFailureException::~TranscoderInternalFailureException()
{
}
XalanOutputStream::TranscodingException::TranscodingException() :
XalanOutputStreamException(
TranscodeFromLocalCodePage("An error occurred while transcoding!"),
TranscodeFromLocalCodePage("TranscodingException"))
{
}
XalanOutputStream::TranscodingException::~TranscodingException()
{
}
XALAN_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hierarchycontent.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 18:05:47 $
*
* 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 _HIERARCHYCONTENT_HXX
#define _HIERARCHYCONTENT_HXX
#include <list>
#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTCREATOR_HPP_
#include <com/sun/star/ucb/XContentCreator.hpp>
#endif
#ifndef _UCBHELPER_CONTENTHELPER_HXX
#include <ucbhelper/contenthelper.hxx>
#endif
#ifndef _HIERARCHYDATA_HXX
#include "hierarchydata.hxx"
#endif
#ifndef _HIERARCHYPROVIDER_HXX
#include "hierarchyprovider.hxx"
#endif
namespace com { namespace sun { namespace star { namespace beans {
struct Property;
struct PropertyValue;
} } } }
namespace com { namespace sun { namespace star { namespace sdbc {
class XRow;
} } } }
namespace com { namespace sun { namespace star { namespace ucb {
struct TransferInfo;
} } } }
namespace hierarchy_ucp
{
//=========================================================================
#define HIERARCHY_ROOT_FOLDER_CONTENT_SERVICE_NAME \
"com.sun.star.ucb.HierarchyRootFolderContent"
#define HIERARCHY_FOLDER_CONTENT_SERVICE_NAME \
"com.sun.star.ucb.HierarchyFolderContent"
#define HIERARCHY_LINK_CONTENT_SERVICE_NAME \
"com.sun.star.ucb.HierarchyLinkContent"
//=========================================================================
class HierarchyContentProperties
{
public:
HierarchyContentProperties() {};
HierarchyContentProperties( const HierarchyEntryData::Type & rType )
: m_aData( rType ),
m_aContentType( rType == HierarchyEntryData::FOLDER
? rtl::OUString::createFromAscii( HIERARCHY_FOLDER_CONTENT_TYPE )
: rtl::OUString::createFromAscii( HIERARCHY_LINK_CONTENT_TYPE ) ) {}
HierarchyContentProperties( const HierarchyEntryData & rData )
: m_aData( rData ),
m_aContentType( rData.getType() == HierarchyEntryData::FOLDER
? rtl::OUString::createFromAscii( HIERARCHY_FOLDER_CONTENT_TYPE )
: rtl::OUString::createFromAscii( HIERARCHY_LINK_CONTENT_TYPE ) ) {}
const rtl::OUString & getName() const { return m_aData.getName(); }
void setName( const rtl::OUString & rName ) { m_aData.setName( rName ); };
const rtl::OUString & getTitle() const { return m_aData.getTitle(); }
void setTitle( const rtl::OUString & rTitle )
{ m_aData.setTitle( rTitle ); };
const rtl::OUString & getTargetURL() const
{ return m_aData.getTargetURL(); }
void setTargetURL( const rtl::OUString & rURL )
{ m_aData.setTargetURL( rURL ); };
const rtl::OUString & getContentType() const { return m_aContentType; }
sal_Bool getIsFolder() const
{ return m_aData.getType() == HierarchyEntryData::FOLDER; }
sal_Bool getIsDocument() const { return !getIsFolder(); }
const HierarchyEntryData & getHierarchyEntryData() const { return m_aData; }
private:
HierarchyEntryData m_aData;
rtl::OUString m_aContentType;
};
//=========================================================================
class HierarchyContentProvider;
class HierarchyContent : public ::ucbhelper::ContentImplHelper,
public com::sun::star::ucb::XContentCreator
{
enum ContentKind { LINK, FOLDER, ROOT };
enum ContentState { TRANSIENT, // created via CreateNewContent,
// but did not process "insert" yet
PERSISTENT, // processed "insert"
DEAD // processed "delete"
};
HierarchyContentProperties m_aProps;
ContentKind m_eKind;
ContentState m_eState;
HierarchyContentProvider* m_pProvider;
bool m_bCheckedReadOnly;
bool m_bIsReadOnly;
private:
HierarchyContent(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier,
const HierarchyContentProperties& rProps );
HierarchyContent(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier,
const com::sun::star::ucb::ContentInfo& Info );
virtual com::sun::star::uno::Sequence< com::sun::star::beans::Property >
getProperties( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv );
virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo >
getCommands( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv );
virtual ::rtl::OUString getParentURL();
static sal_Bool hasData(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier );
sal_Bool hasData(
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier )
{ return hasData( m_xSMgr, m_pProvider, Identifier ); }
static sal_Bool loadData(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier,
HierarchyContentProperties& rProps );
sal_Bool storeData();
sal_Bool renameData( const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& xOldId,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& xNewId );
sal_Bool removeData();
void setKind( const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier );
bool isReadOnly();
sal_Bool isFolder() const { return ( m_eKind > LINK ); }
::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContentIdentifier >
makeNewIdentifier( const rtl::OUString& rTitle );
typedef rtl::Reference< HierarchyContent > HierarchyContentRef;
typedef std::list< HierarchyContentRef > HierarchyContentRefList;
void queryChildren( HierarchyContentRefList& rChildren );
sal_Bool exchangeIdentity(
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContentIdentifier >& xNewId );
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
getPropertyValues( const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::Property >& rProperties );
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >
setPropertyValues(
const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue >& rValues,
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( ::com::sun::star::uno::Exception );
void insert( sal_Int32 nNameClashResolve,
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( ::com::sun::star::uno::Exception );
void destroy( sal_Bool bDeletePhysical,
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( ::com::sun::star::uno::Exception );
void transfer( const ::com::sun::star::ucb::TransferInfo& rInfo,
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( ::com::sun::star::uno::Exception );
public:
// Create existing content. Fail, if not already exists.
static HierarchyContent* create(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier );
// Create new content. Fail, if already exists.
static HierarchyContent* create(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier,
const com::sun::star::ucb::ContentInfo& Info );
virtual ~HierarchyContent();
// XInterface
XINTERFACE_DECL()
// XTypeProvider
XTYPEPROVIDER_DECL()
// XServiceInfo
virtual ::rtl::OUString SAL_CALL
getImplementationName()
throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedServiceNames()
throw( ::com::sun::star::uno::RuntimeException );
// XContent
virtual rtl::OUString SAL_CALL
getContentType()
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier > SAL_CALL
getIdentifier()
throw( com::sun::star::uno::RuntimeException );
// XCommandProcessor
virtual com::sun::star::uno::Any SAL_CALL
execute( const com::sun::star::ucb::Command& aCommand,
sal_Int32 CommandId,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& Environment )
throw( com::sun::star::uno::Exception,
com::sun::star::ucb::CommandAbortedException,
com::sun::star::uno::RuntimeException );
virtual void SAL_CALL
abort( sal_Int32 CommandId )
throw( com::sun::star::uno::RuntimeException );
//////////////////////////////////////////////////////////////////////
// Additional interfaces
//////////////////////////////////////////////////////////////////////
// XContentCreator
virtual com::sun::star::uno::Sequence<
com::sun::star::ucb::ContentInfo > SAL_CALL
queryCreatableContentsInfo()
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Reference<
com::sun::star::ucb::XContent > SAL_CALL
createNewContent( const com::sun::star::ucb::ContentInfo& Info )
throw( com::sun::star::uno::RuntimeException );
//////////////////////////////////////////////////////////////////////
// Non-interface methods.
//////////////////////////////////////////////////////////////////////
static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
getPropertyValues( const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory >& rSMgr,
const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::Property >& rProperties,
const HierarchyContentProperties& rData,
HierarchyContentProvider* pProvider,
const ::rtl::OUString& rContentId );
};
} // namespace hierarchy_ucp
#endif /* !_HIERARCHYCONTENT_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.12.72); FILE MERGED 2008/04/01 16:02:19 thb 1.12.72.3: #i85898# Stripping all external header guards 2008/04/01 12:58:17 thb 1.12.72.2: #i85898# Stripping all external header guards 2008/03/31 15:30:24 rt 1.12.72.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: hierarchycontent.hxx,v $
* $Revision: 1.13 $
*
* 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 _HIERARCHYCONTENT_HXX
#define _HIERARCHYCONTENT_HXX
#include <list>
#include <rtl/ref.hxx>
#include <com/sun/star/ucb/XContentCreator.hpp>
#include <ucbhelper/contenthelper.hxx>
#include "hierarchydata.hxx"
#include "hierarchyprovider.hxx"
namespace com { namespace sun { namespace star { namespace beans {
struct Property;
struct PropertyValue;
} } } }
namespace com { namespace sun { namespace star { namespace sdbc {
class XRow;
} } } }
namespace com { namespace sun { namespace star { namespace ucb {
struct TransferInfo;
} } } }
namespace hierarchy_ucp
{
//=========================================================================
#define HIERARCHY_ROOT_FOLDER_CONTENT_SERVICE_NAME \
"com.sun.star.ucb.HierarchyRootFolderContent"
#define HIERARCHY_FOLDER_CONTENT_SERVICE_NAME \
"com.sun.star.ucb.HierarchyFolderContent"
#define HIERARCHY_LINK_CONTENT_SERVICE_NAME \
"com.sun.star.ucb.HierarchyLinkContent"
//=========================================================================
class HierarchyContentProperties
{
public:
HierarchyContentProperties() {};
HierarchyContentProperties( const HierarchyEntryData::Type & rType )
: m_aData( rType ),
m_aContentType( rType == HierarchyEntryData::FOLDER
? rtl::OUString::createFromAscii( HIERARCHY_FOLDER_CONTENT_TYPE )
: rtl::OUString::createFromAscii( HIERARCHY_LINK_CONTENT_TYPE ) ) {}
HierarchyContentProperties( const HierarchyEntryData & rData )
: m_aData( rData ),
m_aContentType( rData.getType() == HierarchyEntryData::FOLDER
? rtl::OUString::createFromAscii( HIERARCHY_FOLDER_CONTENT_TYPE )
: rtl::OUString::createFromAscii( HIERARCHY_LINK_CONTENT_TYPE ) ) {}
const rtl::OUString & getName() const { return m_aData.getName(); }
void setName( const rtl::OUString & rName ) { m_aData.setName( rName ); };
const rtl::OUString & getTitle() const { return m_aData.getTitle(); }
void setTitle( const rtl::OUString & rTitle )
{ m_aData.setTitle( rTitle ); };
const rtl::OUString & getTargetURL() const
{ return m_aData.getTargetURL(); }
void setTargetURL( const rtl::OUString & rURL )
{ m_aData.setTargetURL( rURL ); };
const rtl::OUString & getContentType() const { return m_aContentType; }
sal_Bool getIsFolder() const
{ return m_aData.getType() == HierarchyEntryData::FOLDER; }
sal_Bool getIsDocument() const { return !getIsFolder(); }
const HierarchyEntryData & getHierarchyEntryData() const { return m_aData; }
private:
HierarchyEntryData m_aData;
rtl::OUString m_aContentType;
};
//=========================================================================
class HierarchyContentProvider;
class HierarchyContent : public ::ucbhelper::ContentImplHelper,
public com::sun::star::ucb::XContentCreator
{
enum ContentKind { LINK, FOLDER, ROOT };
enum ContentState { TRANSIENT, // created via CreateNewContent,
// but did not process "insert" yet
PERSISTENT, // processed "insert"
DEAD // processed "delete"
};
HierarchyContentProperties m_aProps;
ContentKind m_eKind;
ContentState m_eState;
HierarchyContentProvider* m_pProvider;
bool m_bCheckedReadOnly;
bool m_bIsReadOnly;
private:
HierarchyContent(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier,
const HierarchyContentProperties& rProps );
HierarchyContent(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier,
const com::sun::star::ucb::ContentInfo& Info );
virtual com::sun::star::uno::Sequence< com::sun::star::beans::Property >
getProperties( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv );
virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo >
getCommands( const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment > & xEnv );
virtual ::rtl::OUString getParentURL();
static sal_Bool hasData(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier );
sal_Bool hasData(
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier )
{ return hasData( m_xSMgr, m_pProvider, Identifier ); }
static sal_Bool loadData(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier,
HierarchyContentProperties& rProps );
sal_Bool storeData();
sal_Bool renameData( const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& xOldId,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& xNewId );
sal_Bool removeData();
void setKind( const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier );
bool isReadOnly();
sal_Bool isFolder() const { return ( m_eKind > LINK ); }
::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContentIdentifier >
makeNewIdentifier( const rtl::OUString& rTitle );
typedef rtl::Reference< HierarchyContent > HierarchyContentRef;
typedef std::list< HierarchyContentRef > HierarchyContentRefList;
void queryChildren( HierarchyContentRefList& rChildren );
sal_Bool exchangeIdentity(
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XContentIdentifier >& xNewId );
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
getPropertyValues( const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::Property >& rProperties );
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >
setPropertyValues(
const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue >& rValues,
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( ::com::sun::star::uno::Exception );
void insert( sal_Int32 nNameClashResolve,
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( ::com::sun::star::uno::Exception );
void destroy( sal_Bool bDeletePhysical,
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( ::com::sun::star::uno::Exception );
void transfer( const ::com::sun::star::ucb::TransferInfo& rInfo,
const ::com::sun::star::uno::Reference<
::com::sun::star::ucb::XCommandEnvironment > & xEnv )
throw( ::com::sun::star::uno::Exception );
public:
// Create existing content. Fail, if not already exists.
static HierarchyContent* create(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier );
// Create new content. Fail, if already exists.
static HierarchyContent* create(
const com::sun::star::uno::Reference<
com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
HierarchyContentProvider* pProvider,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier >& Identifier,
const com::sun::star::ucb::ContentInfo& Info );
virtual ~HierarchyContent();
// XInterface
XINTERFACE_DECL()
// XTypeProvider
XTYPEPROVIDER_DECL()
// XServiceInfo
virtual ::rtl::OUString SAL_CALL
getImplementationName()
throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedServiceNames()
throw( ::com::sun::star::uno::RuntimeException );
// XContent
virtual rtl::OUString SAL_CALL
getContentType()
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Reference<
com::sun::star::ucb::XContentIdentifier > SAL_CALL
getIdentifier()
throw( com::sun::star::uno::RuntimeException );
// XCommandProcessor
virtual com::sun::star::uno::Any SAL_CALL
execute( const com::sun::star::ucb::Command& aCommand,
sal_Int32 CommandId,
const com::sun::star::uno::Reference<
com::sun::star::ucb::XCommandEnvironment >& Environment )
throw( com::sun::star::uno::Exception,
com::sun::star::ucb::CommandAbortedException,
com::sun::star::uno::RuntimeException );
virtual void SAL_CALL
abort( sal_Int32 CommandId )
throw( com::sun::star::uno::RuntimeException );
//////////////////////////////////////////////////////////////////////
// Additional interfaces
//////////////////////////////////////////////////////////////////////
// XContentCreator
virtual com::sun::star::uno::Sequence<
com::sun::star::ucb::ContentInfo > SAL_CALL
queryCreatableContentsInfo()
throw( com::sun::star::uno::RuntimeException );
virtual com::sun::star::uno::Reference<
com::sun::star::ucb::XContent > SAL_CALL
createNewContent( const com::sun::star::ucb::ContentInfo& Info )
throw( com::sun::star::uno::RuntimeException );
//////////////////////////////////////////////////////////////////////
// Non-interface methods.
//////////////////////////////////////////////////////////////////////
static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
getPropertyValues( const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory >& rSMgr,
const ::com::sun::star::uno::Sequence<
::com::sun::star::beans::Property >& rProperties,
const HierarchyContentProperties& rData,
HierarchyContentProvider* pProvider,
const ::rtl::OUString& rContentId );
};
} // namespace hierarchy_ucp
#endif /* !_HIERARCHYCONTENT_HXX */
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <iostream>
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
static void test_multithread_elementwise()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPool tp(internal::random<int>(3, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(3, 11));
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
static void test_multithread_compound_assignment()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPool tp(internal::random<int>(3, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(3, 11));
out.device(thread_pool_device) = in1;
out.device(thread_pool_device) += in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
template<int DataLayout>
static void test_multithread_contraction()
{
Tensor<float, 4, DataLayout> t_left(30, 50, 37, 31);
Tensor<float, 5, DataLayout> t_right(37, 31, 70, 2, 10);
Tensor<float, 5, DataLayout> t_result(30, 50, 70, 2, 10);
t_left.setRandom();
t_right.setRandom();
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 2> dims({{DimPair(2, 0), DimPair(3, 1)}});
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 1500, 1147);
MapXf m_right(t_right.data(), 1147, 1400);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(1500, 1400);
Eigen::ThreadPool tp(4);
Eigen::ThreadPoolDevice thread_pool_device(&tp, 4);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
VERIFY(&t_result.data()[i] != &m_result.data()[i]);
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_contraction_corner_cases()
{
Tensor<float, 2, DataLayout> t_left(32, 500);
Tensor<float, 2, DataLayout> t_right(32, 28*28);
Tensor<float, 2, DataLayout> t_result(500, 28*28);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result = t_result.constant(NAN);
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims{{DimPair(0, 0)}};
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 32, 500);
MapXf m_right(t_right.data(), 32, 28*28);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(500, 28*28);
Eigen::ThreadPool tp(12);
Eigen::ThreadPoolDevice thread_pool_device(&tp, 12);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected at index " << i << " : " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_result.resize (1, 28*28);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 500);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (500, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 500);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (1, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_multithread_contraction_agrees_with_singlethread() {
int contract_size = internal::random<int>(1, 5000);
Tensor<float, 3, DataLayout> left(internal::random<int>(1, 80),
contract_size,
internal::random<int>(1, 100));
Tensor<float, 4, DataLayout> right(internal::random<int>(1, 25),
internal::random<int>(1, 37),
contract_size,
internal::random<int>(1, 51));
left.setRandom();
right.setRandom();
// add constants to shift values away from 0 for more precision
left += left.constant(1.5f);
right += right.constant(1.5f);
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims({{DimPair(1, 2)}});
Eigen::ThreadPool tp(internal::random<int>(2, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(2, 11));
Tensor<float, 5, DataLayout> st_result;
st_result = left.contract(right, dims);
Tensor<float, 5, DataLayout> tp_result(st_result.dimensions());
tp_result.device(thread_pool_device) = left.contract(right, dims);
VERIFY(dimensions_match(st_result.dimensions(), tp_result.dimensions()));
for (ptrdiff_t i = 0; i < st_result.size(); i++) {
// if both of the values are very small, then do nothing (because the test will fail
// due to numerical precision issues when values are small)
if (fabs(st_result.data()[i] - tp_result.data()[i]) >= 1e-4) {
VERIFY_IS_APPROX(st_result.data()[i], tp_result.data()[i]);
}
}
}
static void test_memcpy() {
for (int i = 0; i < 5; ++i) {
const int num_threads = internal::random<int>(3, 11);
Eigen::ThreadPool tp(num_threads);
Eigen::ThreadPoolDevice thread_pool_device(&tp, num_threads);
const int size = internal::random<int>(13, 7632);
Tensor<float, 1> t1(size);
t1.setRandom();
std::vector<float> result(size);
thread_pool_device.memcpy(&result[0], t1.data(), size*sizeof(float));
for (int i = 0; i < size; i++) {
VERIFY_IS_EQUAL(t1(i), result[i]);
}
}
}
static void test_multithread_random()
{
Eigen::ThreadPool tp(2);
Eigen::ThreadPoolDevice device(&tp, 2);
Tensor<float, 1> t(1 << 20);
t.device(device) = t.random<Eigen::internal::NormalRandomGenerator<float>>();
}
void test_cxx11_tensor_thread_pool()
{
CALL_SUBTEST(test_multithread_elementwise());
CALL_SUBTEST(test_multithread_compound_assignment());
CALL_SUBTEST(test_multithread_contraction<ColMajor>());
CALL_SUBTEST(test_multithread_contraction<RowMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<ColMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<RowMajor>());
// Exercise various cases that have been problematic in the past.
CALL_SUBTEST(test_contraction_corner_cases<ColMajor>());
CALL_SUBTEST(test_contraction_corner_cases<RowMajor>());
CALL_SUBTEST(test_memcpy());
CALL_SUBTEST(test_multithread_random());
}
<commit_msg>Fixed a compilation warning<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <iostream>
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
static void test_multithread_elementwise()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPool tp(internal::random<int>(3, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(3, 11));
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
static void test_multithread_compound_assignment()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPool tp(internal::random<int>(3, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(3, 11));
out.device(thread_pool_device) = in1;
out.device(thread_pool_device) += in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
template<int DataLayout>
static void test_multithread_contraction()
{
Tensor<float, 4, DataLayout> t_left(30, 50, 37, 31);
Tensor<float, 5, DataLayout> t_right(37, 31, 70, 2, 10);
Tensor<float, 5, DataLayout> t_result(30, 50, 70, 2, 10);
t_left.setRandom();
t_right.setRandom();
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 2> dims({{DimPair(2, 0), DimPair(3, 1)}});
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 1500, 1147);
MapXf m_right(t_right.data(), 1147, 1400);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(1500, 1400);
Eigen::ThreadPool tp(4);
Eigen::ThreadPoolDevice thread_pool_device(&tp, 4);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
VERIFY(&t_result.data()[i] != &m_result.data()[i]);
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_contraction_corner_cases()
{
Tensor<float, 2, DataLayout> t_left(32, 500);
Tensor<float, 2, DataLayout> t_right(32, 28*28);
Tensor<float, 2, DataLayout> t_result(500, 28*28);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result = t_result.constant(NAN);
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims{{DimPair(0, 0)}};
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 32, 500);
MapXf m_right(t_right.data(), 32, 28*28);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(500, 28*28);
Eigen::ThreadPool tp(12);
Eigen::ThreadPoolDevice thread_pool_device(&tp, 12);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected at index " << i << " : " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_result.resize (1, 28*28);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 500);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (500, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 500);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (1, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_multithread_contraction_agrees_with_singlethread() {
int contract_size = internal::random<int>(1, 5000);
Tensor<float, 3, DataLayout> left(internal::random<int>(1, 80),
contract_size,
internal::random<int>(1, 100));
Tensor<float, 4, DataLayout> right(internal::random<int>(1, 25),
internal::random<int>(1, 37),
contract_size,
internal::random<int>(1, 51));
left.setRandom();
right.setRandom();
// add constants to shift values away from 0 for more precision
left += left.constant(1.5f);
right += right.constant(1.5f);
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims({{DimPair(1, 2)}});
Eigen::ThreadPool tp(internal::random<int>(2, 11));
Eigen::ThreadPoolDevice thread_pool_device(&tp, internal::random<int>(2, 11));
Tensor<float, 5, DataLayout> st_result;
st_result = left.contract(right, dims);
Tensor<float, 5, DataLayout> tp_result(st_result.dimensions());
tp_result.device(thread_pool_device) = left.contract(right, dims);
VERIFY(dimensions_match(st_result.dimensions(), tp_result.dimensions()));
for (ptrdiff_t i = 0; i < st_result.size(); i++) {
// if both of the values are very small, then do nothing (because the test will fail
// due to numerical precision issues when values are small)
if (fabs(st_result.data()[i] - tp_result.data()[i]) >= 1e-4) {
VERIFY_IS_APPROX(st_result.data()[i], tp_result.data()[i]);
}
}
}
static void test_memcpy() {
for (int i = 0; i < 5; ++i) {
const int num_threads = internal::random<int>(3, 11);
Eigen::ThreadPool tp(num_threads);
Eigen::ThreadPoolDevice thread_pool_device(&tp, num_threads);
const int size = internal::random<int>(13, 7632);
Tensor<float, 1> t1(size);
t1.setRandom();
std::vector<float> result(size);
thread_pool_device.memcpy(&result[0], t1.data(), size*sizeof(float));
for (int j = 0; j < size; j++) {
VERIFY_IS_EQUAL(t1(j), result[j]);
}
}
}
static void test_multithread_random()
{
Eigen::ThreadPool tp(2);
Eigen::ThreadPoolDevice device(&tp, 2);
Tensor<float, 1> t(1 << 20);
t.device(device) = t.random<Eigen::internal::NormalRandomGenerator<float>>();
}
void test_cxx11_tensor_thread_pool()
{
CALL_SUBTEST(test_multithread_elementwise());
CALL_SUBTEST(test_multithread_compound_assignment());
CALL_SUBTEST(test_multithread_contraction<ColMajor>());
CALL_SUBTEST(test_multithread_contraction<RowMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<ColMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<RowMajor>());
// Exercise various cases that have been problematic in the past.
CALL_SUBTEST(test_contraction_corner_cases<ColMajor>());
CALL_SUBTEST(test_contraction_corner_cases<RowMajor>());
CALL_SUBTEST(test_memcpy());
CALL_SUBTEST(test_multithread_random());
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string>
#include "native.h"
#include "file.h"
#include "../general.h"
using namespace std;
inline string getStringVal(Ink_Object *str)
{
if (str->type == INK_STRING) {
return as<Ink_String>(str)->value;
}
return "";
}
Ink_Object *InkNative_File_Exist(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
if (!checkArgument(argc, argv, 1, INK_STRING)) {
return NULL_OBJ;
}
return new Ink_Numeric(!access(getStringVal(argv[0]).c_str(), 0));
}
Ink_Object *InkNative_File_Remove(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
if (!checkArgument(argc, argv, 1, INK_STRING)) {
return NULL_OBJ;
}
return new Ink_Numeric(!remove(getStringVal(argv[0]).c_str()));
}
Ink_Object *InkNative_File_Constructor(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *ret;
FILE *fp = NULL;
const char *tmp;
if (checkArgument(false, argc, argv, 2, INK_STRING, INK_STRING)) {
fp = fopen(tmp = getStringVal(argv[0]).c_str(), getStringVal(argv[1]).c_str());
if (!fp) {
InkWarn_Failed_Open_File(tmp);
}
} else if (checkArgument(false, argc, argv, 1, INK_STRING)) {
fp = fopen(tmp = getStringVal(argv[0]).c_str(), "r");
if (!fp) {
InkWarn_Failed_Open_File(tmp);
}
} else if (checkArgument(false, argc, argv, 1, INK_CUSTOM)) {
fp = as<Ink_FilePointer>(argv[0])->fp;
}
context->getLocal()->context->setSlot("this", ret = new Ink_FilePointer(fp));
return ret;
}
void Ink_FilePointer::setMethod()
{
setSlot("close", new Ink_FunctionObject(InkNative_File_Close));
setSlot("puts", new Ink_FunctionObject(InkNative_File_PutString));
setSlot("gets", new Ink_FunctionObject(InkNative_File_GetString));
setSlot("flush", new Ink_FunctionObject(InkNative_File_Flush));
return;
}
Ink_Object *InkNative_File_Close(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *base = context->searchSlot("base");
FILE *tmp;
ASSUME_BASE_TYPE(INK_CUSTOM);
tmp = as<Ink_FilePointer>(base)->fp;
if (tmp)
fclose(tmp);
return NULL_OBJ;
}
Ink_Object *InkNative_File_PutString(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *base = context->searchSlot("base");
FILE *tmp;
ASSUME_BASE_TYPE(INK_CUSTOM);
if (!checkArgument(argc, argv, 1, INK_STRING)) {
return NULL_OBJ;
}
tmp = as<Ink_FilePointer>(base)->fp;
if (tmp)
fputs(getStringVal(argv[0]).c_str(), tmp);
return NULL_OBJ;
}
Ink_Object *InkNative_File_GetString(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *base = context->searchSlot("base");
FILE *tmp;
char buffer[FILE_GETS_BUFFER_SIZE] = { '\0' };
const char *tmp_str;
ASSUME_BASE_TYPE(INK_CUSTOM);
tmp = as<Ink_FilePointer>(base)->fp;
if (tmp) {
return new Ink_String(*StrPool_addStr(fgets(buffer, FILE_GETS_BUFFER_SIZE, tmp)));
}
return NULL_OBJ;
}
Ink_Object *InkNative_File_Flush(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *base = context->searchSlot("base");
FILE *tmp;
ASSUME_BASE_TYPE(INK_CUSTOM);
tmp = as<Ink_FilePointer>(base)->fp;
if (tmp)
fflush(tmp);
return NULL_OBJ;
}<commit_msg>271215#02: fix a unused variable warning<commit_after>#include <stdio.h>
#include <string>
#include "native.h"
#include "file.h"
#include "../general.h"
using namespace std;
inline string getStringVal(Ink_Object *str)
{
if (str->type == INK_STRING) {
return as<Ink_String>(str)->value;
}
return "";
}
Ink_Object *InkNative_File_Exist(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
if (!checkArgument(argc, argv, 1, INK_STRING)) {
return NULL_OBJ;
}
return new Ink_Numeric(!access(getStringVal(argv[0]).c_str(), 0));
}
Ink_Object *InkNative_File_Remove(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
if (!checkArgument(argc, argv, 1, INK_STRING)) {
return NULL_OBJ;
}
return new Ink_Numeric(!remove(getStringVal(argv[0]).c_str()));
}
Ink_Object *InkNative_File_Constructor(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *ret;
FILE *fp = NULL;
const char *tmp;
if (checkArgument(false, argc, argv, 2, INK_STRING, INK_STRING)) {
fp = fopen(tmp = getStringVal(argv[0]).c_str(), getStringVal(argv[1]).c_str());
if (!fp) {
InkWarn_Failed_Open_File(tmp);
}
} else if (checkArgument(false, argc, argv, 1, INK_STRING)) {
fp = fopen(tmp = getStringVal(argv[0]).c_str(), "r");
if (!fp) {
InkWarn_Failed_Open_File(tmp);
}
} else if (checkArgument(false, argc, argv, 1, INK_CUSTOM)) {
fp = as<Ink_FilePointer>(argv[0])->fp;
}
context->getLocal()->context->setSlot("this", ret = new Ink_FilePointer(fp));
return ret;
}
void Ink_FilePointer::setMethod()
{
setSlot("close", new Ink_FunctionObject(InkNative_File_Close));
setSlot("puts", new Ink_FunctionObject(InkNative_File_PutString));
setSlot("gets", new Ink_FunctionObject(InkNative_File_GetString));
setSlot("flush", new Ink_FunctionObject(InkNative_File_Flush));
return;
}
Ink_Object *InkNative_File_Close(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *base = context->searchSlot("base");
FILE *tmp;
ASSUME_BASE_TYPE(INK_CUSTOM);
tmp = as<Ink_FilePointer>(base)->fp;
if (tmp)
fclose(tmp);
return NULL_OBJ;
}
Ink_Object *InkNative_File_PutString(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *base = context->searchSlot("base");
FILE *tmp;
ASSUME_BASE_TYPE(INK_CUSTOM);
if (!checkArgument(argc, argv, 1, INK_STRING)) {
return NULL_OBJ;
}
tmp = as<Ink_FilePointer>(base)->fp;
if (tmp)
fputs(getStringVal(argv[0]).c_str(), tmp);
return NULL_OBJ;
}
Ink_Object *InkNative_File_GetString(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *base = context->searchSlot("base");
FILE *tmp;
char buffer[FILE_GETS_BUFFER_SIZE] = { '\0' };
ASSUME_BASE_TYPE(INK_CUSTOM);
tmp = as<Ink_FilePointer>(base)->fp;
if (tmp) {
return new Ink_String(*StrPool_addStr(fgets(buffer, FILE_GETS_BUFFER_SIZE, tmp)));
}
return NULL_OBJ;
}
Ink_Object *InkNative_File_Flush(Ink_ContextChain *context, unsigned int argc, Ink_Object **argv, Ink_Object *this_p)
{
Ink_Object *base = context->searchSlot("base");
FILE *tmp;
ASSUME_BASE_TYPE(INK_CUSTOM);
tmp = as<Ink_FilePointer>(base)->fp;
if (tmp)
fflush(tmp);
return NULL_OBJ;
}<|endoftext|> |
<commit_before><commit_msg>gtk3: if we have GTK_STATE_FLAG_CHECKED use only that bit<commit_after><|endoftext|> |
<commit_before>/*
* mcsignal_main.cpp
*
* Created by Tobias Wood on 12/11/2012.
* Copyright (c) 2013 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <string>
#include <iostream>
#include <getopt.h>
#include <exception>
#include <Eigen/Dense>
#include <Nifti/Nifti.h>
#include "QUIT/QUIT.h"
#include "Model.h"
using namespace std;
using namespace Eigen;
using namespace QUIT;
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: mcsignal [options]\n\
\n\
Calculates multi-component DESPOT signals (mainly for debugging mcdespot).\n\
The program will prompt for input (unless --no-prompt specified)\n\
\n\
All times (TR) are in SECONDS. All angles are in degrees.\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--verbose, -v : Print extra information.\n\
--mask, -m file : Only calculate inside the mask.\n\
--out, -o path : Add a prefix to the output filenames\n\
--B1, -b file : B1 Map file (ratio)\n\
--no-prompt, -n : Don't print prompts for input.\n\
--noise, -N val : Add complex noise with std=val.\n\
--1, --2, --3 : Use 1, 2 or 3 component sequences (default 3).\n\
--sequences, -M s : Use simple sequences (default).\n\
f : Use Finite Pulse Length correction.\n"
};
static auto components = Pools::Three;
static bool verbose = false, prompt = true, finitesequences = false;
static string outPrefix = "";
static double sigma = 0.;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"mask", required_argument, 0, 'm'},
{"out", required_argument, 0, 'o'},
{"no-prompt", no_argument, 0, 'n'},
{"noise", required_argument, 0, 'N'},
{"1", no_argument, 0, '1'},
{"2", no_argument, 0, '2'},
{"3", no_argument, 0, '3'},
{"sequences", no_argument, 0, 'M'},
{"B1", required_argument, 0, 'b'},
{0, 0, 0, 0}
};
//******************************************************************************
#pragma mark Read in all required files and data from cin
//******************************************************************************
void parseInput(Sequences &cs, vector<string> &names);
void parseInput(Sequences &cs, vector<string> &names) {
string type;
if (prompt) cout << "Specify next signal type (SPGR/SSFP): " << flush;
while (getline(cin, type) && (type != "END") && (type != "")) {
if (type != "SPGR" && type != "SSFP") {
throw(std::runtime_error("Unknown signal type: " + type));
}
if (prompt) cout << "Enter output filename: " << flush;
string filename;
getline(cin, filename);
names.push_back(filename);
if ((type == "SPGR") && !finitesequences) {
cs.addSequence(SequenceType::SPGR, prompt);
} else if ((type == "SPGR" && finitesequences)) {
cs.addSequence(SequenceType::SPGR_Finite, prompt);
} else if ((type == "SSFP" && !finitesequences)) {
cs.addSequence(SequenceType::SSFP, prompt);
} else if ((type == "SSFP" && finitesequences)) {
cs.addSequence(SequenceType::SSFP_Finite, prompt);
}
// Print message ready for next loop
string temp; getline(cin, temp); // Just to eat the newline
if (prompt) cout << "Specify next image type (SPGR/SSFP, END to finish input): " << flush;
}
}
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv)
{
//**************************************************************************
#pragma mark Argument Processing
//**************************************************************************
cout << version << endl << credit_me << endl;
Eigen::initParallel();
try { // To fix uncaught exceptions on Mac
Nifti::File maskFile, B1File;
MultiArray<int8_t, 3> maskVol;
MultiArray<float, 3> B1Vol;
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, "hvnN:m:o:b:123M:", long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'n': prompt = false; break;
case 'N': sigma = atof(optarg); break;
case 'm':
cout << "Reading mask file " << optarg << endl;
maskFile.open(optarg, Nifti::Mode::Read);
maskVol.resize(maskFile.matrix());
maskFile.readVolumes(maskVol.begin(), maskVol.end(), 0, 1);
break;
case 'o':
outPrefix = optarg;
cout << "Output prefix will be: " << outPrefix << endl;
break;
case 'b':
cout << "Reading B1 file: " << optarg << endl;
B1File.open(optarg, Nifti::Mode::Read);
B1Vol.resize(B1File.matrix());
B1File.readVolumes(B1Vol.begin(), B1Vol.end(), 0, 1);
break;
case '1': components = Pools::One; break;
case '2': components = Pools::Two; break;
case '3': components = Pools::Three; break;
case 'M':
switch (*optarg) {
case 's': finitesequences = false; if (prompt) cout << "Simple sequences selected." << endl; break;
case 'f': finitesequences = true; if (prompt) cout << "Finite pulse correction selected." << endl; break;
default:
cout << "Unknown sequences type " << *optarg << endl;
return EXIT_FAILURE;
break;
}
break;
case 'h':
case '?': // getopt will print an error message
default:
cout << usage << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 0) {
cerr << usage << endl << "Incorrect number of arguments." << endl;
return EXIT_FAILURE;
}
//**************************************************************************
#pragma mark Set up sequences
//**************************************************************************
Sequences sequences(Scale::None);
vector<string> filenames;
parseInput(sequences, filenames);
cout << sequences << endl;
//**************************************************************************
#pragma mark Read in parameter files
//**************************************************************************
// Build a Functor here so we can query number of parameters etc.
cout << "Using " << to_string(components) << " component sequences." << endl;
MultiArray<float, 4> paramsVols;
Nifti::Header templateHdr;
if (prompt) cout << "Loading parameters." << endl;
for (size_t i = 0; i < PoolInfo::nParameters(Pools::One); i++) {
if (prompt) cout << "Enter path to " << PoolInfo::Names(Pools::One)[i] << " file: " << flush;
string filename; cin >> filename;
cout << "Opening " << filename << endl;
Nifti::File input(filename);
if (i == 0) {
templateHdr = input.header();
paramsVols = MultiArray<float, 4>(input.matrix(), PoolInfo::nParameters(Pools::One));
} else {
if (!input.header().matchesSpace(templateHdr)) {
cout << "Mismatched input volumes" << endl;
return EXIT_FAILURE;
}
}
auto inVol = paramsVols.slice<3>({0,0,0,i},{-1,-1,-1,0});
cout << "Reading data." << endl;
input.readVolumes(inVol.begin(), inVol.end(), 0, 1);
}
const auto d = paramsVols.dims();
vector<MultiArray<complex<float>, 4>> signalVols(sequences.count()); //d.head(3), sequences.combinedSize());
for (size_t s = 0; s < sequences.count(); s++) {
signalVols[s] = MultiArray<complex<float>, 4>(d.head(3), sequences.sequence(s)->size());
}
cout << "Calculating..." << endl;
function<void (const size_t&)> calcVox = [&] (const size_t &k) {
for (size_t j = 0; j < d[1]; j++) {
for (size_t i = 0; i < d[0]; i++) {
if (!maskFile || (maskVol[{i,j,k}])) {
ArrayXd params = paramsVols.slice<1>({i,j,k,0},{0,0,0,-1}).asArray().cast<double>();
double B1 = B1File ? B1Vol[{i,j,k}] : 1.;
for (size_t s = 0; s < sequences.count(); s++) {
ArrayXcd signal = sequences.sequences()[s]->signal(components, params, B1);
ArrayXcd noise(sequences.size());
noise.real() = (ArrayXd::Ones(sequences.size()) * sigma).unaryExpr(function<double(double)>(randNorm<double>));
noise.imag() = (ArrayXd::Ones(sequences.size()) * sigma).unaryExpr(function<double(double)>(randNorm<double>));
signalVols[s].slice<1>({i,j,k,0},{0,0,0,-1}).asArray() = (signal + noise).cast<complex<float>>();
}
}
}
}
};
ThreadPool threads;
threads.for_loop(calcVox, d[2]);
cout << "Finished calculating." << endl;
cout << "Saving data." << endl;
templateHdr.setDatatype(Nifti::DataType::COMPLEX64);
size_t startVol = 0;
for (size_t i = 0; i < sequences.count(); i++) {
size_t thisSize = sequences.sequence(i)->size();
templateHdr.setDim(4, thisSize);
Nifti::File saveFile(templateHdr, outPrefix + filenames[i] + OutExt());
auto thisSignal = signalVols[i].slice<4>({0,0,0,startVol},{-1,-1,-1,thisSize});
saveFile.writeVolumes(thisSignal.begin(), thisSignal.end());
saveFile.close();
}
} catch (exception &e) {
cerr << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Changed order of reading parameter files and setting up sequences. Fixed bugs with sequence sizes.<commit_after>/*
* mcsignal_main.cpp
*
* Created by Tobias Wood on 12/11/2012.
* Copyright (c) 2013 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <string>
#include <iostream>
#include <getopt.h>
#include <exception>
#include <Eigen/Dense>
#include <Nifti/Nifti.h>
#include "QUIT/QUIT.h"
#include "Model.h"
using namespace std;
using namespace Eigen;
using namespace QUIT;
//******************************************************************************
// Arguments / Usage
//******************************************************************************
const string usage {
"Usage is: mcsignal [options]\n\
\n\
Calculates multi-component DESPOT signals (mainly for debugging mcdespot).\n\
The program will prompt for input (unless --no-prompt specified)\n\
\n\
All times (TR) are in SECONDS. All angles are in degrees.\n\
\n\
Options:\n\
--help, -h : Print this message.\n\
--verbose, -v : Print extra information.\n\
--mask, -m file : Only calculate inside the mask.\n\
--out, -o path : Add a prefix to the output filenames\n\
--B1, -b file : B1 Map file (ratio)\n\
--no-prompt, -n : Don't print prompts for input.\n\
--noise, -N val : Add complex noise with std=val.\n\
--1, --2, --3 : Use 1, 2 or 3 component sequences (default 3).\n\
--sequences, -M s : Use simple sequences (default).\n\
f : Use Finite Pulse Length correction.\n"
};
static auto components = Pools::One;
static bool verbose = false, prompt = true, finitesequences = false;
static string outPrefix = "";
static double sigma = 0.;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"mask", required_argument, 0, 'm'},
{"out", required_argument, 0, 'o'},
{"no-prompt", no_argument, 0, 'n'},
{"noise", required_argument, 0, 'N'},
{"1", no_argument, 0, '1'},
{"2", no_argument, 0, '2'},
{"3", no_argument, 0, '3'},
{"sequences", no_argument, 0, 'M'},
{"B1", required_argument, 0, 'b'},
{0, 0, 0, 0}
};
//******************************************************************************
#pragma mark Read in all required files and data from cin
//******************************************************************************
void parseInput(Sequences &cs, vector<string> &names);
void parseInput(Sequences &cs, vector<string> &names) {
string type;
if (prompt) cout << "Specify next signal type (SPGR/SSFP): " << flush;
while (getline(cin, type) && (type != "END") && (type != "")) {
if (type != "SPGR" && type != "SSFP") {
throw(std::runtime_error("Unknown signal type: " + type));
}
if (prompt) cout << "Enter output filename: " << flush;
string filename;
getline(cin, filename);
names.push_back(filename);
if ((type == "SPGR") && !finitesequences) {
cs.addSequence(SequenceType::SPGR, prompt);
} else if ((type == "SPGR" && finitesequences)) {
cs.addSequence(SequenceType::SPGR_Finite, prompt);
} else if ((type == "SSFP" && !finitesequences)) {
cs.addSequence(SequenceType::SSFP, prompt);
} else if ((type == "SSFP" && finitesequences)) {
cs.addSequence(SequenceType::SSFP_Finite, prompt);
}
// Print message ready for next loop
if (prompt) cout << "Specify next image type (SPGR/SSFP, END to finish input): " << flush;
}
}
//******************************************************************************
// Main
//******************************************************************************
int main(int argc, char **argv)
{
//**************************************************************************
#pragma mark Argument Processing
//**************************************************************************
cout << version << endl << credit_me << endl;
Eigen::initParallel();
try { // To fix uncaught exceptions on Mac
Nifti::File maskFile, B1File;
MultiArray<int8_t, 3> maskVol;
MultiArray<float, 3> B1Vol;
int indexptr = 0, c;
while ((c = getopt_long(argc, argv, "hvnN:m:o:b:123M:", long_options, &indexptr)) != -1) {
switch (c) {
case 'v': verbose = true; break;
case 'n': prompt = false; break;
case 'N': sigma = atof(optarg); break;
case 'm':
cout << "Reading mask file " << optarg << endl;
maskFile.open(optarg, Nifti::Mode::Read);
maskVol.resize(maskFile.matrix());
maskFile.readVolumes(maskVol.begin(), maskVol.end(), 0, 1);
break;
case 'o':
outPrefix = optarg;
cout << "Output prefix will be: " << outPrefix << endl;
break;
case 'b':
cout << "Reading B1 file: " << optarg << endl;
B1File.open(optarg, Nifti::Mode::Read);
B1Vol.resize(B1File.matrix());
B1File.readVolumes(B1Vol.begin(), B1Vol.end(), 0, 1);
break;
case '1': components = Pools::One; break;
case '2': components = Pools::Two; break;
case '3': components = Pools::Three; break;
case 'M':
switch (*optarg) {
case 's': finitesequences = false; if (prompt) cout << "Simple sequences selected." << endl; break;
case 'f': finitesequences = true; if (prompt) cout << "Finite pulse correction selected." << endl; break;
default:
cout << "Unknown sequences type " << *optarg << endl;
return EXIT_FAILURE;
break;
}
break;
case 'h':
case '?': // getopt will print an error message
default:
cout << usage << endl;
return EXIT_FAILURE;
}
}
if ((argc - optind) != 0) {
cerr << usage << endl << "Incorrect number of arguments." << endl;
return EXIT_FAILURE;
}
/**************************************************************************
* Read in parameter files
*************************************************************************/
cout << "Using " << to_string(components) << " component sequences." << endl;
MultiArray<float, 4> paramsVols;
Nifti::Header templateHdr;
if (prompt) cout << "Loading parameters." << endl;
for (size_t i = 0; i < PoolInfo::nParameters(components); i++) {
if (prompt) cout << "Enter path to " << PoolInfo::Names(components)[i] << " file: " << flush;
string filename; getline(cin,filename);
cout << "Opening " << filename << endl;
Nifti::File input(filename);
if (i == 0) {
templateHdr = input.header();
paramsVols = MultiArray<float, 4>(input.matrix(), PoolInfo::nParameters(components));
} else {
if (!input.header().matchesSpace(templateHdr)) {
cout << "Mismatched input volumes" << endl;
return EXIT_FAILURE;
}
}
auto inVol = paramsVols.slice<3>({0,0,0,i},{-1,-1,-1,0});
cout << "Reading data." << endl;
input.readVolumes(inVol.begin(), inVol.end(), 0, 1);
}
const auto d = paramsVols.dims();
//**************************************************************************
#pragma mark Set up sequences
//**************************************************************************
Sequences sequences(Scale::None);
vector<string> filenames;
parseInput(sequences, filenames);
cout << sequences << endl;
vector<MultiArray<complex<float>, 4>> signalVols(sequences.count()); //d.head(3), sequences.combinedSize());
for (size_t s = 0; s < sequences.count(); s++) {
signalVols[s] = MultiArray<complex<float>, 4>(d.head(3), sequences.sequence(s)->size());
}
cout << "Calculating..." << endl;
function<void (const size_t&)> calcVox = [&] (const size_t &k) {
for (size_t j = 0; j < d[1]; j++) {
for (size_t i = 0; i < d[0]; i++) {
if (!maskFile || (maskVol[{i,j,k}])) {
ArrayXd params = paramsVols.slice<1>({i,j,k,0},{0,0,0,-1}).asArray().cast<double>();
double B1 = B1File ? B1Vol[{i,j,k}] : 1.;
for (size_t s = 0; s < sequences.count(); s++) {
const size_t sigsize = sequences.sequences()[s]->size();
ArrayXcd signal = sequences.sequences()[s]->signal(components, params, B1);
ArrayXcd noise(sigsize);
noise.real() = (ArrayXd::Ones(sigsize) * sigma).unaryExpr(function<double(double)>(randNorm<double>));
noise.imag() = (ArrayXd::Ones(sigsize) * sigma).unaryExpr(function<double(double)>(randNorm<double>));
signalVols[s].slice<1>({i,j,k,0},{0,0,0,-1}).asArray() = (signal + noise).cast<complex<float>>();
}
}
}
}
};
ThreadPool threads;
threads.for_loop(calcVox, d[2]);
cout << "Finished calculating." << endl;
cout << "Saving data." << endl;
templateHdr.setDatatype(Nifti::DataType::COMPLEX64);
size_t startVol = 0;
for (size_t i = 0; i < sequences.count(); i++) {
size_t thisSize = sequences.sequence(i)->size();
templateHdr.setDim(4, thisSize);
Nifti::File saveFile(templateHdr, outPrefix + filenames[i]);
auto thisSignal = signalVols[i].slice<4>({0,0,0,startVol},{-1,-1,-1,thisSize});
saveFile.writeVolumes(thisSignal.begin(), thisSignal.end());
saveFile.close();
}
} catch (exception &e) {
cerr << e.what() << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "FirebaseArduino.h"
void FirebaseArduino::begin(const char* host, const char* auth) {
http_.reset(FirebaseHttpClient::create());
http_->setReuseConnection(true);
host_ = host;
auth_ = auth;
}
String FirebaseArduino::FirebaseArduino::push(const String& path, const JsonVariant& value) {
String buf;
value.printTo(buf);
auto push = FirebasePush(host_, auth_, path, buf, http_.get());
error_ = push.error();
return push.name();
}
void FirebaseArduino::set(const String& path, const JsonVariant& value) {
String buf;
value.printTo(buf);
auto set = FirebaseSet(host_, auth_, path, buf, http_.get());
error_ = set.error();
}
FirebaseObject FirebaseArduino::get(const char* path) {
auto get = FirebaseGet(host_, auth_, path, http_.get());
error_ = get.error();
if (!error_) {
return FirebaseObject{""};
}
return FirebaseObject(get.response());
}
void FirebaseArduino::remove(const char* path) {
auto remove = FirebaseRemove(host_, auth_, path, http_.get());
error_ = remove.error();
}
void FirebaseArduino::stream(const char* path) {
auto stream = FirebaseStream(host_, auth_, path, http_.get());
error_ = stream.error();
}
bool FirebaseArduino::available() {
return http_->getStreamPtr()->available();
}
FirebaseObject FirebaseArduino::readEvent() {
auto client = http_->getStreamPtr();
String type = client->readStringUntil('\n').substring(7);;
String event = client->readStringUntil('\n').substring(6);
client->readStringUntil('\n'); // consume separator
FirebaseObject obj = FirebaseObject(event);
obj["type"] = type;
return obj;
}
bool FirebaseArduino::success() {
return error_.code() == 0;
}
bool FirebaseArduino::failed() {
return error_.code() != 0;
}
const String& FirebaseArduino::error() {
return error_.message();
}
FirebaseArduino Firebase;
<commit_msg>FirebaseArduino: fix get error checking<commit_after>//
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "FirebaseArduino.h"
void FirebaseArduino::begin(const char* host, const char* auth) {
http_.reset(FirebaseHttpClient::create());
http_->setReuseConnection(true);
host_ = host;
auth_ = auth;
}
String FirebaseArduino::FirebaseArduino::push(const String& path, const JsonVariant& value) {
String buf;
value.printTo(buf);
auto push = FirebasePush(host_, auth_, path, buf, http_.get());
error_ = push.error();
return push.name();
}
void FirebaseArduino::set(const String& path, const JsonVariant& value) {
String buf;
value.printTo(buf);
auto set = FirebaseSet(host_, auth_, path, buf, http_.get());
error_ = set.error();
}
FirebaseObject FirebaseArduino::get(const char* path) {
auto get = FirebaseGet(host_, auth_, path, http_.get());
error_ = get.error();
if (failed()) {
return FirebaseObject{""};
}
return FirebaseObject(get.response());
}
void FirebaseArduino::remove(const char* path) {
auto remove = FirebaseRemove(host_, auth_, path, http_.get());
error_ = remove.error();
}
void FirebaseArduino::stream(const char* path) {
auto stream = FirebaseStream(host_, auth_, path, http_.get());
error_ = stream.error();
}
bool FirebaseArduino::available() {
return http_->getStreamPtr()->available();
}
FirebaseObject FirebaseArduino::readEvent() {
auto client = http_->getStreamPtr();
String type = client->readStringUntil('\n').substring(7);;
String event = client->readStringUntil('\n').substring(6);
client->readStringUntil('\n'); // consume separator
FirebaseObject obj = FirebaseObject(event);
obj["type"] = type;
return obj;
}
bool FirebaseArduino::success() {
return error_.code() == 0;
}
bool FirebaseArduino::failed() {
return error_.code() != 0;
}
const String& FirebaseArduino::error() {
return error_.message();
}
FirebaseArduino Firebase;
<|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.
*/
#include <sstream>
#include "Compiler.hh"
#include "Types.hh"
#include "Schema.hh"
#include "ValidSchema.hh"
#include "Stream.hh"
#include "json/JsonDom.hh"
extern void yyparse(void *ctx);
using std::string;
using std::map;
using std::vector;
namespace rmf_avro {
typedef map<Name, NodePtr> SymbolTable;
using json::Entity;
// #define DEBUG_VERBOSE
static NodePtr makePrimitive(const std::string& t)
{
if (t == "null") {
return NodePtr(new NodePrimitive(AVRO_NULL));
} else if (t == "boolean") {
return NodePtr(new NodePrimitive(AVRO_BOOL));
} else if (t == "int") {
return NodePtr(new NodePrimitive(AVRO_INT));
} else if (t == "long") {
return NodePtr(new NodePrimitive(AVRO_LONG));
} else if (t == "float") {
return NodePtr(new NodePrimitive(AVRO_FLOAT));
} else if (t == "double") {
return NodePtr(new NodePrimitive(AVRO_DOUBLE));
} else if (t == "string") {
return NodePtr(new NodePrimitive(AVRO_STRING));
} else if (t == "bytes") {
return NodePtr(new NodePrimitive(AVRO_BYTES));
} else {
return NodePtr();
}
}
static NodePtr makeNode(const json::Entity& e, SymbolTable& st, const string& ns);
template <typename T>
concepts::SingleAttribute<T> asSingleAttribute(const T& t)
{
concepts::SingleAttribute<T> n;
n.add(t);
return n;
}
static bool isFullName(const string& s)
{
return s.find('.') != string::npos;
}
static Name getName(const string& name, const string& ns)
{
return (isFullName(name)) ? Name(name) : Name(name, ns);
}
static NodePtr makeNode(const std::string& t, SymbolTable& st, const string& ns)
{
NodePtr result = makePrimitive(t);
if (result) {
return result;
}
Name n = getName(t, ns);
map<Name, NodePtr>::const_iterator it = st.find(n);
if (it != st.end()) {
return NodePtr(new NodeSymbolic(asSingleAttribute(n), it->second));
}
throw Exception(boost::format("Unknown type: %1%") % n.fullname());
}
const map<string, Entity>::const_iterator findField(const Entity& e,
const map<string, Entity>& m, const string& fieldName)
{
map<string, Entity>::const_iterator it = m.find(fieldName);
if (it == m.end()) {
throw Exception(boost::format("Missing Json field \"%1%\": %2%") %
fieldName % e.toString());
} else {
return it;
}
}
template<typename T>
const T& getField(const Entity& e, const map<string, Entity>& m,
const string& fieldName)
{
map<string, Entity>::const_iterator it = findField(e, m, fieldName);
if (it->second.type() != json::type_traits<T>::type()) {
throw Exception(boost::format(
"Json field \"%1%\" is not a %2%: %3%") %
fieldName % json::type_traits<T>::name() %
it->second.toString());
} else {
return it->second.value<T>();
}
}
struct Field {
const string& name;
const NodePtr value;
Field(const string& n, const NodePtr& v) : name(n), value(v) { }
};
static Field makeField(const Entity& e, SymbolTable& st, const string& ns)
{
const map<string, Entity>& m = e.value<map<string, Entity> >();
const string& n = getField<string>(e, m, "name");
map<string, Entity>::const_iterator it = findField(e, m, "type");
return Field(n, makeNode(it->second, st, ns));
}
static NodePtr makeRecordNode(const Entity& e,
const Name& name, const map<string, Entity>& m, SymbolTable& st, const string& ns)
{
const vector<Entity>& v = getField<vector<Entity> >(e, m, "fields");
concepts::MultiAttribute<string> fieldNames;
concepts::MultiAttribute<NodePtr> fieldValues;
for (vector<Entity>::const_iterator it = v.begin(); it != v.end(); ++it) {
Field f = makeField(*it, st, ns);
fieldNames.add(f.name);
fieldValues.add(f.value);
}
return NodePtr(new NodeRecord(asSingleAttribute(name),
fieldValues, fieldNames));
}
static NodePtr makeEnumNode(const Entity& e,
const Name& name, const map<string, Entity>& m)
{
const vector<Entity>& v = getField<vector<Entity> >(e, m, "symbols");
concepts::MultiAttribute<string> symbols;
for (vector<Entity>::const_iterator it = v.begin(); it != v.end(); ++it) {
if (it->type() != json::etString) {
throw Exception(boost::format("Enum symbol not a string: %1%") %
it->toString());
}
symbols.add(it->value<string>());
}
return NodePtr(new NodeEnum(asSingleAttribute(name), symbols));
}
static NodePtr makeFixedNode(const Entity& e,
const Name& name, const map<string, Entity>& m)
{
int v = static_cast<int>(getField<int64_t>(e, m, "size"));
if (v <= 0) {
throw Exception(boost::format("Size for fixed is not positive: ") %
e.toString());
}
return NodePtr(new NodeFixed(asSingleAttribute(name),
asSingleAttribute(v)));
}
static NodePtr makeArrayNode(const Entity& e, const map<string, Entity>& m,
SymbolTable& st, const string& ns)
{
map<string, Entity>::const_iterator it = findField(e, m, "items");
return NodePtr(new NodeArray(asSingleAttribute(
makeNode(it->second, st, ns))));
}
static NodePtr makeMapNode(const Entity& e, const map<string, Entity>& m,
SymbolTable& st, const string& ns)
{
map<string, Entity>::const_iterator it = findField(e, m, "values");
return NodePtr(new NodeMap(asSingleAttribute(
makeNode(it->second, st, ns))));
}
static Name getName(const Entity& e, const map<string, Entity>& m, const string& ns)
{
const string& name = getField<string>(e, m, "name");
if (isFullName(name)) {
return Name(name);
} else {
map<string, Entity>::const_iterator it = m.find("namespace");
if (it != m.end()) {
if (it->second.type() != json::type_traits<string>::type()) {
throw Exception(boost::format(
"Json field \"%1%\" is not a %2%: %3%") %
"namespace" % json::type_traits<string>::name() %
it->second.toString());
}
Name result = Name(name, it->second.value<string>());
return result;
}
return Name(name, ns);
}
}
static NodePtr makeNode(const Entity& e, const map<string, Entity>& m,
SymbolTable& st, const string& ns)
{
const string& type = getField<string>(e, m, "type");
if (NodePtr result = makePrimitive(type)) {
if (m.size() > 1) {
throw Exception(boost::format(
"Unknown additional Json fields: %1%")
% e.toString());
} else {
return result;
}
} else if (type == "record" || type == "error" ||
type == "enum" || type == "fixed") {
Name nm = getName(e, m, ns);
NodePtr result;
if (type == "record" || type == "error") {
result = NodePtr(new NodeRecord());
st[nm] = result;
NodePtr r = makeRecordNode(e, nm, m, st, nm.ns());
(boost::dynamic_pointer_cast<NodeRecord>(r))->swap(
*boost::dynamic_pointer_cast<NodeRecord>(result));
} else {
result = (type == "enum") ? makeEnumNode(e, nm, m) :
makeFixedNode(e, nm, m);
st[nm] = result;
}
return result;
} else if (type == "array") {
return makeArrayNode(e, m, st, ns);
} else if (type == "map") {
return makeMapNode(e, m, st, ns);
}
throw Exception(boost::format("Unknown type definition: %1%")
% e.toString());
}
static NodePtr makeNode(const Entity& e, const vector<Entity>& m,
SymbolTable& st, const string& ns)
{
concepts::MultiAttribute<NodePtr> mm;
for (vector<Entity>::const_iterator it = m.begin(); it != m.end(); ++it) {
mm.add(makeNode(*it, st, ns));
}
return NodePtr(new NodeUnion(mm));
}
static NodePtr makeNode(const json::Entity& e, SymbolTable& st, const string& ns)
{
switch (e.type()) {
case json::etString:
return makeNode(e.value<string>(), st, ns);
case json::etObject:
return makeNode(e, e.value<map<string, Entity> >(), st, ns);
case json::etArray:
return makeNode(e, e.value<vector<Entity> >(), st, ns);
default:
throw Exception(boost::format("Invalid Avro type: %1%") % e.toString());
}
}
AVRO_DECL ValidSchema compileJsonSchemaFromStream(InputStream& is)
{
json::Entity e = json::loadEntity(is);
SymbolTable st;
NodePtr n = makeNode(e, st, "");
return ValidSchema(n);
}
AVRO_DECL ValidSchema compileJsonSchemaFromMemory(const uint8_t* input, size_t len)
{
return compileJsonSchemaFromStream(*memoryInputStream(input, len));
}
AVRO_DECL ValidSchema compileJsonSchemaFromString(const char* input)
{
return compileJsonSchemaFromMemory(reinterpret_cast<const uint8_t*>(input),
::strlen(input));
}
static ValidSchema compile(std::istream& is)
{
std::auto_ptr<InputStream> in = istreamInputStream(is);
return compileJsonSchemaFromStream(*in);
}
AVRO_DECL void compileJsonSchema(std::istream &is, ValidSchema &schema)
{
if (!is.good()) {
throw Exception("Input stream is not good");
}
schema = compile(is);
}
AVRO_DECL bool compileJsonSchema(std::istream &is, ValidSchema &schema, std::string &error)
{
try {
compileJsonSchema(is, schema);
return true;
} catch (const Exception &e) {
error = e.what();
return false;
}
}
} // namespace rmf_avro
<commit_msg>remove stray export decls<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.
*/
#include <sstream>
#include "Compiler.hh"
#include "Types.hh"
#include "Schema.hh"
#include "ValidSchema.hh"
#include "Stream.hh"
#include "json/JsonDom.hh"
extern void yyparse(void *ctx);
using std::string;
using std::map;
using std::vector;
namespace rmf_avro {
typedef map<Name, NodePtr> SymbolTable;
using json::Entity;
// #define DEBUG_VERBOSE
static NodePtr makePrimitive(const std::string& t)
{
if (t == "null") {
return NodePtr(new NodePrimitive(AVRO_NULL));
} else if (t == "boolean") {
return NodePtr(new NodePrimitive(AVRO_BOOL));
} else if (t == "int") {
return NodePtr(new NodePrimitive(AVRO_INT));
} else if (t == "long") {
return NodePtr(new NodePrimitive(AVRO_LONG));
} else if (t == "float") {
return NodePtr(new NodePrimitive(AVRO_FLOAT));
} else if (t == "double") {
return NodePtr(new NodePrimitive(AVRO_DOUBLE));
} else if (t == "string") {
return NodePtr(new NodePrimitive(AVRO_STRING));
} else if (t == "bytes") {
return NodePtr(new NodePrimitive(AVRO_BYTES));
} else {
return NodePtr();
}
}
static NodePtr makeNode(const json::Entity& e, SymbolTable& st, const string& ns);
template <typename T>
concepts::SingleAttribute<T> asSingleAttribute(const T& t)
{
concepts::SingleAttribute<T> n;
n.add(t);
return n;
}
static bool isFullName(const string& s)
{
return s.find('.') != string::npos;
}
static Name getName(const string& name, const string& ns)
{
return (isFullName(name)) ? Name(name) : Name(name, ns);
}
static NodePtr makeNode(const std::string& t, SymbolTable& st, const string& ns)
{
NodePtr result = makePrimitive(t);
if (result) {
return result;
}
Name n = getName(t, ns);
map<Name, NodePtr>::const_iterator it = st.find(n);
if (it != st.end()) {
return NodePtr(new NodeSymbolic(asSingleAttribute(n), it->second));
}
throw Exception(boost::format("Unknown type: %1%") % n.fullname());
}
const map<string, Entity>::const_iterator findField(const Entity& e,
const map<string, Entity>& m, const string& fieldName)
{
map<string, Entity>::const_iterator it = m.find(fieldName);
if (it == m.end()) {
throw Exception(boost::format("Missing Json field \"%1%\": %2%") %
fieldName % e.toString());
} else {
return it;
}
}
template<typename T>
const T& getField(const Entity& e, const map<string, Entity>& m,
const string& fieldName)
{
map<string, Entity>::const_iterator it = findField(e, m, fieldName);
if (it->second.type() != json::type_traits<T>::type()) {
throw Exception(boost::format(
"Json field \"%1%\" is not a %2%: %3%") %
fieldName % json::type_traits<T>::name() %
it->second.toString());
} else {
return it->second.value<T>();
}
}
struct Field {
const string& name;
const NodePtr value;
Field(const string& n, const NodePtr& v) : name(n), value(v) { }
};
static Field makeField(const Entity& e, SymbolTable& st, const string& ns)
{
const map<string, Entity>& m = e.value<map<string, Entity> >();
const string& n = getField<string>(e, m, "name");
map<string, Entity>::const_iterator it = findField(e, m, "type");
return Field(n, makeNode(it->second, st, ns));
}
static NodePtr makeRecordNode(const Entity& e,
const Name& name, const map<string, Entity>& m, SymbolTable& st, const string& ns)
{
const vector<Entity>& v = getField<vector<Entity> >(e, m, "fields");
concepts::MultiAttribute<string> fieldNames;
concepts::MultiAttribute<NodePtr> fieldValues;
for (vector<Entity>::const_iterator it = v.begin(); it != v.end(); ++it) {
Field f = makeField(*it, st, ns);
fieldNames.add(f.name);
fieldValues.add(f.value);
}
return NodePtr(new NodeRecord(asSingleAttribute(name),
fieldValues, fieldNames));
}
static NodePtr makeEnumNode(const Entity& e,
const Name& name, const map<string, Entity>& m)
{
const vector<Entity>& v = getField<vector<Entity> >(e, m, "symbols");
concepts::MultiAttribute<string> symbols;
for (vector<Entity>::const_iterator it = v.begin(); it != v.end(); ++it) {
if (it->type() != json::etString) {
throw Exception(boost::format("Enum symbol not a string: %1%") %
it->toString());
}
symbols.add(it->value<string>());
}
return NodePtr(new NodeEnum(asSingleAttribute(name), symbols));
}
static NodePtr makeFixedNode(const Entity& e,
const Name& name, const map<string, Entity>& m)
{
int v = static_cast<int>(getField<int64_t>(e, m, "size"));
if (v <= 0) {
throw Exception(boost::format("Size for fixed is not positive: ") %
e.toString());
}
return NodePtr(new NodeFixed(asSingleAttribute(name),
asSingleAttribute(v)));
}
static NodePtr makeArrayNode(const Entity& e, const map<string, Entity>& m,
SymbolTable& st, const string& ns)
{
map<string, Entity>::const_iterator it = findField(e, m, "items");
return NodePtr(new NodeArray(asSingleAttribute(
makeNode(it->second, st, ns))));
}
static NodePtr makeMapNode(const Entity& e, const map<string, Entity>& m,
SymbolTable& st, const string& ns)
{
map<string, Entity>::const_iterator it = findField(e, m, "values");
return NodePtr(new NodeMap(asSingleAttribute(
makeNode(it->second, st, ns))));
}
static Name getName(const Entity& e, const map<string, Entity>& m, const string& ns)
{
const string& name = getField<string>(e, m, "name");
if (isFullName(name)) {
return Name(name);
} else {
map<string, Entity>::const_iterator it = m.find("namespace");
if (it != m.end()) {
if (it->second.type() != json::type_traits<string>::type()) {
throw Exception(boost::format(
"Json field \"%1%\" is not a %2%: %3%") %
"namespace" % json::type_traits<string>::name() %
it->second.toString());
}
Name result = Name(name, it->second.value<string>());
return result;
}
return Name(name, ns);
}
}
static NodePtr makeNode(const Entity& e, const map<string, Entity>& m,
SymbolTable& st, const string& ns)
{
const string& type = getField<string>(e, m, "type");
if (NodePtr result = makePrimitive(type)) {
if (m.size() > 1) {
throw Exception(boost::format(
"Unknown additional Json fields: %1%")
% e.toString());
} else {
return result;
}
} else if (type == "record" || type == "error" ||
type == "enum" || type == "fixed") {
Name nm = getName(e, m, ns);
NodePtr result;
if (type == "record" || type == "error") {
result = NodePtr(new NodeRecord());
st[nm] = result;
NodePtr r = makeRecordNode(e, nm, m, st, nm.ns());
(boost::dynamic_pointer_cast<NodeRecord>(r))->swap(
*boost::dynamic_pointer_cast<NodeRecord>(result));
} else {
result = (type == "enum") ? makeEnumNode(e, nm, m) :
makeFixedNode(e, nm, m);
st[nm] = result;
}
return result;
} else if (type == "array") {
return makeArrayNode(e, m, st, ns);
} else if (type == "map") {
return makeMapNode(e, m, st, ns);
}
throw Exception(boost::format("Unknown type definition: %1%")
% e.toString());
}
static NodePtr makeNode(const Entity& e, const vector<Entity>& m,
SymbolTable& st, const string& ns)
{
concepts::MultiAttribute<NodePtr> mm;
for (vector<Entity>::const_iterator it = m.begin(); it != m.end(); ++it) {
mm.add(makeNode(*it, st, ns));
}
return NodePtr(new NodeUnion(mm));
}
static NodePtr makeNode(const json::Entity& e, SymbolTable& st, const string& ns)
{
switch (e.type()) {
case json::etString:
return makeNode(e.value<string>(), st, ns);
case json::etObject:
return makeNode(e, e.value<map<string, Entity> >(), st, ns);
case json::etArray:
return makeNode(e, e.value<vector<Entity> >(), st, ns);
default:
throw Exception(boost::format("Invalid Avro type: %1%") % e.toString());
}
}
ValidSchema compileJsonSchemaFromStream(InputStream& is)
{
json::Entity e = json::loadEntity(is);
SymbolTable st;
NodePtr n = makeNode(e, st, "");
return ValidSchema(n);
}
ValidSchema compileJsonSchemaFromMemory(const uint8_t* input, size_t len)
{
return compileJsonSchemaFromStream(*memoryInputStream(input, len));
}
ValidSchema compileJsonSchemaFromString(const char* input)
{
return compileJsonSchemaFromMemory(reinterpret_cast<const uint8_t*>(input),
::strlen(input));
}
static ValidSchema compile(std::istream& is)
{
std::auto_ptr<InputStream> in = istreamInputStream(is);
return compileJsonSchemaFromStream(*in);
}
void compileJsonSchema(std::istream &is, ValidSchema &schema)
{
if (!is.good()) {
throw Exception("Input stream is not good");
}
schema = compile(is);
}
bool compileJsonSchema(std::istream &is, ValidSchema &schema, std::string &error)
{
try {
compileJsonSchema(is, schema);
return true;
} catch (const Exception &e) {
error = e.what();
return false;
}
}
} // namespace rmf_avro
<|endoftext|> |
<commit_before>#include "wayland.h"
#include <../x/x_keycodes.h>
#include <iostream>
#include <algorithm>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <linux/input-event-codes.h>
#include <QuickDraw.h>
using namespace wayland;
using namespace Executor;
constexpr int16_t rgnStop = 32767;
WaylandVideoDriver::SharedMem::SharedMem(size_t size)
: size_(size)
{
fd_ = memfd_create("executor", MFD_CLOEXEC);
ftruncate(fd_, size_);
mem_ = mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
}
WaylandVideoDriver::SharedMem::~SharedMem()
{
if(mem_)
{
munmap(mem_, size_);
close(fd_);
}
}
WaylandVideoDriver::Buffer::Buffer(shm_t& shm, int w, int h)
: mem_(w * h * 4),
wlbuffer_(shm.create_pool(mem_.fd(), mem_.size())
.create_buffer(0, w, h, w*4, wayland::shm_format::argb8888)),
width_(w), height_(h)
{
}
void WaylandVideoDriver::setColors(int num_colors, const Executor::vdriver_color_t *color_array)
{
for(int i = 0; i < num_colors; i++)
{
colors_[i] = (0xFF << 24)
| ((color_array[i].red >> 8) << 16)
| ((color_array[i].green >> 8) << 8)
| (color_array[i].blue >> 8);
}
}
bool WaylandVideoDriver::setMode(int width, int height, int bpp,
bool grayscale_p)
{
if(xdg_wm_base_)
return true;
rootlessRegion_ = { 0, 0, rgnStop, rgnStop };
registry_ = display_.get_registry();
registry_.on_global() = [this] (uint32_t name, const std::string& interface, uint32_t version) {
if(interface == compositor_t::interface_name)
registry_.bind(name, compositor_, version);
else if(interface == shell_t::interface_name)
registry_.bind(name, shell_, version);
else if(interface == xdg_wm_base_t::interface_name)
registry_.bind(name, xdg_wm_base_, version);
else if(interface == seat_t::interface_name)
registry_.bind(name, seat_, version);
else if(interface == shm_t::interface_name)
registry_.bind(name, shm_, version);
// TODO: handle changes
};
display_.roundtrip();
// TODO:
xdg_wm_base_.on_ping() = [this] (uint32_t serial) { xdg_wm_base_.pong(serial); };
surface_ = compositor_.create_surface();
xdg_surface_ = xdg_wm_base_.get_xdg_surface(surface_);
xdg_toplevel_ = xdg_surface_.get_toplevel();
xdg_toplevel_.set_title("Executor");
xdg_toplevel_.set_app_id("io.github.autc04.executor");
xdg_toplevel_.on_configure() = [this] (int32_t x, int32_t y, array_t states) {
//configuredX = std::max(0,x);
//configuredY = std::max(0,y);
if(x && y && !initDone_)
{
width_ = x;
height_ = y;
}
std::vector<xdg_toplevel_state> states1 = states;
std::cout << "toplevel configure " << x << " " << y << "\n";
};
auto fillBuffer = [this](Buffer& buf) {
//uint32_t colors[] = { 0xFFFFFF00, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0x80808080 };
int w = buf.width(), h = buf.height();
uint32_t color = 0x80808080;//colors[colorIdx];
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++)
{
uint32_t& pixel = ((uint32_t*)buf.data())[y * w + x];
if(x < w/3 || x > 2*w/3)
pixel = color;
else
pixel = 0;
}
};
xdg_surface_.on_configure() = [this, fillBuffer] (uint32_t serial) {
xdg_surface_.ack_configure(serial);
if(width_ == buffer_.width() && height_ == buffer_.height())
return;
//updateScreenRects(0,nullptr,false);
buffer_ = Buffer(shm_, width_, height_);
fillBuffer(buffer_);
surface_.attach(buffer_.wlbuffer(), 0, 0);
surface_.commit();
};
xdg_toplevel_.on_close() = [this] () { };
pointer_ = seat_.get_pointer();
pointer_.on_button() = [this] (uint32_t serial, uint32_t time, uint32_t button, pointer_button_state state) {
std::cout << "button: " << button << " " << (int)state << std::endl;
if(button == BTN_LEFT)
callbacks_->mouseButtonEvent(state == pointer_button_state::pressed);
};
pointer_.on_motion() = [this] (uint32_t serial, double x, double y) {
std::cout << "motion: " << x << " " << y << std::endl;
callbacks_->mouseMoved(x, y);
};
keyboard_ = seat_.get_keyboard();
keyboard_.on_key() = [this] (uint32_t serial, uint32_t time, uint32_t key, keyboard_key_state state) {
bool down = state == keyboard_key_state::pressed;
std::cout << "key: " << std::hex << key << std::dec << " " << (down ? "down" : "up") << std::endl;
auto mkvkey = x_keycode_to_mac_virt[key + 8];
callbacks_->keyboardEvent(down, mkvkey);
};
keyboard_.on_enter() = [this] (uint32_t serial, wayland::surface_t, wayland::array_t) {
callbacks_->resumeEvent(true);
};
keyboard_.on_leave() = [this] (uint32_t serial, wayland::surface_t) {
callbacks_->suspendEvent();
};
width_ = 1024;
height_ = 768;
bpp_ = 8;
xdg_toplevel_.set_maximized();
surface_.commit();
cursorBuffer_ = Buffer(shm_, 16,16);
cursorSurface_ = compositor_.create_surface();
hotSpot_ = {0,0};
display_.roundtrip();
cursorSurface_.attach(cursorBuffer_.wlbuffer(), 0, 0);
cursorSurface_.commit();
//pointer_.set_cursor(0, cursorSurface_, hotSpot_.first, hotSpot_.second);
//display_.roundtrip();
pointer_.on_enter() = [this](uint32_t serial, surface_t surface, double x, double y) {
pointer_.set_cursor(serial, cursorSurface_, hotSpot_.first, hotSpot_.second);
cursorEnterSerial_ = serial;
};
rowBytes_ = ((width_ * bpp_ + 31) & ~31) / 8;
framebuffer_ = new uint8_t[rowBytes_ * height_];
initDone_ = true;
isRootless_ = true;
return true;
}
void WaylandVideoDriver::pumpEvents()
{
//display_.dispatch();
display_.roundtrip();
}
void WaylandVideoDriver::setRootlessRegion(RgnHandle rgn)
{
if((*rgn)->rgnSize == 10)
{
rootlessRegion_.clear();
rootlessRegion_.insert(rootlessRegion_.end(),
{ (*rgn)->rgnBBox.top.get(), (*rgn)->rgnBBox.left.get(), (*rgn)->rgnBBox.right.get(), rgnStop,
(*rgn)->rgnBBox.bottom.get(), (*rgn)->rgnBBox.left.get(), (*rgn)->rgnBBox.right.get(), rgnStop,
rgnStop });
}
else
{
GUEST<uint16_t> *p = (GUEST<uint16_t>*) ((*(Handle)rgn) + 10);
GUEST<uint16_t> *q = (GUEST<uint16_t>*) ((*(Handle)rgn) + (*rgn)->rgnSize);
rootlessRegion_.clear();
rootlessRegion_.insert(rootlessRegion_.end(), p, q);
}
std::vector<int> rgnRow;
std::vector<int> rgnTmp;
auto rgnIt = rootlessRegion_.begin();
rgnRow.push_back(rgnStop);
region_t waylandRgn = compositor_.create_region();
int from = *rgnIt, to;
while(from < height_)
{
++rgnIt;
auto end = rgnIt;
while(*end != rgnStop)
++end;
std::set_symmetric_difference(rgnRow.begin(), rgnRow.end(), rgnIt, end, std::back_inserter(rgnTmp));
swap(rgnRow, rgnTmp);
rgnTmp.clear();
rgnIt = end;
++rgnIt;
to = *rgnIt;
for(int i = 0; i + 1 < rgnRow.size(); i += 2)
{
waylandRgn.add(rgnRow[i], from, rgnRow[i+1] - rgnRow[i], to - from);
}
from = to;
}
surface_.set_input_region(waylandRgn);
}
void WaylandVideoDriver::updateScreenRects(
int num_rects, const vdriver_rect_t *r,
bool cursor_p)
{
std::cout << "update.\n";
//buffer_ = Buffer(shm_, width_, height_);
uint32_t *screen = reinterpret_cast<uint32_t*>(buffer_.data());
std::vector<int> rgnRow;
std::vector<int> rgnTmp;
auto rgnIt = rootlessRegion_.begin();
rgnRow.push_back(rgnStop);
for(int y = 0; y < height_; y++)
{
while(y >= *rgnIt)
{
++rgnIt;
auto end = rgnIt;
while(*end != rgnStop)
++end;
std::set_symmetric_difference(rgnRow.begin(), rgnRow.end(), rgnIt, end, std::back_inserter(rgnTmp));
swap(rgnRow, rgnTmp);
rgnTmp.clear();
rgnIt = end;
++rgnIt;
}
auto rowIt = rgnRow.begin();
int x = 0;
while(x < width_)
{
int nextX = std::min(width_, *rowIt++);
for(; x < nextX; x++)
{
uint32_t pixel = colors_[framebuffer_[y * rowBytes_ + x]];
screen[y * width_ + x] = pixel == 0xFFFFFFFF ? 0 : pixel;
}
if(x >= width_)
break;
nextX = std::min(width_, *rowIt++);
for(; x < nextX; x++)
screen[y * width_ + x] = colors_[framebuffer_[y * rowBytes_ + x]];
}
}
for(int i = 0; i < num_rects; i++)
surface_.damage_buffer(r[i].left,r[i].top,r[i].right-r[i].left,r[i].bottom-r[i].top);
surface_.attach(buffer_.wlbuffer(), 0, 0);
surface_.commit();
display_.flush();
}
void WaylandVideoDriver::setCursor(char *cursor_data, uint16_t cursor_mask[16], int hotspot_x, int hotspot_y)
{
uint32_t *dst = reinterpret_cast<uint32_t*>(cursorBuffer_.data());
uint8_t *data = reinterpret_cast<uint8_t*>(cursor_data);
uint8_t *mask = reinterpret_cast<uint8_t*>(cursor_mask);
for(int y = 0; y < 16; y++)
for(int x = 0; x < 16; x++)
{
if(mask[2*y + x/8] & (0x80 >> x%8))
*dst++ = (data[2*y + x/8] & (0x80 >> x%8)) ? 0xFF000000 : 0xFFFFFFFF;
else
*dst++ = (data[2*y + x/8] & (0x80 >> x%8)) ? 0xFF000000 : 0;
}
cursorSurface_.damage_buffer(0,0,16,16);
cursorSurface_.attach(cursorBuffer_.wlbuffer(), 0, 0);
hotSpot_ = { hotspot_x, hotspot_y };
cursorSurface_.commit();
pointer_.set_cursor(cursorEnterSerial_, cursorSurface_, hotSpot_.first, hotSpot_.second);
}
bool WaylandVideoDriver::setCursorVisible(bool show_p)
{
pointer_.set_cursor(cursorEnterSerial_, show_p ? cursorSurface_ : surface_t(), hotSpot_.first, hotSpot_.second);
return true;
}
<commit_msg>factor out RegionProcessor<commit_after>#include "wayland.h"
#include <../x/x_keycodes.h>
#include <iostream>
#include <algorithm>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <linux/input-event-codes.h>
#include <QuickDraw.h>
using namespace wayland;
using namespace Executor;
constexpr int16_t rgnStop = 32767;
WaylandVideoDriver::SharedMem::SharedMem(size_t size)
: size_(size)
{
fd_ = memfd_create("executor", MFD_CLOEXEC);
ftruncate(fd_, size_);
mem_ = mmap(nullptr, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
}
WaylandVideoDriver::SharedMem::~SharedMem()
{
if(mem_)
{
munmap(mem_, size_);
close(fd_);
}
}
WaylandVideoDriver::Buffer::Buffer(shm_t& shm, int w, int h)
: mem_(w * h * 4),
wlbuffer_(shm.create_pool(mem_.fd(), mem_.size())
.create_buffer(0, w, h, w*4, wayland::shm_format::argb8888)),
width_(w), height_(h)
{
}
void WaylandVideoDriver::setColors(int num_colors, const Executor::vdriver_color_t *color_array)
{
for(int i = 0; i < num_colors; i++)
{
colors_[i] = (0xFF << 24)
| ((color_array[i].red >> 8) << 16)
| ((color_array[i].green >> 8) << 8)
| (color_array[i].blue >> 8);
}
}
bool WaylandVideoDriver::setMode(int width, int height, int bpp,
bool grayscale_p)
{
if(xdg_wm_base_)
return true;
rootlessRegion_ = { 0, 0, rgnStop, rgnStop };
registry_ = display_.get_registry();
registry_.on_global() = [this] (uint32_t name, const std::string& interface, uint32_t version) {
if(interface == compositor_t::interface_name)
registry_.bind(name, compositor_, version);
else if(interface == shell_t::interface_name)
registry_.bind(name, shell_, version);
else if(interface == xdg_wm_base_t::interface_name)
registry_.bind(name, xdg_wm_base_, version);
else if(interface == seat_t::interface_name)
registry_.bind(name, seat_, version);
else if(interface == shm_t::interface_name)
registry_.bind(name, shm_, version);
// TODO: handle changes
};
display_.roundtrip();
// TODO:
xdg_wm_base_.on_ping() = [this] (uint32_t serial) { xdg_wm_base_.pong(serial); };
surface_ = compositor_.create_surface();
xdg_surface_ = xdg_wm_base_.get_xdg_surface(surface_);
xdg_toplevel_ = xdg_surface_.get_toplevel();
xdg_toplevel_.set_title("Executor");
xdg_toplevel_.set_app_id("io.github.autc04.executor");
xdg_toplevel_.on_configure() = [this] (int32_t x, int32_t y, array_t states) {
//configuredX = std::max(0,x);
//configuredY = std::max(0,y);
if(x && y && !initDone_)
{
width_ = x;
height_ = y;
}
std::vector<xdg_toplevel_state> states1 = states;
std::cout << "toplevel configure " << x << " " << y << "\n";
};
auto fillBuffer = [this](Buffer& buf) {
//uint32_t colors[] = { 0xFFFFFF00, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0x80808080 };
int w = buf.width(), h = buf.height();
uint32_t color = 0x80808080;//colors[colorIdx];
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++)
{
uint32_t& pixel = ((uint32_t*)buf.data())[y * w + x];
if(x < w/3 || x > 2*w/3)
pixel = color;
else
pixel = 0;
}
};
xdg_surface_.on_configure() = [this, fillBuffer] (uint32_t serial) {
xdg_surface_.ack_configure(serial);
if(width_ == buffer_.width() && height_ == buffer_.height())
return;
//updateScreenRects(0,nullptr,false);
buffer_ = Buffer(shm_, width_, height_);
fillBuffer(buffer_);
surface_.attach(buffer_.wlbuffer(), 0, 0);
surface_.commit();
};
xdg_toplevel_.on_close() = [this] () { };
pointer_ = seat_.get_pointer();
pointer_.on_button() = [this] (uint32_t serial, uint32_t time, uint32_t button, pointer_button_state state) {
std::cout << "button: " << button << " " << (int)state << std::endl;
if(button == BTN_LEFT)
callbacks_->mouseButtonEvent(state == pointer_button_state::pressed);
};
pointer_.on_motion() = [this] (uint32_t serial, double x, double y) {
std::cout << "motion: " << x << " " << y << std::endl;
callbacks_->mouseMoved(x, y);
};
keyboard_ = seat_.get_keyboard();
keyboard_.on_key() = [this] (uint32_t serial, uint32_t time, uint32_t key, keyboard_key_state state) {
bool down = state == keyboard_key_state::pressed;
std::cout << "key: " << std::hex << key << std::dec << " " << (down ? "down" : "up") << std::endl;
auto mkvkey = x_keycode_to_mac_virt[key + 8];
callbacks_->keyboardEvent(down, mkvkey);
};
keyboard_.on_enter() = [this] (uint32_t serial, wayland::surface_t, wayland::array_t) {
callbacks_->resumeEvent(true);
};
keyboard_.on_leave() = [this] (uint32_t serial, wayland::surface_t) {
callbacks_->suspendEvent();
};
width_ = 1024;
height_ = 768;
bpp_ = 8;
xdg_toplevel_.set_maximized();
surface_.commit();
cursorBuffer_ = Buffer(shm_, 16,16);
cursorSurface_ = compositor_.create_surface();
hotSpot_ = {0,0};
display_.roundtrip();
cursorSurface_.attach(cursorBuffer_.wlbuffer(), 0, 0);
cursorSurface_.commit();
//pointer_.set_cursor(0, cursorSurface_, hotSpot_.first, hotSpot_.second);
//display_.roundtrip();
pointer_.on_enter() = [this](uint32_t serial, surface_t surface, double x, double y) {
pointer_.set_cursor(serial, cursorSurface_, hotSpot_.first, hotSpot_.second);
cursorEnterSerial_ = serial;
};
rowBytes_ = ((width_ * bpp_ + 31) & ~31) / 8;
framebuffer_ = new uint8_t[rowBytes_ * height_];
initDone_ = true;
isRootless_ = true;
return true;
}
void WaylandVideoDriver::pumpEvents()
{
//display_.dispatch();
display_.roundtrip();
}
template<typename Iterator>
struct RegionProcessor
{
std::vector<int16_t> row { rgnStop };
std::vector<int16_t> tmp;
Iterator it;
int16_t top_;
RegionProcessor(Iterator rgnIt)
: it(rgnIt)
{
}
void advance()
{
top_ = *it++;
auto end = it;
while(*end != rgnStop)
++end;
std::set_symmetric_difference(row.begin(), row.end(), it, end, std::back_inserter(tmp));
swap(row, tmp);
tmp.clear();
it = end;
++it;
}
int16_t bottom() const { return *it; }
int16_t top() const { return top_; }
};
void WaylandVideoDriver::setRootlessRegion(RgnHandle rgn)
{
if((*rgn)->rgnSize == 10)
{
rootlessRegion_.clear();
rootlessRegion_.insert(rootlessRegion_.end(),
{ (*rgn)->rgnBBox.top.get(), (*rgn)->rgnBBox.left.get(), (*rgn)->rgnBBox.right.get(), rgnStop,
(*rgn)->rgnBBox.bottom.get(), (*rgn)->rgnBBox.left.get(), (*rgn)->rgnBBox.right.get(), rgnStop,
rgnStop });
}
else
{
GUEST<uint16_t> *p = (GUEST<uint16_t>*) ((*(Handle)rgn) + 10);
GUEST<uint16_t> *q = (GUEST<uint16_t>*) ((*(Handle)rgn) + (*rgn)->rgnSize);
rootlessRegion_.clear();
rootlessRegion_.insert(rootlessRegion_.end(), p, q);
}
RegionProcessor rgnP(rootlessRegion_.begin());
region_t waylandRgn = compositor_.create_region();
int from = *rgnP.it, to;
while(from < height_)
{
rgnP.advance();
to = *rgnP.it;
for(int i = 0; i + 1 < rgnP.row.size(); i += 2)
{
waylandRgn.add(rgnP.row[i], from, rgnP.row[i+1] - rgnP.row[i], to - from);
}
from = to;
}
surface_.set_input_region(waylandRgn);
}
void WaylandVideoDriver::updateScreenRects(
int num_rects, const vdriver_rect_t *r,
bool cursor_p)
{
std::cout << "update.\n";
//buffer_ = Buffer(shm_, width_, height_);
uint32_t *screen = reinterpret_cast<uint32_t*>(buffer_.data());
RegionProcessor rgnP(rootlessRegion_.begin());
for(int y = 0; y < height_; y++)
{
while(y >= *rgnP.it)
rgnP.advance();
auto rowIt = rgnP.row.begin();
int x = 0;
while(x < width_)
{
int nextX = std::min(width_, (int)*rowIt++);
for(; x < nextX; x++)
{
uint32_t pixel = colors_[framebuffer_[y * rowBytes_ + x]];
screen[y * width_ + x] = pixel == 0xFFFFFFFF ? 0 : pixel;
}
if(x >= width_)
break;
nextX = std::min(width_, (int)*rowIt++);
for(; x < nextX; x++)
screen[y * width_ + x] = colors_[framebuffer_[y * rowBytes_ + x]];
}
}
for(int i = 0; i < num_rects; i++)
surface_.damage_buffer(r[i].left,r[i].top,r[i].right-r[i].left,r[i].bottom-r[i].top);
surface_.attach(buffer_.wlbuffer(), 0, 0);
surface_.commit();
display_.flush();
}
void WaylandVideoDriver::setCursor(char *cursor_data, uint16_t cursor_mask[16], int hotspot_x, int hotspot_y)
{
uint32_t *dst = reinterpret_cast<uint32_t*>(cursorBuffer_.data());
uint8_t *data = reinterpret_cast<uint8_t*>(cursor_data);
uint8_t *mask = reinterpret_cast<uint8_t*>(cursor_mask);
for(int y = 0; y < 16; y++)
for(int x = 0; x < 16; x++)
{
if(mask[2*y + x/8] & (0x80 >> x%8))
*dst++ = (data[2*y + x/8] & (0x80 >> x%8)) ? 0xFF000000 : 0xFFFFFFFF;
else
*dst++ = (data[2*y + x/8] & (0x80 >> x%8)) ? 0xFF000000 : 0;
}
cursorSurface_.damage_buffer(0,0,16,16);
cursorSurface_.attach(cursorBuffer_.wlbuffer(), 0, 0);
hotSpot_ = { hotspot_x, hotspot_y };
cursorSurface_.commit();
pointer_.set_cursor(cursorEnterSerial_, cursorSurface_, hotSpot_.first, hotSpot_.second);
}
bool WaylandVideoDriver::setCursorVisible(bool show_p)
{
pointer_.set_cursor(cursorEnterSerial_, show_p ? cursorSurface_ : surface_t(), hotSpot_.first, hotSpot_.second);
return true;
}
<|endoftext|> |
<commit_before>/* The following has been auto-generated by makedll.pl */
#ifndef ecmdDllCapi_H
#define ecmdDllCapi_H
#include <inttypes.h>
#include <vector>
#include <string>
#include <ecmdStructs.H>
#include <ecmdReturnCodes.H>
#include <ecmdDataBuffer.H>
extern "C" {
/* Dll Common load function - verifies version */
uint32_t dllLoadDll (const char * i_version, uint32_t debugLevel);
/* Dll Specific load function - used by Cronus/GFW to init variables/object models*/
uint32_t dllInitDll ();
/* Dll Common unload function */
uint32_t dllUnloadDll ();
/* Dll Specific unload function - deallocates variables/object models*/
uint32_t dllFreeDll();
/* Dll Common Command Line Args Function*/
uint32_t dllCommonCommandArgs(int* io_argc, char** io_argv[]);
/* Dll Specific Command Line Args Function*/
uint32_t dllSpecificCommandArgs(int* io_argc, char** io_argv[]);
uint32_t dllQueryDllInfo(ecmdDllInfo & o_dllInfo);
uint32_t dllQueryConfig(ecmdChipTarget & i_target, ecmdQueryData & o_queryData, ecmdQueryDetail_t i_detail );
uint32_t dllQuerySelected(ecmdChipTarget & io_target, ecmdQueryData & o_queryData);
uint32_t dllQueryRing(ecmdChipTarget & i_target, std::list<ecmdRingData> & o_queryData, const char * i_ringName );
uint32_t dllQueryArray(ecmdChipTarget & i_target, ecmdArrayData & o_queryData, const char * i_arrayName);
uint32_t dllQuerySpy(ecmdChipTarget & i_target, ecmdSpyData & o_queryData, const char * i_spyName);
uint32_t dllQueryFileLocation(ecmdChipTarget & i_target, ecmdFileType_t i_fileType, std::string & o_fileLocation);
uint32_t dllGetRing(ecmdChipTarget & i_target, const char * i_ringName, ecmdDataBuffer & o_data);
uint32_t dllPutRing(ecmdChipTarget & i_target, const char * i_ringName, ecmdDataBuffer & i_data);
uint32_t dllGetLatch(ecmdChipTarget & i_target, const char* i_ringName, const char * i_latchName, std::list<ecmdLatchEntry> & o_data, ecmdLatchMode_t i_mode);
uint32_t dllPutLatch(ecmdChipTarget & i_target, const char* i_ringName, const char * i_latchName, ecmdDataBuffer & i_data, ecmdLatchMode_t i_mode);
uint32_t dllGetScom(ecmdChipTarget & i_target, uint32_t i_address, ecmdDataBuffer & o_data);
uint32_t dllPutScom(ecmdChipTarget & i_target, uint32_t i_address, ecmdDataBuffer & i_data);
uint32_t dllSendCmd(ecmdChipTarget & i_target, uint32_t i_instruction, uint32_t i_modifier, ecmdDataBuffer & o_status);
uint32_t dllGetCfamRegister(ecmdChipTarget & i_target, uint32_t i_address, ecmdDataBuffer & o_data);
uint32_t dllPutCfamRegister(ecmdChipTarget & i_target, uint32_t i_address, ecmdDataBuffer & i_data);
uint32_t dllGetSpy(ecmdChipTarget & i_target, const char * i_spyName, ecmdDataBuffer & o_data);
uint32_t dllGetSpyEnum(ecmdChipTarget & i_target, const char * i_spyName, std::string & o_enumValue);
uint32_t dllGetSpyEccGrouping(ecmdChipTarget & i_target, const char * i_spyEccGroupName, ecmdDataBuffer & o_groupData, ecmdDataBuffer & o_eccData, ecmdDataBuffer & o_eccErrorMask);
uint32_t dllPutSpy(ecmdChipTarget & i_target, const char * i_spyName, ecmdDataBuffer & i_data);
uint32_t dllPutSpyEnum(ecmdChipTarget & i_target, const char * i_spyName, const std::string i_enumValue);
void dllEnableRingCache();
uint32_t dllDisableRingCache();
uint32_t dllFlushRingCache();
bool dllIsRingCacheEnabled();
uint32_t dllGetArray(ecmdChipTarget & i_target, const char * i_arrayName, ecmdDataBuffer & i_address, ecmdDataBuffer & o_data);
uint32_t dllGetArrayMultiple(ecmdChipTarget & i_target, const char * i_arrayName, std::list<ecmdArrayEntry> & io_entries);
uint32_t dllPutArray(ecmdChipTarget & i_target, const char * i_arrayName, ecmdDataBuffer & i_address, ecmdDataBuffer & i_data);
uint32_t dllPutArrayMultiple(ecmdChipTarget & i_target, const char * i_arrayName, std::list<ecmdArrayEntry> & i_entries);
uint32_t dllQueryClockState(ecmdChipTarget & i_target, const char * i_clockDomain, ecmdClockState_t o_clockState);
uint32_t dllStartClocks(ecmdChipTarget & i_target, const char * i_clockDomain, bool i_forceState );
uint32_t dllStopClocks(ecmdChipTarget & i_target, const char * i_clockDomain, bool i_forceState );
uint32_t dllISteps(ecmdDataBuffer & i_steps);
uint32_t dllQueryProcRegisterInfo(ecmdChipTarget & i_target, const char* i_name, ecmdProcRegisterInfo & o_data);
uint32_t dllGetSpr(ecmdChipTarget & i_target, const char * i_sprName, ecmdDataBuffer & o_data);
uint32_t dllGetSprMultiple(ecmdChipTarget & i_target, std::list<ecmdNameEntry> & io_entries);
uint32_t dllPutSpr(ecmdChipTarget & i_target, const char * i_sprName, ecmdDataBuffer & i_data);
uint32_t dllPutSprMultiple(ecmdChipTarget & i_target, std::list<ecmdNameEntry> & i_entries);
uint32_t dllGetGpr(ecmdChipTarget & i_target, uint32_t i_gprNum, ecmdDataBuffer & o_data);
uint32_t dllGetGprMultiple(ecmdChipTarget & i_target, std::list<ecmdIndexEntry> & io_entries);
uint32_t dllPutGpr(ecmdChipTarget & i_target, uint32_t i_gprNum, ecmdDataBuffer & i_data);
uint32_t dllPutGprMultiple(ecmdChipTarget & i_target, std::list<ecmdIndexEntry> & i_entries);
uint32_t dllGetFpr(ecmdChipTarget & i_target, uint32_t i_fprNum, ecmdDataBuffer & o_data);
uint32_t dllGetFprMultiple(ecmdChipTarget & i_target, std::list<ecmdIndexEntry> & io_entries);
uint32_t dllPutFpr(ecmdChipTarget & i_target, uint32_t i_fprNum, ecmdDataBuffer & i_data);
uint32_t dllPutFprMultiple(ecmdChipTarget & i_target, std::list<ecmdIndexEntry> & i_entries);
uint32_t dllGetTraceArray(ecmdChipTarget & i_target, const char* i_name, std::vector <ecmdDataBuffer> & o_data);
uint32_t dllGetTraceArrayMultiple(ecmdChipTarget & i_target, std::list <ecmdNameVectorEntry> & o_data);
uint32_t dllGetMemProc(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & o_data);
uint32_t dllPutMemProc(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & i_data);
uint32_t dllGetMemDma(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & o_data);
uint32_t dllPutMemDma(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & i_data);
uint32_t dllGetMemMemCtrl(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & o_data);
uint32_t dllPutMemMemCtrl(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & i_data);
uint32_t dllSimaet(const char* i_function);
uint32_t dllSimcheckpoint(const char* i_checkpoint);
uint32_t dllSimclock(uint32_t i_cycles);
uint32_t dllSimecho(const char* i_message);
uint32_t dllSimexit(uint32_t i_rc , const char* i_message );
uint32_t dllSimEXPECTFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_expect, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimexpecttcfac(const char* i_tcfacname, uint32_t i_bitlength, ecmdDataBuffer & i_expect, uint32_t i_row );
uint32_t dllSimgetcurrentcycle(uint32_t & o_cyclecount);
uint32_t dllSimGETFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & o_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimGETFACX(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & o_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimgettcfac(const char* i_tcfacname, ecmdDataBuffer & o_data, uint32_t i_row , uint32_t i_startbit , uint32_t i_bitlength );
uint32_t dllSiminit(const char* i_checkpoint);
uint32_t dllSimPOLLFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_expect, uint32_t i_row , uint32_t i_offset , uint32_t i_maxcycles , uint32_t i_pollinterval );
uint32_t dllSimPUTFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimPUTFACX(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimputtcfac(const char* i_tcfacname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_numrows );
uint32_t dllSimrestart(const char* i_checkpoint);
uint32_t dllSimSTKFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimstktcfac(const char* i_tcfacname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_numrows );
uint32_t dllSimSUBCMD(const char* i_command);
uint32_t dllSimtckinterval(uint32_t i_tckinterval);
uint32_t dllSimUNSTICK(const char* i_facname, uint32_t i_bitlength, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimunsticktcfac(const char* i_tcfacname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_numrows );
std::string dllGetErrorMsg(uint32_t i_errorCode);
uint32_t dllRegisterErrorMsg(uint32_t i_errorCode, const char* i_whom, const char* i_message);
void dllOutputError(const char* i_message);
void dllOutputWarning(const char* i_message);
void dllOutput(const char* i_message);
uint32_t dllGetGlobalVar(ecmdGlobalVarType_t i_type);
void dllSetTraceMode(ecmdTraceType_t i_type, bool i_enable);
bool dllQueryTraceMode(ecmdTraceType_t i_type);
uint32_t dllGetConfiguration(std::string i_name, std::string & o_value);
uint32_t dllSetConfiguration(std::string i_name, std::string i_value);
uint32_t dllDeconfigureTarget(ecmdChipTarget & i_target);
uint32_t dllConfigureTarget(ecmdChipTarget & i_target);
} //extern C
#endif
/* The previous has been auto-generated by makedll.pl */
<commit_msg>Added include of ecmdUtils.H<commit_after>/* The following has been auto-generated by makedll.pl */
#ifndef ecmdDllCapi_H
#define ecmdDllCapi_H
#include <inttypes.h>
#include <vector>
#include <string>
#include <ecmdStructs.H>
#include <ecmdUtils.H>
#include <ecmdReturnCodes.H>
#include <ecmdDataBuffer.H>
extern "C" {
/* Dll Common load function - verifies version */
uint32_t dllLoadDll (const char * i_version, uint32_t debugLevel);
/* Dll Specific load function - used by Cronus/GFW to init variables/object models*/
uint32_t dllInitDll ();
/* Dll Common unload function */
uint32_t dllUnloadDll ();
/* Dll Specific unload function - deallocates variables/object models*/
uint32_t dllFreeDll();
/* Dll Common Command Line Args Function*/
uint32_t dllCommonCommandArgs(int* io_argc, char** io_argv[]);
/* Dll Specific Command Line Args Function*/
uint32_t dllSpecificCommandArgs(int* io_argc, char** io_argv[]);
uint32_t dllQueryDllInfo(ecmdDllInfo & o_dllInfo);
uint32_t dllQueryConfig(ecmdChipTarget & i_target, ecmdQueryData & o_queryData, ecmdQueryDetail_t i_detail );
uint32_t dllQuerySelected(ecmdChipTarget & io_target, ecmdQueryData & o_queryData);
uint32_t dllQueryRing(ecmdChipTarget & i_target, std::list<ecmdRingData> & o_queryData, const char * i_ringName );
uint32_t dllQueryArray(ecmdChipTarget & i_target, ecmdArrayData & o_queryData, const char * i_arrayName);
uint32_t dllQuerySpy(ecmdChipTarget & i_target, ecmdSpyData & o_queryData, const char * i_spyName);
uint32_t dllQueryFileLocation(ecmdChipTarget & i_target, ecmdFileType_t i_fileType, std::string & o_fileLocation);
uint32_t dllGetRing(ecmdChipTarget & i_target, const char * i_ringName, ecmdDataBuffer & o_data);
uint32_t dllPutRing(ecmdChipTarget & i_target, const char * i_ringName, ecmdDataBuffer & i_data);
uint32_t dllGetLatch(ecmdChipTarget & i_target, const char* i_ringName, const char * i_latchName, std::list<ecmdLatchEntry> & o_data, ecmdLatchMode_t i_mode);
uint32_t dllPutLatch(ecmdChipTarget & i_target, const char* i_ringName, const char * i_latchName, ecmdDataBuffer & i_data, ecmdLatchMode_t i_mode);
uint32_t dllGetScom(ecmdChipTarget & i_target, uint32_t i_address, ecmdDataBuffer & o_data);
uint32_t dllPutScom(ecmdChipTarget & i_target, uint32_t i_address, ecmdDataBuffer & i_data);
uint32_t dllSendCmd(ecmdChipTarget & i_target, uint32_t i_instruction, uint32_t i_modifier, ecmdDataBuffer & o_status);
uint32_t dllGetCfamRegister(ecmdChipTarget & i_target, uint32_t i_address, ecmdDataBuffer & o_data);
uint32_t dllPutCfamRegister(ecmdChipTarget & i_target, uint32_t i_address, ecmdDataBuffer & i_data);
uint32_t dllGetSpy(ecmdChipTarget & i_target, const char * i_spyName, ecmdDataBuffer & o_data);
uint32_t dllGetSpyEnum(ecmdChipTarget & i_target, const char * i_spyName, std::string & o_enumValue);
uint32_t dllGetSpyEccGrouping(ecmdChipTarget & i_target, const char * i_spyEccGroupName, ecmdDataBuffer & o_groupData, ecmdDataBuffer & o_eccData, ecmdDataBuffer & o_eccErrorMask);
uint32_t dllPutSpy(ecmdChipTarget & i_target, const char * i_spyName, ecmdDataBuffer & i_data);
uint32_t dllPutSpyEnum(ecmdChipTarget & i_target, const char * i_spyName, const std::string i_enumValue);
void dllEnableRingCache();
uint32_t dllDisableRingCache();
uint32_t dllFlushRingCache();
bool dllIsRingCacheEnabled();
uint32_t dllGetArray(ecmdChipTarget & i_target, const char * i_arrayName, ecmdDataBuffer & i_address, ecmdDataBuffer & o_data);
uint32_t dllGetArrayMultiple(ecmdChipTarget & i_target, const char * i_arrayName, std::list<ecmdArrayEntry> & io_entries);
uint32_t dllPutArray(ecmdChipTarget & i_target, const char * i_arrayName, ecmdDataBuffer & i_address, ecmdDataBuffer & i_data);
uint32_t dllPutArrayMultiple(ecmdChipTarget & i_target, const char * i_arrayName, std::list<ecmdArrayEntry> & i_entries);
uint32_t dllQueryClockState(ecmdChipTarget & i_target, const char * i_clockDomain, ecmdClockState_t o_clockState);
uint32_t dllStartClocks(ecmdChipTarget & i_target, const char * i_clockDomain, bool i_forceState );
uint32_t dllStopClocks(ecmdChipTarget & i_target, const char * i_clockDomain, bool i_forceState );
uint32_t dllISteps(ecmdDataBuffer & i_steps);
uint32_t dllQueryProcRegisterInfo(ecmdChipTarget & i_target, const char* i_name, ecmdProcRegisterInfo & o_data);
uint32_t dllGetSpr(ecmdChipTarget & i_target, const char * i_sprName, ecmdDataBuffer & o_data);
uint32_t dllGetSprMultiple(ecmdChipTarget & i_target, std::list<ecmdNameEntry> & io_entries);
uint32_t dllPutSpr(ecmdChipTarget & i_target, const char * i_sprName, ecmdDataBuffer & i_data);
uint32_t dllPutSprMultiple(ecmdChipTarget & i_target, std::list<ecmdNameEntry> & i_entries);
uint32_t dllGetGpr(ecmdChipTarget & i_target, uint32_t i_gprNum, ecmdDataBuffer & o_data);
uint32_t dllGetGprMultiple(ecmdChipTarget & i_target, std::list<ecmdIndexEntry> & io_entries);
uint32_t dllPutGpr(ecmdChipTarget & i_target, uint32_t i_gprNum, ecmdDataBuffer & i_data);
uint32_t dllPutGprMultiple(ecmdChipTarget & i_target, std::list<ecmdIndexEntry> & i_entries);
uint32_t dllGetFpr(ecmdChipTarget & i_target, uint32_t i_fprNum, ecmdDataBuffer & o_data);
uint32_t dllGetFprMultiple(ecmdChipTarget & i_target, std::list<ecmdIndexEntry> & io_entries);
uint32_t dllPutFpr(ecmdChipTarget & i_target, uint32_t i_fprNum, ecmdDataBuffer & i_data);
uint32_t dllPutFprMultiple(ecmdChipTarget & i_target, std::list<ecmdIndexEntry> & i_entries);
uint32_t dllGetTraceArray(ecmdChipTarget & i_target, const char* i_name, std::vector <ecmdDataBuffer> & o_data);
uint32_t dllGetTraceArrayMultiple(ecmdChipTarget & i_target, std::list <ecmdNameVectorEntry> & o_data);
uint32_t dllGetMemProc(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & o_data);
uint32_t dllPutMemProc(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & i_data);
uint32_t dllGetMemDma(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & o_data);
uint32_t dllPutMemDma(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & i_data);
uint32_t dllGetMemMemCtrl(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & o_data);
uint32_t dllPutMemMemCtrl(ecmdChipTarget & i_target, uint64_t i_address, uint32_t i_bytes, ecmdDataBuffer & i_data);
uint32_t dllSimaet(const char* i_function);
uint32_t dllSimcheckpoint(const char* i_checkpoint);
uint32_t dllSimclock(uint32_t i_cycles);
uint32_t dllSimecho(const char* i_message);
uint32_t dllSimexit(uint32_t i_rc , const char* i_message );
uint32_t dllSimEXPECTFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_expect, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimexpecttcfac(const char* i_tcfacname, uint32_t i_bitlength, ecmdDataBuffer & i_expect, uint32_t i_row );
uint32_t dllSimgetcurrentcycle(uint32_t & o_cyclecount);
uint32_t dllSimGETFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & o_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimGETFACX(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & o_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimgettcfac(const char* i_tcfacname, ecmdDataBuffer & o_data, uint32_t i_row , uint32_t i_startbit , uint32_t i_bitlength );
uint32_t dllSiminit(const char* i_checkpoint);
uint32_t dllSimPOLLFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_expect, uint32_t i_row , uint32_t i_offset , uint32_t i_maxcycles , uint32_t i_pollinterval );
uint32_t dllSimPUTFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimPUTFACX(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimputtcfac(const char* i_tcfacname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_numrows );
uint32_t dllSimrestart(const char* i_checkpoint);
uint32_t dllSimSTKFAC(const char* i_facname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimstktcfac(const char* i_tcfacname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_numrows );
uint32_t dllSimSUBCMD(const char* i_command);
uint32_t dllSimtckinterval(uint32_t i_tckinterval);
uint32_t dllSimUNSTICK(const char* i_facname, uint32_t i_bitlength, uint32_t i_row , uint32_t i_offset );
uint32_t dllSimunsticktcfac(const char* i_tcfacname, uint32_t i_bitlength, ecmdDataBuffer & i_data, uint32_t i_row , uint32_t i_numrows );
std::string dllGetErrorMsg(uint32_t i_errorCode);
uint32_t dllRegisterErrorMsg(uint32_t i_errorCode, const char* i_whom, const char* i_message);
void dllOutputError(const char* i_message);
void dllOutputWarning(const char* i_message);
void dllOutput(const char* i_message);
uint32_t dllGetGlobalVar(ecmdGlobalVarType_t i_type);
void dllSetTraceMode(ecmdTraceType_t i_type, bool i_enable);
bool dllQueryTraceMode(ecmdTraceType_t i_type);
uint32_t dllGetConfiguration(std::string i_name, std::string & o_value);
uint32_t dllSetConfiguration(std::string i_name, std::string i_value);
uint32_t dllDeconfigureTarget(ecmdChipTarget & i_target);
uint32_t dllConfigureTarget(ecmdChipTarget & i_target);
} //extern C
#endif
/* The previous has been auto-generated by makedll.pl */
<|endoftext|> |
<commit_before>/*
* REnvironmentPosix.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/REnvironment.hpp>
#include <algorithm>
#include <boost/algorithm/string/trim.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/ConfigUtils.hpp>
#include <core/system/System.hpp>
namespace core {
namespace r_util {
namespace {
// MacOS X Specific
#ifdef __APPLE__
#define kLibRFileName "libR.dylib"
#define kLibraryPathEnvVariable "DYLD_LIBRARY_PATH"
// no extra paths on the mac
std::string extraLibraryPaths(const FilePath& ldPathsScript,
const std::string& rHome)
{
return std::string();
}
// Linux specific
#else
#define kLibRFileName "libR.so"
#define kLibraryPathEnvVariable "LD_LIBRARY_PATH"
// extra paths from R (for rjava) on linux
std::string extraLibraryPaths(const FilePath& ldPathsScript,
const std::string& rHome)
{
// verify that script exists
if (!ldPathsScript.exists())
{
LOG_WARNING_MESSAGE("r-ldpaths script not found at " +
ldPathsScript.absolutePath());
return std::string();
}
// run script to capture paths
std::string libraryPaths;
std::string command = ldPathsScript.absolutePath() + " " + rHome;
Error error = system::captureCommand(command, &libraryPaths);
if (error)
LOG_ERROR(error);
boost::algorithm::trim(libraryPaths);
return libraryPaths;
}
#endif
FilePath systemDefaultRScript()
{
// ask system which R to use
std::string whichOutput;
Error error = core::system::captureCommand("which R", &whichOutput);
if (error)
{
LOG_ERROR(error);
return FilePath();
}
boost::algorithm::trim(whichOutput);
// check for nothing returned
if (whichOutput.empty())
return FilePath();
// verify that the alias points to a real version of R
FilePath rBinaryPath;
error = core::system::realPath(whichOutput, &rBinaryPath);
if (error)
{
LOG_ERROR(error);
return FilePath();
}
// check for real path doesn't exist
if (!rBinaryPath.exists())
return FilePath();
// got a valid R binary
return rBinaryPath;
}
bool validateREnvironment(const EnvironmentVars& vars, std::string* pErrMsg)
{
// first extract paths
FilePath rHomePath, rSharePath, rIncludePath, rDocPath, rLibPath, rLibRPath;
for (EnvironmentVars::const_iterator it = vars.begin();
it != vars.end();
++it)
{
if (it->first == "R_HOME")
rHomePath = FilePath(it->second);
else if (it->first == "R_SHARE_DIR")
rSharePath = FilePath(it->second);
else if (it->first == "R_INCLUDE_DIR")
rIncludePath = FilePath(it->second);
else if (it->first == "R_DOC_DIR")
rDocPath = FilePath(it->second);
}
// resolve derivitive paths
rLibPath = rHomePath.complete("lib");
rLibRPath = rLibPath.complete(kLibRFileName);
// validate required paths (if these don't exist then rsession won't
// be able start up)
if (!rHomePath.exists())
{
*pErrMsg = "R Home path (" + rHomePath.absolutePath() + ") not found";
return false;
}
else if (!rLibPath.exists())
{
*pErrMsg = "R lib path (" + rLibPath.absolutePath() + ") not found";
return false;
}
else if (!rLibRPath.exists())
{
*pErrMsg = "R shared library (" + rLibRPath.absolutePath() + ") "
"not found. If this is a custom build of R, was it "
"built with the --enable-R-shlib option?";
return false;
}
// log warnings for other missing paths (rsession can still start but
// won't be able to find these paths)
if (!rSharePath.exists())
{
LOG_WARNING_MESSAGE("R share path (" + rSharePath.absolutePath() +
") not found");
}
// merely log warnings for other missing paths
if (!rIncludePath.exists())
{
LOG_WARNING_MESSAGE("R include path (" + rIncludePath.absolutePath() +
") not found");
}
// merely log warnings for other missing paths
if (!rDocPath.exists())
{
LOG_WARNING_MESSAGE("R doc path (" + rDocPath.absolutePath() +
") not found");
}
return true;
}
} // anonymous namespace
bool detectREnvironment(const FilePath& ldPathsScript,
EnvironmentVars* pVars,
std::string* pErrMsg)
{
return detectREnvironment(FilePath(), ldPathsScript, pVars, pErrMsg);
}
bool detectREnvironment(const FilePath& whichRScript,
const FilePath& ldPathsScript,
EnvironmentVars* pVars,
std::string* pErrMsg)
{
// determine R script path. use either system default or user override
FilePath rScriptPath = whichRScript;
if (rScriptPath.empty())
rScriptPath = systemDefaultRScript();
// bail if not found
if (!rScriptPath.exists())
{
LOG_ERROR(pathNotFoundError(rScriptPath.absolutePath(), ERROR_LOCATION));
*pErrMsg = "R binary (" + rScriptPath.absolutePath() + ") not found";
return false;
}
// run R script to detect R home
std::string rHomeOutput;
std::string command = rScriptPath.absolutePath() + " RHOME";
Error error = core::system::captureCommand(command, &rHomeOutput);
if (error)
{
LOG_ERROR(error);
*pErrMsg = "Error running R (" + rScriptPath.absolutePath() + "): " +
error.summary();
return false;
}
boost::algorithm::trim(rHomeOutput);
// error if we got no output
if (rHomeOutput.empty())
{
*pErrMsg = "Unable to determine R home directory";
LOG_ERROR(systemError(boost::system::errc::not_supported,
*pErrMsg,
ERROR_LOCATION));
return false;
}
// set r home path
FilePath rHomePath(rHomeOutput);
pVars->push_back(std::make_pair("R_HOME", rHomePath.absolutePath()));
// scan R script for other locations and append them to our vars
config_utils::Variables locationVars;
locationVars.push_back(std::make_pair("R_SHARE_DIR", ""));
locationVars.push_back(std::make_pair("R_INCLUDE_DIR", ""));
locationVars.push_back(std::make_pair("R_DOC_DIR", ""));
error = config_utils::extractVariables(rScriptPath, &locationVars);
if (error)
{
LOG_ERROR(error);
*pErrMsg = "Error reading R script (" + rScriptPath.absolutePath() +
"), " + error.summary();
return false;
}
pVars->insert(pVars->end(), locationVars.begin(), locationVars.end());
// determine library path (existing + r lib dir + r extra lib dirs)
std::string libraryPath = core::system::getenv(kLibraryPathEnvVariable);
if (!libraryPath.empty())
libraryPath.append(":");
libraryPath.append(rHomePath.complete("lib").absolutePath());
std::string extraPaths = extraLibraryPaths(ldPathsScript,
rHomePath.absolutePath());
if (!extraPaths.empty())
libraryPath.append(":" + extraPaths);
pVars->push_back(std::make_pair(kLibraryPathEnvVariable, libraryPath));
return validateREnvironment(*pVars, pErrMsg);
}
void setREnvironmentVars(const EnvironmentVars& vars)
{
for (EnvironmentVars::const_iterator it = vars.begin();
it != vars.end();
++it)
{
core::system::setenv(it->first, it->second);
}
}
} // namespace r_util
} // namespace core
<commit_msg>make detection of valid R_DOC_DIR requried for startup<commit_after>/*
* REnvironmentPosix.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/r_util/REnvironment.hpp>
#include <algorithm>
#include <boost/algorithm/string/trim.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/ConfigUtils.hpp>
#include <core/system/System.hpp>
namespace core {
namespace r_util {
namespace {
// MacOS X Specific
#ifdef __APPLE__
#define kLibRFileName "libR.dylib"
#define kLibraryPathEnvVariable "DYLD_LIBRARY_PATH"
// no extra paths on the mac
std::string extraLibraryPaths(const FilePath& ldPathsScript,
const std::string& rHome)
{
return std::string();
}
// Linux specific
#else
#define kLibRFileName "libR.so"
#define kLibraryPathEnvVariable "LD_LIBRARY_PATH"
// extra paths from R (for rjava) on linux
std::string extraLibraryPaths(const FilePath& ldPathsScript,
const std::string& rHome)
{
// verify that script exists
if (!ldPathsScript.exists())
{
LOG_WARNING_MESSAGE("r-ldpaths script not found at " +
ldPathsScript.absolutePath());
return std::string();
}
// run script to capture paths
std::string libraryPaths;
std::string command = ldPathsScript.absolutePath() + " " + rHome;
Error error = system::captureCommand(command, &libraryPaths);
if (error)
LOG_ERROR(error);
boost::algorithm::trim(libraryPaths);
return libraryPaths;
}
#endif
FilePath systemDefaultRScript()
{
// ask system which R to use
std::string whichOutput;
Error error = core::system::captureCommand("which R", &whichOutput);
if (error)
{
LOG_ERROR(error);
return FilePath();
}
boost::algorithm::trim(whichOutput);
// check for nothing returned
if (whichOutput.empty())
return FilePath();
// verify that the alias points to a real version of R
FilePath rBinaryPath;
error = core::system::realPath(whichOutput, &rBinaryPath);
if (error)
{
LOG_ERROR(error);
return FilePath();
}
// check for real path doesn't exist
if (!rBinaryPath.exists())
return FilePath();
// got a valid R binary
return rBinaryPath;
}
bool validateREnvironment(const EnvironmentVars& vars, std::string* pErrMsg)
{
// first extract paths
FilePath rHomePath, rSharePath, rIncludePath, rDocPath, rLibPath, rLibRPath;
for (EnvironmentVars::const_iterator it = vars.begin();
it != vars.end();
++it)
{
if (it->first == "R_HOME")
rHomePath = FilePath(it->second);
else if (it->first == "R_SHARE_DIR")
rSharePath = FilePath(it->second);
else if (it->first == "R_INCLUDE_DIR")
rIncludePath = FilePath(it->second);
else if (it->first == "R_DOC_DIR")
rDocPath = FilePath(it->second);
}
// resolve derivitive paths
rLibPath = rHomePath.complete("lib");
rLibRPath = rLibPath.complete(kLibRFileName);
// validate required paths (if these don't exist then rsession won't
// be able start up)
if (!rHomePath.exists())
{
*pErrMsg = "R Home path (" + rHomePath.absolutePath() + ") not found";
return false;
}
else if (!rLibPath.exists())
{
*pErrMsg = "R lib path (" + rLibPath.absolutePath() + ") not found";
return false;
}
else if (!rLibRPath.exists())
{
*pErrMsg = "R shared library (" + rLibRPath.absolutePath() + ") "
"not found. If this is a custom build of R, was it "
"built with the --enable-R-shlib option?";
return false;
}
else if (!rDocPath.exists())
{
*pErrMsg = "R doc dir (" + rDocPath.absolutePath() + ") not found.";
return false;
}
// log warnings for other missing paths (rsession can still start but
// won't be able to find these env variables)
if (!rSharePath.exists())
{
LOG_WARNING_MESSAGE("R share path (" + rSharePath.absolutePath() +
") not found");
}
if (!rIncludePath.exists())
{
LOG_WARNING_MESSAGE("R include path (" + rIncludePath.absolutePath() +
") not found");
}
return true;
}
} // anonymous namespace
bool detectREnvironment(const FilePath& ldPathsScript,
EnvironmentVars* pVars,
std::string* pErrMsg)
{
return detectREnvironment(FilePath(), ldPathsScript, pVars, pErrMsg);
}
bool detectREnvironment(const FilePath& whichRScript,
const FilePath& ldPathsScript,
EnvironmentVars* pVars,
std::string* pErrMsg)
{
// determine R script path. use either system default or user override
FilePath rScriptPath = whichRScript;
if (rScriptPath.empty())
rScriptPath = systemDefaultRScript();
// bail if not found
if (!rScriptPath.exists())
{
LOG_ERROR(pathNotFoundError(rScriptPath.absolutePath(), ERROR_LOCATION));
*pErrMsg = "R binary (" + rScriptPath.absolutePath() + ") not found";
return false;
}
// run R script to detect R home
std::string rHomeOutput;
std::string command = rScriptPath.absolutePath() + " RHOME";
Error error = core::system::captureCommand(command, &rHomeOutput);
if (error)
{
LOG_ERROR(error);
*pErrMsg = "Error running R (" + rScriptPath.absolutePath() + "): " +
error.summary();
return false;
}
boost::algorithm::trim(rHomeOutput);
// error if we got no output
if (rHomeOutput.empty())
{
*pErrMsg = "Unable to determine R home directory";
LOG_ERROR(systemError(boost::system::errc::not_supported,
*pErrMsg,
ERROR_LOCATION));
return false;
}
// error if `R RHOME` yields file that doesn't exist
FilePath rHomePath(rHomeOutput);
if (!rHomePath.exists())
{
*pErrMsg = "R home path (" + rHomeOutput + ") not found";
LOG_ERROR(pathNotFoundError(*pErrMsg, ERROR_LOCATION));
return false;
}
// set r home path
pVars->push_back(std::make_pair("R_HOME", rHomePath.absolutePath()));
// scan R script for other locations and append them to our vars
config_utils::Variables locationVars;
locationVars.push_back(std::make_pair("R_SHARE_DIR", ""));
locationVars.push_back(std::make_pair("R_INCLUDE_DIR", ""));
locationVars.push_back(std::make_pair("R_DOC_DIR", ""));
error = config_utils::extractVariables(rScriptPath, &locationVars);
if (error)
{
LOG_ERROR(error);
*pErrMsg = "Error reading R script (" + rScriptPath.absolutePath() +
"), " + error.summary();
return false;
}
pVars->insert(pVars->end(), locationVars.begin(), locationVars.end());
// determine library path (existing + r lib dir + r extra lib dirs)
std::string libraryPath = core::system::getenv(kLibraryPathEnvVariable);
if (!libraryPath.empty())
libraryPath.append(":");
libraryPath.append(rHomePath.complete("lib").absolutePath());
std::string extraPaths = extraLibraryPaths(ldPathsScript,
rHomePath.absolutePath());
if (!extraPaths.empty())
libraryPath.append(":" + extraPaths);
pVars->push_back(std::make_pair(kLibraryPathEnvVariable, libraryPath));
return validateREnvironment(*pVars, pErrMsg);
}
void setREnvironmentVars(const EnvironmentVars& vars)
{
for (EnvironmentVars::const_iterator it = vars.begin();
it != vars.end();
++it)
{
core::system::setenv(it->first, it->second);
}
}
} // namespace r_util
} // namespace core
<|endoftext|> |
<commit_before>#include <vector>
#include <cstdint>
#include <functional>
#include <iostream>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/buffer.h>
#include <openssl/pem.h>
#include "jwt.hpp"
using namespace std;
using namespace nlohmann;
namespace jwt {
namespace detail {
class OnLeave : public vector<function<void()>> {
public:
~OnLeave() {
for (auto& fn : *this) {
fn();
}
}
};
void replaceAll(string& str, const string& from, const string& to) {
size_t pos = 0;
while ((pos = str.find(from, pos)) != string::npos) {
str.replace(pos, from.length(), to);
pos += to.length();
}
}
string b64encode(const uint8_t* data, size_t len) {
auto b64 = BIO_new(BIO_f_base64());
auto bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO_write(bio, data, len);
BIO_flush(bio);
BUF_MEM* buf = nullptr;
BIO_get_mem_ptr(bio, &buf);
string s{ buf->data };
BIO_free_all(bio);
// Convert it to base64url.
s = s.substr(0, s.find_last_not_of("=") + 1);
replaceAll(s, "+", "-");
replaceAll(s, "/", "_");
return s;
}
vector<uint8_t> b64decode(string str) {
// Convert it from base64url back to normal base64.
size_t padding{ 0 };
replaceAll(str, "-", "+");
replaceAll(str, "_", "/");
switch (str.length() % 4) {
case 0:
break;
case 2:
str += "==";
padding = 2;
break;
case 3:
str += "=";
padding = 1;
break;
default:
return vector<uint8_t>{};
}
size_t len{ (str.length() * 3) / 4 - padding };
vector<uint8_t> buf(len);
auto bio = BIO_new_mem_buf((void*)str.c_str(), -1);
auto b64 = BIO_new(BIO_f_base64());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO_read(bio, buf.data(), str.length());
BIO_free_all(bio);
return buf;
}
}
#define SCOPE_EXIT(x) do { onLeave.push_back([&]() { x; }); } while(0)
string signHMAC(const string& str, const string& key, const string& alg) {
const EVP_MD* evp = nullptr;
if (alg == "HS256") {
evp = EVP_sha256();
}
else if (alg == "HS384") {
evp = EVP_sha384();
}
else if (alg == "HS512") {
evp = EVP_sha512();
}
else {
return string{};
}
vector<uint8_t> out(EVP_MAX_MD_SIZE);
unsigned int len = 0;
HMAC(evp, key.c_str(), key.length(), (const unsigned char*)str.c_str(), str.length(), out.data(), &len);
return detail::b64encode(out.data(), len);
}
string signPEM(const string& str, const string& key, const string& alg) {
detail::OnLeave onLeave;
const EVP_MD* evp = nullptr;
if (alg == "RS256") {
evp = EVP_sha256();
}
else if (alg == "RS384") {
evp = EVP_sha384();
}
else if (alg == "RS512") {
evp = EVP_sha512();
}
else if (alg == "ES256") {
evp = EVP_sha256();
}
else if (alg == "ES384") {
evp = EVP_sha384();
}
else if (alg == "ES512") {
evp = EVP_sha512();
}
else {
return string{};
}
auto bufkey = BIO_new_mem_buf((void*)key.c_str(), key.length());
SCOPE_EXIT(if (bufkey) BIO_free(bufkey));
if (!bufkey) {
return string{};
}
// Use OpenSSL's default passphrase callbacks if needed.
auto pkey = PEM_read_bio_PrivateKey(bufkey, nullptr, nullptr, nullptr);
SCOPE_EXIT(if (pkey) EVP_PKEY_free(pkey));
if (!pkey) {
return string{};
}
auto mdctx = EVP_MD_CTX_create();
SCOPE_EXIT(if (mdctx) EVP_MD_CTX_destroy(mdctx));
if (!mdctx) {
return string{};
}
// Initialize the digest sign operation.
if (EVP_DigestSignInit(mdctx, nullptr, evp, nullptr, pkey) != 1) {
return string{};
}
// Update the digest sign with the message.
if (EVP_DigestSignUpdate(mdctx, str.c_str(), str.length()) != 1) {
return string{};
}
// Determin the size of the finalized digest sign.
size_t siglen = 0;
if (EVP_DigestSignFinal(mdctx, nullptr, &siglen) != 1) {
return string{};
}
// Finalize it.
vector<uint8_t> sig(siglen);
if (EVP_DigestSignFinal(mdctx, sig.data(), &siglen) != 1) {
return string{};
}
// For RSA, we are done.
return detail::b64encode(sig.data(), siglen);
}
bool verifyPEM(const string& str, const string& b64sig, const string& key, const string& alg) {
detail::OnLeave onLeave;
const EVP_MD* evp = nullptr;
if (alg == "RS256") {
evp = EVP_sha256();
}
else if (alg == "RS384") {
evp = EVP_sha384();
}
else if (alg == "RS512") {
evp = EVP_sha512();
}
else if (alg == "ES256") {
evp = EVP_sha256();
}
else if (alg == "ES384") {
evp = EVP_sha384();
}
else if (alg == "ES512") {
evp = EVP_sha512();
}
else {
return false;
}
auto sig = detail::b64decode(b64sig);
auto siglen = sig.size();
if (sig.empty()) {
return false;
}
auto bufkey = BIO_new_mem_buf((void*)key.c_str(), key.length());
SCOPE_EXIT(if (bufkey) BIO_free(bufkey));
if (!bufkey) {
return false;
}
// Use OpenSSL's default passphrase callbacks if needed.
auto pkey = PEM_read_bio_PUBKEY(bufkey, nullptr, nullptr, nullptr);
SCOPE_EXIT(if (pkey) EVP_PKEY_free(pkey));
if (!pkey) {
return false;
}
auto mdctx = EVP_MD_CTX_create();
SCOPE_EXIT(if (mdctx) EVP_MD_CTX_destroy(mdctx));
if (EVP_DigestVerifyInit(mdctx, nullptr, evp, nullptr, pkey) != 1) {
return false;
}
if (EVP_DigestVerifyUpdate(mdctx, str.c_str(), str.length()) != 1) {
return false;
}
if (EVP_DigestVerifyFinal(mdctx, sig.data(), siglen) != 1) {
return false;
}
return true;
}
string encode(const json& payload, const string& key, const string& alg) {
// Create a JWT header defaulting to the HS256 alg if none is supplied.
json header{
{"typ", "JWT"},
{"alg", alg.empty() ? "HS256" : alg }
};
auto headerStr = header.dump();
auto encodedHeader = detail::b64encode((const uint8_t*)headerStr.c_str(), headerStr.length());
// Encode the payload.
auto payloadStr = payload.dump();
auto encodedPayload = detail::b64encode((const uint8_t*)payloadStr.c_str(), payloadStr.length());
// Sign it and return the final JWT.
auto encodedToken = encodedHeader + "." + encodedPayload;
const string& theAlg = header["alg"];
string signature{};
if (theAlg == "none") {
// Nothing to sign.
}
else if (theAlg.find("HS") != string::npos) {
signature = signHMAC(encodedToken, key, theAlg);
}
else {
signature = signPEM(encodedToken, key, theAlg);
}
if (theAlg != "none" && signature.empty()) {
return string{};
}
return encodedToken + "." + signature;
}
json decode(const string& jwt, const string& key, const set<string>& alg) {
if (jwt.empty()) {
return json{};
}
// Make sure the jwt we recieve looks like a jwt.
auto firstPeriod = jwt.find_first_of('.');
auto secondPeriod = jwt.find_first_of('.', firstPeriod + 1);
if (firstPeriod == string::npos || secondPeriod == string::npos) {
return json{};
}
// Decode the header so we can get the alg used by the jwt.
auto decodedHeader = detail::b64decode(jwt.substr(0, firstPeriod));
string decodedHeaderStr{ decodedHeader.begin(), decodedHeader.end() };
auto header = json::parse(decodedHeaderStr.c_str());
const string& theAlg = header["alg"];
// Make sure no key is supplied if the alg is none.
if (theAlg == "none" && !key.empty()) {
return json{};
}
// Make sure the alg supplied is one we expect.
else if (alg.count(theAlg) == 0 && !alg.empty()) {
return json{};
}
auto encodedToken = jwt.substr(0, secondPeriod);
auto signature = jwt.substr(secondPeriod + 1);
// Verify the signature.
if (theAlg == "none") {
// Nothing to do, no verification needed.
}
else if (theAlg.find("HS") != string::npos) {
auto calculatedSignature = signHMAC(encodedToken, key, theAlg);
if (signature != calculatedSignature || calculatedSignature.empty()) {
return json{};
}
}
else {
if (!verifyPEM(encodedToken, signature, key, theAlg)) {
return json{};
}
}
// Decode the payload since the jwt has been verified.
auto decodedPayload = detail::b64decode(jwt.substr(firstPeriod + 1, secondPeriod - firstPeriod - 1));
string decodedPayloadStr{ decodedPayload.begin(), decodedPayload.end() };
auto payload = json::parse(decodedPayloadStr.c_str());
return payload;
}
}<commit_msg>Explicitly default construct detail::OnLeave<commit_after>#include <vector>
#include <cstdint>
#include <functional>
#include <iostream>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/buffer.h>
#include <openssl/pem.h>
#include "jwt.hpp"
using namespace std;
using namespace nlohmann;
namespace jwt {
namespace detail {
class OnLeave : public vector<function<void()>> {
public:
~OnLeave() {
for (auto& fn : *this) {
fn();
}
}
};
void replaceAll(string& str, const string& from, const string& to) {
size_t pos = 0;
while ((pos = str.find(from, pos)) != string::npos) {
str.replace(pos, from.length(), to);
pos += to.length();
}
}
string b64encode(const uint8_t* data, size_t len) {
auto b64 = BIO_new(BIO_f_base64());
auto bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO_write(bio, data, len);
BIO_flush(bio);
BUF_MEM* buf = nullptr;
BIO_get_mem_ptr(bio, &buf);
string s{ buf->data };
BIO_free_all(bio);
// Convert it to base64url.
s = s.substr(0, s.find_last_not_of("=") + 1);
replaceAll(s, "+", "-");
replaceAll(s, "/", "_");
return s;
}
vector<uint8_t> b64decode(string str) {
// Convert it from base64url back to normal base64.
size_t padding{ 0 };
replaceAll(str, "-", "+");
replaceAll(str, "_", "/");
switch (str.length() % 4) {
case 0:
break;
case 2:
str += "==";
padding = 2;
break;
case 3:
str += "=";
padding = 1;
break;
default:
return vector<uint8_t>{};
}
size_t len{ (str.length() * 3) / 4 - padding };
vector<uint8_t> buf(len);
auto bio = BIO_new_mem_buf((void*)str.c_str(), -1);
auto b64 = BIO_new(BIO_f_base64());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO_read(bio, buf.data(), str.length());
BIO_free_all(bio);
return buf;
}
}
#define SCOPE_EXIT(x) do { onLeave.push_back([&]() { x; }); } while(0)
string signHMAC(const string& str, const string& key, const string& alg) {
const EVP_MD* evp = nullptr;
if (alg == "HS256") {
evp = EVP_sha256();
}
else if (alg == "HS384") {
evp = EVP_sha384();
}
else if (alg == "HS512") {
evp = EVP_sha512();
}
else {
return string{};
}
vector<uint8_t> out(EVP_MAX_MD_SIZE);
unsigned int len = 0;
HMAC(evp, key.c_str(), key.length(), (const unsigned char*)str.c_str(), str.length(), out.data(), &len);
return detail::b64encode(out.data(), len);
}
string signPEM(const string& str, const string& key, const string& alg) {
detail::OnLeave onLeave{};
const EVP_MD* evp = nullptr;
if (alg == "RS256") {
evp = EVP_sha256();
}
else if (alg == "RS384") {
evp = EVP_sha384();
}
else if (alg == "RS512") {
evp = EVP_sha512();
}
else if (alg == "ES256") {
evp = EVP_sha256();
}
else if (alg == "ES384") {
evp = EVP_sha384();
}
else if (alg == "ES512") {
evp = EVP_sha512();
}
else {
return string{};
}
auto bufkey = BIO_new_mem_buf((void*)key.c_str(), key.length());
SCOPE_EXIT(if (bufkey) BIO_free(bufkey));
if (!bufkey) {
return string{};
}
// Use OpenSSL's default passphrase callbacks if needed.
auto pkey = PEM_read_bio_PrivateKey(bufkey, nullptr, nullptr, nullptr);
SCOPE_EXIT(if (pkey) EVP_PKEY_free(pkey));
if (!pkey) {
return string{};
}
auto mdctx = EVP_MD_CTX_create();
SCOPE_EXIT(if (mdctx) EVP_MD_CTX_destroy(mdctx));
if (!mdctx) {
return string{};
}
// Initialize the digest sign operation.
if (EVP_DigestSignInit(mdctx, nullptr, evp, nullptr, pkey) != 1) {
return string{};
}
// Update the digest sign with the message.
if (EVP_DigestSignUpdate(mdctx, str.c_str(), str.length()) != 1) {
return string{};
}
// Determin the size of the finalized digest sign.
size_t siglen = 0;
if (EVP_DigestSignFinal(mdctx, nullptr, &siglen) != 1) {
return string{};
}
// Finalize it.
vector<uint8_t> sig(siglen);
if (EVP_DigestSignFinal(mdctx, sig.data(), &siglen) != 1) {
return string{};
}
// For RSA, we are done.
return detail::b64encode(sig.data(), siglen);
}
bool verifyPEM(const string& str, const string& b64sig, const string& key, const string& alg) {
detail::OnLeave onLeave{};
const EVP_MD* evp = nullptr;
if (alg == "RS256") {
evp = EVP_sha256();
}
else if (alg == "RS384") {
evp = EVP_sha384();
}
else if (alg == "RS512") {
evp = EVP_sha512();
}
else if (alg == "ES256") {
evp = EVP_sha256();
}
else if (alg == "ES384") {
evp = EVP_sha384();
}
else if (alg == "ES512") {
evp = EVP_sha512();
}
else {
return false;
}
auto sig = detail::b64decode(b64sig);
auto siglen = sig.size();
if (sig.empty()) {
return false;
}
auto bufkey = BIO_new_mem_buf((void*)key.c_str(), key.length());
SCOPE_EXIT(if (bufkey) BIO_free(bufkey));
if (!bufkey) {
return false;
}
// Use OpenSSL's default passphrase callbacks if needed.
auto pkey = PEM_read_bio_PUBKEY(bufkey, nullptr, nullptr, nullptr);
SCOPE_EXIT(if (pkey) EVP_PKEY_free(pkey));
if (!pkey) {
return false;
}
auto mdctx = EVP_MD_CTX_create();
SCOPE_EXIT(if (mdctx) EVP_MD_CTX_destroy(mdctx));
if (EVP_DigestVerifyInit(mdctx, nullptr, evp, nullptr, pkey) != 1) {
return false;
}
if (EVP_DigestVerifyUpdate(mdctx, str.c_str(), str.length()) != 1) {
return false;
}
if (EVP_DigestVerifyFinal(mdctx, sig.data(), siglen) != 1) {
return false;
}
return true;
}
string encode(const json& payload, const string& key, const string& alg) {
// Create a JWT header defaulting to the HS256 alg if none is supplied.
json header{
{"typ", "JWT"},
{"alg", alg.empty() ? "HS256" : alg }
};
auto headerStr = header.dump();
auto encodedHeader = detail::b64encode((const uint8_t*)headerStr.c_str(), headerStr.length());
// Encode the payload.
auto payloadStr = payload.dump();
auto encodedPayload = detail::b64encode((const uint8_t*)payloadStr.c_str(), payloadStr.length());
// Sign it and return the final JWT.
auto encodedToken = encodedHeader + "." + encodedPayload;
const string& theAlg = header["alg"];
string signature{};
if (theAlg == "none") {
// Nothing to sign.
}
else if (theAlg.find("HS") != string::npos) {
signature = signHMAC(encodedToken, key, theAlg);
}
else {
signature = signPEM(encodedToken, key, theAlg);
}
if (theAlg != "none" && signature.empty()) {
return string{};
}
return encodedToken + "." + signature;
}
json decode(const string& jwt, const string& key, const set<string>& alg) {
if (jwt.empty()) {
return json{};
}
// Make sure the jwt we recieve looks like a jwt.
auto firstPeriod = jwt.find_first_of('.');
auto secondPeriod = jwt.find_first_of('.', firstPeriod + 1);
if (firstPeriod == string::npos || secondPeriod == string::npos) {
return json{};
}
// Decode the header so we can get the alg used by the jwt.
auto decodedHeader = detail::b64decode(jwt.substr(0, firstPeriod));
string decodedHeaderStr{ decodedHeader.begin(), decodedHeader.end() };
auto header = json::parse(decodedHeaderStr.c_str());
const string& theAlg = header["alg"];
// Make sure no key is supplied if the alg is none.
if (theAlg == "none" && !key.empty()) {
return json{};
}
// Make sure the alg supplied is one we expect.
else if (alg.count(theAlg) == 0 && !alg.empty()) {
return json{};
}
auto encodedToken = jwt.substr(0, secondPeriod);
auto signature = jwt.substr(secondPeriod + 1);
// Verify the signature.
if (theAlg == "none") {
// Nothing to do, no verification needed.
}
else if (theAlg.find("HS") != string::npos) {
auto calculatedSignature = signHMAC(encodedToken, key, theAlg);
if (signature != calculatedSignature || calculatedSignature.empty()) {
return json{};
}
}
else {
if (!verifyPEM(encodedToken, signature, key, theAlg)) {
return json{};
}
}
// Decode the payload since the jwt has been verified.
auto decodedPayload = detail::b64decode(jwt.substr(firstPeriod + 1, secondPeriod - firstPeriod - 1));
string decodedPayloadStr{ decodedPayload.begin(), decodedPayload.end() };
auto payload = json::parse(decodedPayloadStr.c_str());
return payload;
}
}<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2009 by Jeroen Broekhuizen *
* jengine.sse@live.nl *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This 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 Library 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 "guilistboxkeylistener.h"
#include "gui/input/keyevent.h"
#include "gui/guilistbox.h"
#include "gui/guieventhandler.h"
#include "gui/guieventhandlers.h"
#include "scriptmanager.h"
GuiListBoxKeyListener::GuiListBoxKeyListener(GuiListBox& listbox):
KeyListener(),
mListbox(listbox)
{
}
// - Notifications
void GuiListBoxKeyListener::onKeyReleased(const KeyEvent& event)
{
GuiEventHandler* phandler = mListbox.getEventHandlers().findByEventType(GuiListKeyPressEvent);
if ( phandler != NULL )
{
ScriptManager& mgr = ScriptManager::getInstance();
Script& script = mgr.getTemporaryScript();
script.setSelf(this, "GuiListBox");
script.prepareCall(phandler->getFunctionName().c_str());
script.addParam(event.getKey());
script.run(1);
}
}
<commit_msg>* fixed bug 3053316 - set self to correct pointer<commit_after>/***************************************************************************
* Copyright (C) 2009 by Jeroen Broekhuizen *
* jengine.sse@live.nl *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This 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 Library 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 "guilistboxkeylistener.h"
#include "gui/input/keyevent.h"
#include "gui/guilistbox.h"
#include "gui/guieventhandler.h"
#include "gui/guieventhandlers.h"
#include "scriptmanager.h"
GuiListBoxKeyListener::GuiListBoxKeyListener(GuiListBox& listbox):
KeyListener(),
mListbox(listbox)
{
}
// - Notifications
void GuiListBoxKeyListener::onKeyReleased(const KeyEvent& event)
{
GuiEventHandler* phandler = mListbox.getEventHandlers().findByEventType(GuiListKeyPressEvent);
if ( phandler != NULL )
{
ScriptManager& mgr = ScriptManager::getInstance();
Script& script = mgr.getTemporaryScript();
script.setSelf(this, &mListbox);
script.prepareCall(phandler->getFunctionName().c_str());
script.addParam(event.getKey());
script.run(1);
}
}
<|endoftext|> |
<commit_before>/**
* A class which describes the properties and actions of a device session.
*
* @date July 7, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <cassert>
#include <cstring>
#include <iostream>
// Application dependencies.
#include <ias/channel/socket_channel.h>
#include <ias/server/session/device_session.h>
#include <ias/logger/logger.h>
// END Includes. /////////////////////////////////////////////////////
inline void DeviceSession::initialize( void ) {
mDispatcher = nullptr;
mFlagRunning = false;
}
void DeviceSession::setDispatcher( Dispatcher<const std::string &> * d ) {
// Checking the precondition.
assert( d != nullptr );
mDispatcher = d;
}
void DeviceSession::authorize( void ) {
std::uint8_t type;
std::uint8_t deviceIdentifier;
logi("Authorizing device.");
if( !readBytes(reinterpret_cast<char *>(&type),1) ) return;
if( type == 0x00 && readBytes(reinterpret_cast<char *>(&deviceIdentifier),1) ) {
char identifier[deviceIdentifier + 1];
if( !readBytes(identifier,deviceIdentifier) ) return;
identifier[deviceIdentifier] = 0;
if( strlen(identifier) > 0 && containsDevice(identifier) &&
!mDispatcher->containsChannel(identifier) ) {
mFlagRunning = true;
mDevice = identifier;
mDispatcher->addChannel(identifier,new SocketChannel(getSocket()));
logi(mDevice + " has been authorized.");
} else {
stop();
}
}
if( !mFlagRunning )
loge("Device authorization failed.");
}
void DeviceSession::setDevices( const std::vector<std::string> * devices ) {
// Checking the precondition.
assert( devices != nullptr );
mDevices = devices;
}
bool DeviceSession::containsDevice( const std::string & identifier ) const {
bool contains;
contains = false;
for( auto it = mDevices->begin() ; it != mDevices->end() ; ++it ) {
if( (*it) == identifier ) {
contains = true;
break;
}
}
return ( contains );
}
void DeviceSession::updateDeviceState( void ) {
std::uint8_t length[2];
memset(&length,0,2);
if( !readBytes(reinterpret_cast<char *>(length),2) ) return;
char buffer[length[0] + length[1]];
if( !readBytes(buffer,length[0] + length[1]) ) return;
char stateIdentifier[length[0] + 1];
char value[length[1] + 1];
memcpy(stateIdentifier,buffer,length[0]);
memcpy(value,buffer + length[0],length[1]);
stateIdentifier[length[0]] = 0;
value[length[1]] = 0;
sendDeviceState(stateIdentifier,value);
}
void DeviceSession::sendDeviceState( const std::string & stateIdentifier,
const std::string & value ) {
std::uint8_t header[4];
std::string message;
std::size_t n;
Writer * writer;
bool success;
// Checking the precondition.
assert( !stateIdentifier.empty() && !value.empty() );
header[0] = 0x01;
header[1] = static_cast<std::uint8_t>(mDevice.length());
header[2] = static_cast<std::uint8_t>(stateIdentifier.length());
header[3] = static_cast<std::uint8_t>(value.length());
message = mDevice + stateIdentifier + value;
writer = mServerSocket->getWriter();
success = true;
writer->lock();
n = writer->writeBytes(reinterpret_cast<char *>(header),4);
success &= ( n > 0 );
n = writer->writeBytes(reinterpret_cast<const char *>(message.c_str()),
message.length());
success &= ( n > 0 );
writer->unlock();
if( !success ) {
stop();
}
}
void DeviceSession::setServerSocket( Socket * serverSocket ) {
// Checking the precondition.
assert( serverSocket != nullptr );
mServerSocket = serverSocket;
}
DeviceSession::DeviceSession( Socket * socket,
Socket * serverSocket,
Dispatcher<const std::string &> * d,
const std::vector<std::string> * devices ) :
Session(socket) {
initialize();
setDispatcher(d);
setServerSocket(serverSocket);
setDevices(devices);
}
DeviceSession::~DeviceSession( void ) {
stop();
}
void DeviceSession::run( void ) {
std::uint8_t type;
std::size_t nBytes;
Reader * reader;
authorize();
if( getSocket()->isConnected() ) {
reader = getSocket()->getReader();
while( mFlagRunning && mServerSocket->isConnected() &&
getSocket()->isConnected() ) {
nBytes = reader->readByte(reinterpret_cast<char *>(&type));
if( nBytes == 0 ) {
stop();
} else {
switch(type) {
case 0x01:
updateDeviceState();
break;
default:
stop();
break;
}
}
}
}
std::cout << "Server socket status: " << std::to_string(mServerSocket->isConnected()) << std::endl << std::flush;
std::cout << "Socket status: " << std::to_string(getSocket()->isConnected()) << std::endl << std::flush;
if( !mDevice.empty() )
mDispatcher->removeChannel(mDevice);
getSocket()->closeConnection();
}
void DeviceSession::stop( void ) {
const static std::uint8_t close = 0xff;
Socket * socket;
Writer * writer;
if( mFlagRunning ) {
logi("Closing device session.");
mFlagRunning = false;
socket = getSocket();
if( socket->isConnected() ) {
writer = getSocket()->getWriter();
writer->lock();
writer->writeBytes(reinterpret_cast<const char *>(&close),1);
writer->unlock();
socket->closeConnection();
}
}
}
<commit_msg>Remove device session debugging information.<commit_after>/**
* A class which describes the properties and actions of a device session.
*
* @date July 7, 2014
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <cassert>
#include <cstring>
#include <iostream>
// Application dependencies.
#include <ias/channel/socket_channel.h>
#include <ias/server/session/device_session.h>
#include <ias/logger/logger.h>
// END Includes. /////////////////////////////////////////////////////
inline void DeviceSession::initialize( void ) {
mDispatcher = nullptr;
mFlagRunning = false;
}
void DeviceSession::setDispatcher( Dispatcher<const std::string &> * d ) {
// Checking the precondition.
assert( d != nullptr );
mDispatcher = d;
}
void DeviceSession::authorize( void ) {
std::uint8_t type;
std::uint8_t deviceIdentifier;
logi("Authorizing device.");
if( !readBytes(reinterpret_cast<char *>(&type),1) ) return;
if( type == 0x00 && readBytes(reinterpret_cast<char *>(&deviceIdentifier),1) ) {
char identifier[deviceIdentifier + 1];
if( !readBytes(identifier,deviceIdentifier) ) return;
identifier[deviceIdentifier] = 0;
if( strlen(identifier) > 0 && containsDevice(identifier) &&
!mDispatcher->containsChannel(identifier) ) {
mFlagRunning = true;
mDevice = identifier;
mDispatcher->addChannel(identifier,new SocketChannel(getSocket()));
logi(mDevice + " has been authorized.");
} else {
stop();
}
}
if( !mFlagRunning )
loge("Device authorization failed.");
}
void DeviceSession::setDevices( const std::vector<std::string> * devices ) {
// Checking the precondition.
assert( devices != nullptr );
mDevices = devices;
}
bool DeviceSession::containsDevice( const std::string & identifier ) const {
bool contains;
contains = false;
for( auto it = mDevices->begin() ; it != mDevices->end() ; ++it ) {
if( (*it) == identifier ) {
contains = true;
break;
}
}
return ( contains );
}
void DeviceSession::updateDeviceState( void ) {
std::uint8_t length[2];
memset(&length,0,2);
if( !readBytes(reinterpret_cast<char *>(length),2) ) return;
char buffer[length[0] + length[1]];
if( !readBytes(buffer,length[0] + length[1]) ) return;
char stateIdentifier[length[0] + 1];
char value[length[1] + 1];
memcpy(stateIdentifier,buffer,length[0]);
memcpy(value,buffer + length[0],length[1]);
stateIdentifier[length[0]] = 0;
value[length[1]] = 0;
sendDeviceState(stateIdentifier,value);
}
void DeviceSession::sendDeviceState( const std::string & stateIdentifier,
const std::string & value ) {
std::uint8_t header[4];
std::string message;
std::size_t n;
Writer * writer;
bool success;
// Checking the precondition.
assert( !stateIdentifier.empty() && !value.empty() );
header[0] = 0x01;
header[1] = static_cast<std::uint8_t>(mDevice.length());
header[2] = static_cast<std::uint8_t>(stateIdentifier.length());
header[3] = static_cast<std::uint8_t>(value.length());
message = mDevice + stateIdentifier + value;
writer = mServerSocket->getWriter();
success = true;
writer->lock();
n = writer->writeBytes(reinterpret_cast<char *>(header),4);
success &= ( n > 0 );
n = writer->writeBytes(reinterpret_cast<const char *>(message.c_str()),
message.length());
success &= ( n > 0 );
writer->unlock();
if( !success ) {
stop();
}
}
void DeviceSession::setServerSocket( Socket * serverSocket ) {
// Checking the precondition.
assert( serverSocket != nullptr );
mServerSocket = serverSocket;
}
DeviceSession::DeviceSession( Socket * socket,
Socket * serverSocket,
Dispatcher<const std::string &> * d,
const std::vector<std::string> * devices ) :
Session(socket) {
initialize();
setDispatcher(d);
setServerSocket(serverSocket);
setDevices(devices);
}
DeviceSession::~DeviceSession( void ) {
stop();
}
void DeviceSession::run( void ) {
std::uint8_t type;
std::size_t nBytes;
Reader * reader;
authorize();
if( getSocket()->isConnected() ) {
reader = getSocket()->getReader();
while( mFlagRunning && mServerSocket->isConnected() &&
getSocket()->isConnected() ) {
nBytes = reader->readByte(reinterpret_cast<char *>(&type));
if( nBytes == 0 ) {
stop();
} else {
switch(type) {
case 0x01:
updateDeviceState();
break;
default:
stop();
break;
}
}
}
}
if( !mDevice.empty() )
mDispatcher->removeChannel(mDevice);
getSocket()->closeConnection();
}
void DeviceSession::stop( void ) {
const static std::uint8_t close = 0xff;
Socket * socket;
Writer * writer;
if( mFlagRunning ) {
logi("Closing device session.");
mFlagRunning = false;
socket = getSocket();
if( socket->isConnected() ) {
writer = getSocket()->getWriter();
writer->lock();
writer->writeBytes(reinterpret_cast<const char *>(&close),1);
writer->unlock();
socket->closeConnection();
}
}
}
<|endoftext|> |
<commit_before>#include <cmath>
#include "ingameelements/weapons/peacemaker.h"
#include "renderer.h"
#include "ingameelements/projectiles/peacemakerbullet.h"
#include "ingameelements/heroes/mccree.h"
#include "ingameelements/explosion.h"
#include "engine.h"
Peacemaker::Peacemaker(uint64_t id_, Gamestate *state, EntityPtr owner_) : Weapon(id_, state, owner_, constructparameters(state)),
fthanim("heroes/mccree/fanthehammerstart/", std::bind(&Peacemaker::firesecondary, this, state)), isfthing(false)
{
fthanim.active(false);
}
Peacemaker::~Peacemaker()
{
//dtor
}
void Peacemaker::render(Renderer *renderer, Gamestate *state)
{
std::string mainsprite;
double dir = aimdirection;
Mccree *c = state->get<Mccree>(state->get<Player>(owner)->character);
if (firinganim.active())
{
mainsprite = firinganim.getframe();
}
else if (reloadanim.active())
{
mainsprite = reloadanim.getframe();
dir = 3.1415*c->isflipped;
}
else if (fthanim.active())
{
mainsprite = fthanim.getframe();
}
else
{
mainsprite = c->getcharacterfolder()+"arm/1.png";
}
ALLEGRO_BITMAP *sprite = renderer->spriteloader.requestsprite(mainsprite);
int spriteoffset_x = renderer->spriteloader.get_spriteoffset_x(mainsprite);
int spriteoffset_y = renderer->spriteloader.get_spriteoffset_y(mainsprite);
al_set_target_bitmap(renderer->midground);
if (not c->rollanim.active())
{
if (c->isflipped)
{
al_draw_scaled_rotated_bitmap(sprite, -getattachpoint_x()-spriteoffset_x, getattachpoint_y()+spriteoffset_y, x - renderer->cam_x, y - renderer->cam_y, 1, -1, dir, 0);
}
else
{
al_draw_rotated_bitmap(sprite, getattachpoint_x()+spriteoffset_x, getattachpoint_y()+spriteoffset_y, x - renderer->cam_x, y - renderer->cam_y, dir, 0);
}
}
}
void Peacemaker::midstep(Gamestate *state, double frametime)
{
Weapon::midstep(state, frametime);
if (isfthing)
{
fthanim.active(true);
}
fthanim.update(state, frametime);
}
void Peacemaker::reload(Gamestate *state)
{
if (clip < getclipsize() and not firinganim.active() and not reloadanim.active() and not isfthing)
{
// We need to reload
reloadanim.reset();
reloadanim.active(true);
}
}
void Peacemaker::wantfireprimary(Gamestate *state)
{
if (state->engine->isserver and clip > 0 and not firinganim.active())
{
fireprimary(state);
state->sendbuffer->write<uint8_t>(PRIMARY_FIRED);
state->sendbuffer->write<uint8_t>(state->findplayerid(state->get<Character>(owner)->owner));
}
}
void Peacemaker::fireprimary(Gamestate *state)
{
EntityPtr newshot = state->make_entity<PeacemakerBullet>(state, owner);
PeacemakerBullet *shot = state->get<PeacemakerBullet>(newshot);
shot->x = x+std::cos(aimdirection)*10;
shot->y = y+std::sin(aimdirection)*10;
shot->hspeed = std::cos(aimdirection) * bulletspeed;
shot->vspeed = std::sin(aimdirection) * bulletspeed;
Explosion *e = state->get<Explosion>(state->make_entity<Explosion>(state, "heroes/mccree/projectiletrail/", aimdirection));
e->x = x+std::cos(aimdirection)*24;
e->y = y+std::sin(aimdirection)*24;
--clip;
firinganim.reset();
firinganim.active(true);
}
void Peacemaker::wantfiresecondary(Gamestate *state)
{
if (clip > 0)
{
if (not isfthing and state->engine->isserver)
{
firesecondary(state);
state->sendbuffer->write<uint8_t>(SECONDARY_FIRED);
state->sendbuffer->write<uint8_t>(state->findplayerid(state->get<Character>(owner)->owner));
}
else if (isfthing and fthanim.getpercent() >= 1)
{
firesecondary(state);
}
}
else
{
isfthing = false;
fthanim.active(false);
}
}
void Peacemaker::firesecondary(Gamestate *state)
{
EntityPtr newshot = state->make_entity<PeacemakerBullet>(state, owner);
PeacemakerBullet *shot = state->get<PeacemakerBullet>(newshot);
double spread = (2*(rand()/(RAND_MAX+1.0)) - 1)*25*3.1415/180.0;
shot->x = x+std::cos(aimdirection+spread)*10;
shot->y = y+std::sin(aimdirection+spread)*10;
shot->hspeed = std::cos(aimdirection+spread) * bulletspeed;
shot->vspeed = std::sin(aimdirection+spread) * bulletspeed;
Explosion *e = state->get<Explosion>(state->make_entity<Explosion>(state, "heroes/mccree/projectiletrail/", aimdirection+spread));
e->x = x+std::cos(aimdirection+spread)*24;
e->y = y+std::sin(aimdirection+spread)*24;
--clip;
if (clip > 0)
{
if (isfthing)
{
fthanim = Animation("heroes/mccree/fanthehammerloop/", std::bind(&Peacemaker::wantfiresecondary, this, state));
}
else
{
fthanim = Animation("heroes/mccree/fanthehammerstart/", std::bind(&Peacemaker::wantfiresecondary, this, state));
isfthing = true;
}
}
}
WeaponChildParameters Peacemaker::constructparameters(Gamestate *state)
{
WeaponChildParameters p;
p.clipsize = 6;
p.characterfolder = "heroes/mccree/";
p.reloadfunction = std::bind(&Peacemaker::restoreclip, this, state);
return p;
}
<commit_msg>Fixed a bug related to the owner change two commits ago.<commit_after>#include <cmath>
#include "ingameelements/weapons/peacemaker.h"
#include "renderer.h"
#include "ingameelements/projectiles/peacemakerbullet.h"
#include "ingameelements/heroes/mccree.h"
#include "ingameelements/explosion.h"
#include "engine.h"
Peacemaker::Peacemaker(uint64_t id_, Gamestate *state, EntityPtr owner_) : Weapon(id_, state, owner_, constructparameters(state)),
fthanim("heroes/mccree/fanthehammerstart/", std::bind(&Peacemaker::firesecondary, this, state)), isfthing(false)
{
fthanim.active(false);
}
Peacemaker::~Peacemaker()
{
//dtor
}
void Peacemaker::render(Renderer *renderer, Gamestate *state)
{
std::string mainsprite;
double dir = aimdirection;
Mccree *c = state->get<Mccree>(state->get<Player>(owner)->character);
if (firinganim.active())
{
mainsprite = firinganim.getframe();
}
else if (reloadanim.active())
{
mainsprite = reloadanim.getframe();
dir = 3.1415*c->isflipped;
}
else if (fthanim.active())
{
mainsprite = fthanim.getframe();
}
else
{
mainsprite = c->getcharacterfolder()+"arm/1.png";
}
ALLEGRO_BITMAP *sprite = renderer->spriteloader.requestsprite(mainsprite);
int spriteoffset_x = renderer->spriteloader.get_spriteoffset_x(mainsprite);
int spriteoffset_y = renderer->spriteloader.get_spriteoffset_y(mainsprite);
al_set_target_bitmap(renderer->midground);
if (not c->rollanim.active())
{
if (c->isflipped)
{
al_draw_scaled_rotated_bitmap(sprite, -getattachpoint_x()-spriteoffset_x, getattachpoint_y()+spriteoffset_y, x - renderer->cam_x, y - renderer->cam_y, 1, -1, dir, 0);
}
else
{
al_draw_rotated_bitmap(sprite, getattachpoint_x()+spriteoffset_x, getattachpoint_y()+spriteoffset_y, x - renderer->cam_x, y - renderer->cam_y, dir, 0);
}
}
}
void Peacemaker::midstep(Gamestate *state, double frametime)
{
Weapon::midstep(state, frametime);
if (isfthing)
{
fthanim.active(true);
}
fthanim.update(state, frametime);
}
void Peacemaker::reload(Gamestate *state)
{
if (clip < getclipsize() and not firinganim.active() and not reloadanim.active() and not isfthing)
{
// We need to reload
reloadanim.reset();
reloadanim.active(true);
}
}
void Peacemaker::wantfireprimary(Gamestate *state)
{
if (state->engine->isserver and clip > 0 and not firinganim.active())
{
fireprimary(state);
state->sendbuffer->write<uint8_t>(PRIMARY_FIRED);
state->sendbuffer->write<uint8_t>(state->findplayerid(owner));
}
}
void Peacemaker::fireprimary(Gamestate *state)
{
EntityPtr newshot = state->make_entity<PeacemakerBullet>(state, owner);
PeacemakerBullet *shot = state->get<PeacemakerBullet>(newshot);
shot->x = x+std::cos(aimdirection)*10;
shot->y = y+std::sin(aimdirection)*10;
shot->hspeed = std::cos(aimdirection) * bulletspeed;
shot->vspeed = std::sin(aimdirection) * bulletspeed;
Explosion *e = state->get<Explosion>(state->make_entity<Explosion>(state, "heroes/mccree/projectiletrail/", aimdirection));
e->x = x+std::cos(aimdirection)*24;
e->y = y+std::sin(aimdirection)*24;
--clip;
firinganim.reset();
firinganim.active(true);
}
void Peacemaker::wantfiresecondary(Gamestate *state)
{
if (clip > 0)
{
if (not isfthing and state->engine->isserver)
{
firesecondary(state);
state->sendbuffer->write<uint8_t>(SECONDARY_FIRED);
state->sendbuffer->write<uint8_t>(state->findplayerid(owner));
}
else if (isfthing and fthanim.getpercent() >= 1)
{
firesecondary(state);
}
}
else
{
isfthing = false;
fthanim.active(false);
}
}
void Peacemaker::firesecondary(Gamestate *state)
{
EntityPtr newshot = state->make_entity<PeacemakerBullet>(state, owner);
PeacemakerBullet *shot = state->get<PeacemakerBullet>(newshot);
double spread = (2*(rand()/(RAND_MAX+1.0)) - 1)*25*3.1415/180.0;
shot->x = x+std::cos(aimdirection+spread)*10;
shot->y = y+std::sin(aimdirection+spread)*10;
shot->hspeed = std::cos(aimdirection+spread) * bulletspeed;
shot->vspeed = std::sin(aimdirection+spread) * bulletspeed;
Explosion *e = state->get<Explosion>(state->make_entity<Explosion>(state, "heroes/mccree/projectiletrail/", aimdirection+spread));
e->x = x+std::cos(aimdirection+spread)*24;
e->y = y+std::sin(aimdirection+spread)*24;
--clip;
if (clip > 0)
{
if (isfthing)
{
fthanim = Animation("heroes/mccree/fanthehammerloop/", std::bind(&Peacemaker::wantfiresecondary, this, state));
}
else
{
fthanim = Animation("heroes/mccree/fanthehammerstart/", std::bind(&Peacemaker::wantfiresecondary, this, state));
isfthing = true;
}
}
}
WeaponChildParameters Peacemaker::constructparameters(Gamestate *state)
{
WeaponChildParameters p;
p.clipsize = 6;
p.characterfolder = "heroes/mccree/";
p.reloadfunction = std::bind(&Peacemaker::restoreclip, this, state);
return p;
}
<|endoftext|> |
<commit_before> /*
* Gather entropy by running various system commands in the hopes that
* some of the output cannot be guessed by a remote attacker.
*
* (C) 1999-2009,2013 Jack Lloyd
* 2012 Markus Wanner
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/unix_procs.h>
#include <botan/parsing.h>
#include <algorithm>
#include <atomic>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
namespace Botan {
namespace {
std::string find_full_path_if_exists(const std::vector<std::string>& trusted_path,
const std::string& proc)
{
for(auto dir : trusted_path)
{
const std::string full_path = dir + "/" + proc;
if(::access(full_path.c_str(), X_OK) == 0)
return full_path;
}
return "";
}
size_t concurrent_processes(size_t user_request)
{
const size_t DEFAULT_CONCURRENT = 2;
const size_t MAX_CONCURRENT = 8;
if(user_request > 0 && user_request < MAX_CONCURRENT)
return user_request;
const long online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
if(online_cpus > 0)
return static_cast<size_t>(online_cpus); // maybe fewer?
return DEFAULT_CONCURRENT;
}
}
/**
* Unix_EntropySource Constructor
*/
Unix_EntropySource::Unix_EntropySource(const std::vector<std::string>& trusted_path,
size_t proc_cnt) :
m_trusted_paths(trusted_path),
m_concurrent(concurrent_processes(proc_cnt))
{
}
void UnixProcessInfo_EntropySource::poll(Entropy_Accumulator& accum)
{
static std::atomic<int> last_pid;
int pid = ::getpid();
accum.add(pid, 0.0);
if(pid != last_pid)
{
last_pid = pid;
accum.add(::getppid(), 0.0);
accum.add(::getuid(), 0.0);
accum.add(::getgid(), 0.0);
accum.add(::getsid(0), 0.0);
accum.add(::getpgrp(), 0.0);
}
struct ::rusage usage;
::getrusage(RUSAGE_SELF, &usage);
accum.add(usage, 0.0);
}
namespace {
void do_exec(const std::vector<std::string>& args)
{
// cleaner way to do this?
const char* arg0 = (args.size() > 0) ? args[0].c_str() : nullptr;
const char* arg1 = (args.size() > 1) ? args[1].c_str() : nullptr;
const char* arg2 = (args.size() > 2) ? args[2].c_str() : nullptr;
const char* arg3 = (args.size() > 3) ? args[3].c_str() : nullptr;
const char* arg4 = (args.size() > 4) ? args[4].c_str() : nullptr;
::execl(arg0, arg0, arg1, arg2, arg3, arg4, NULL);
}
}
void Unix_EntropySource::Unix_Process::spawn(const std::vector<std::string>& args)
{
shutdown();
int pipe[2];
if(::pipe(pipe) != 0)
return;
pid_t pid = ::fork();
if(pid == -1)
{
::close(pipe[0]);
::close(pipe[1]);
}
else if(pid > 0) // in parent
{
m_pid = pid;
m_fd = pipe[0];
::close(pipe[1]);
}
else // in child
{
if(::dup2(pipe[1], STDOUT_FILENO) == -1)
::exit(127);
if(::close(pipe[0]) != 0 || ::close(pipe[1]) != 0)
::exit(127);
if(close(STDERR_FILENO) != 0)
::exit(127);
do_exec(args);
::exit(127);
}
}
void Unix_EntropySource::Unix_Process::shutdown()
{
if(m_pid == -1)
return;
::close(m_fd);
m_fd = -1;
pid_t reaped = waitpid(m_pid, nullptr, WNOHANG);
if(reaped == 0)
{
/*
* Child is still alive - send it SIGTERM, sleep for a bit and
* try to reap again, if still alive send SIGKILL
*/
kill(m_pid, SIGTERM);
struct ::timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 1000;
select(0, nullptr, nullptr, nullptr, &tv);
reaped = ::waitpid(m_pid, nullptr, WNOHANG);
if(reaped == 0)
{
::kill(m_pid, SIGKILL);
do
reaped = ::waitpid(m_pid, nullptr, 0);
while(reaped == -1);
}
}
m_pid = -1;
}
const std::vector<std::string>& Unix_EntropySource::next_source()
{
const auto& src = m_sources.at(m_sources_idx);
m_sources_idx = (m_sources_idx + 1) % m_sources.size();
return src;
}
void Unix_EntropySource::poll(Entropy_Accumulator& accum)
{
// refuse to run setuid or setgid, or as root
if((getuid() != geteuid()) || (getgid() != getegid()) || (geteuid() == 0))
return;
std::lock_guard<std::mutex> lock(m_mutex);
if(m_sources.empty())
{
auto sources = get_default_sources();
for(auto src : sources)
{
const std::string path = find_full_path_if_exists(m_trusted_paths, src[0]);
if(path != "")
{
src[0] = path;
m_sources.push_back(src);
}
}
}
if(m_sources.empty())
return; // still empty, really nothing to try
const size_t MS_WAIT_TIME = 32;
const double ENTROPY_ESTIMATE = 1.0 / 1024;
m_buf.resize(4096);
while(!accum.polling_finished())
{
while(m_procs.size() < m_concurrent)
m_procs.emplace_back(Unix_Process(next_source()));
fd_set read_set;
FD_ZERO(&read_set);
std::vector<int> fds;
for(auto& proc : m_procs)
{
int fd = proc.fd();
if(fd > 0)
{
fds.push_back(fd);
FD_SET(fd, &read_set);
}
}
if(fds.empty())
break;
const int max_fd = *std::max_element(fds.begin(), fds.end());
struct ::timeval timeout;
timeout.tv_sec = (MS_WAIT_TIME / 1000);
timeout.tv_usec = (MS_WAIT_TIME % 1000) * 1000;
if(::select(max_fd + 1, &read_set, nullptr, nullptr, &timeout) < 0)
return; // or continue?
for(auto& proc : m_procs)
{
int fd = proc.fd();
if(FD_ISSET(fd, &read_set))
{
const ssize_t got = ::read(fd, &m_buf[0], m_buf.size());
if(got > 0)
accum.add(&m_buf[0], got, ENTROPY_ESTIMATE);
else
proc.spawn(next_source());
}
}
}
}
}
<commit_msg>This check doesn't make sense as the entropy source is shared<commit_after> /*
* Gather entropy by running various system commands in the hopes that
* some of the output cannot be guessed by a remote attacker.
*
* (C) 1999-2009,2013 Jack Lloyd
* 2012 Markus Wanner
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/unix_procs.h>
#include <botan/parsing.h>
#include <algorithm>
#include <atomic>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
namespace Botan {
namespace {
std::string find_full_path_if_exists(const std::vector<std::string>& trusted_path,
const std::string& proc)
{
for(auto dir : trusted_path)
{
const std::string full_path = dir + "/" + proc;
if(::access(full_path.c_str(), X_OK) == 0)
return full_path;
}
return "";
}
size_t concurrent_processes(size_t user_request)
{
const size_t DEFAULT_CONCURRENT = 2;
const size_t MAX_CONCURRENT = 8;
if(user_request > 0 && user_request < MAX_CONCURRENT)
return user_request;
const long online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
if(online_cpus > 0)
return static_cast<size_t>(online_cpus); // maybe fewer?
return DEFAULT_CONCURRENT;
}
}
/**
* Unix_EntropySource Constructor
*/
Unix_EntropySource::Unix_EntropySource(const std::vector<std::string>& trusted_path,
size_t proc_cnt) :
m_trusted_paths(trusted_path),
m_concurrent(concurrent_processes(proc_cnt))
{
}
void UnixProcessInfo_EntropySource::poll(Entropy_Accumulator& accum)
{
accum.add(::getpid(), 0.0);
accum.add(::getppid(), 0.0);
accum.add(::getuid(), 0.0);
accum.add(::getgid(), 0.0);
accum.add(::getsid(0), 0.0);
accum.add(::getpgrp(), 0.0);
struct ::rusage usage;
::getrusage(RUSAGE_SELF, &usage);
accum.add(usage, 0.0);
}
namespace {
void do_exec(const std::vector<std::string>& args)
{
// cleaner way to do this?
const char* arg0 = (args.size() > 0) ? args[0].c_str() : nullptr;
const char* arg1 = (args.size() > 1) ? args[1].c_str() : nullptr;
const char* arg2 = (args.size() > 2) ? args[2].c_str() : nullptr;
const char* arg3 = (args.size() > 3) ? args[3].c_str() : nullptr;
const char* arg4 = (args.size() > 4) ? args[4].c_str() : nullptr;
::execl(arg0, arg0, arg1, arg2, arg3, arg4, NULL);
}
}
void Unix_EntropySource::Unix_Process::spawn(const std::vector<std::string>& args)
{
shutdown();
int pipe[2];
if(::pipe(pipe) != 0)
return;
pid_t pid = ::fork();
if(pid == -1)
{
::close(pipe[0]);
::close(pipe[1]);
}
else if(pid > 0) // in parent
{
m_pid = pid;
m_fd = pipe[0];
::close(pipe[1]);
}
else // in child
{
if(::dup2(pipe[1], STDOUT_FILENO) == -1)
::exit(127);
if(::close(pipe[0]) != 0 || ::close(pipe[1]) != 0)
::exit(127);
if(close(STDERR_FILENO) != 0)
::exit(127);
do_exec(args);
::exit(127);
}
}
void Unix_EntropySource::Unix_Process::shutdown()
{
if(m_pid == -1)
return;
::close(m_fd);
m_fd = -1;
pid_t reaped = waitpid(m_pid, nullptr, WNOHANG);
if(reaped == 0)
{
/*
* Child is still alive - send it SIGTERM, sleep for a bit and
* try to reap again, if still alive send SIGKILL
*/
kill(m_pid, SIGTERM);
struct ::timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 1000;
select(0, nullptr, nullptr, nullptr, &tv);
reaped = ::waitpid(m_pid, nullptr, WNOHANG);
if(reaped == 0)
{
::kill(m_pid, SIGKILL);
do
reaped = ::waitpid(m_pid, nullptr, 0);
while(reaped == -1);
}
}
m_pid = -1;
}
const std::vector<std::string>& Unix_EntropySource::next_source()
{
const auto& src = m_sources.at(m_sources_idx);
m_sources_idx = (m_sources_idx + 1) % m_sources.size();
return src;
}
void Unix_EntropySource::poll(Entropy_Accumulator& accum)
{
// refuse to run setuid or setgid, or as root
if((getuid() != geteuid()) || (getgid() != getegid()) || (geteuid() == 0))
return;
std::lock_guard<std::mutex> lock(m_mutex);
if(m_sources.empty())
{
auto sources = get_default_sources();
for(auto src : sources)
{
const std::string path = find_full_path_if_exists(m_trusted_paths, src[0]);
if(path != "")
{
src[0] = path;
m_sources.push_back(src);
}
}
}
if(m_sources.empty())
return; // still empty, really nothing to try
const size_t MS_WAIT_TIME = 32;
const double ENTROPY_ESTIMATE = 1.0 / 1024;
m_buf.resize(4096);
while(!accum.polling_finished())
{
while(m_procs.size() < m_concurrent)
m_procs.emplace_back(Unix_Process(next_source()));
fd_set read_set;
FD_ZERO(&read_set);
std::vector<int> fds;
for(auto& proc : m_procs)
{
int fd = proc.fd();
if(fd > 0)
{
fds.push_back(fd);
FD_SET(fd, &read_set);
}
}
if(fds.empty())
break;
const int max_fd = *std::max_element(fds.begin(), fds.end());
struct ::timeval timeout;
timeout.tv_sec = (MS_WAIT_TIME / 1000);
timeout.tv_usec = (MS_WAIT_TIME % 1000) * 1000;
if(::select(max_fd + 1, &read_set, nullptr, nullptr, &timeout) < 0)
return; // or continue?
for(auto& proc : m_procs)
{
int fd = proc.fd();
if(FD_ISSET(fd, &read_set))
{
const ssize_t got = ::read(fd, &m_buf[0], m_buf.size());
if(got > 0)
accum.add(&m_buf[0], got, ENTROPY_ESTIMATE);
else
proc.spawn(next_source());
}
}
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <linal/linear_equation.hpp>
namespace Linal
{
template <typename T>
class LinearSystem
{
public:
LinearSystem(std::initializer_list<LinearEquation<T>> l)
: eqs(l.size())
{
/* Currently there's no way to move from initializer_list, so we're actually copying.
* http://stackoverflow.com/questions/8193102/initializer-list-and-move-semantics
*/
std::move(l.begin(), l.end(), eqs.begin());
}
const LinearEquation<T> & operator[](int idx) const
{
return eqs[idx];
}
LinearEquation<T> & operator[](int idx)
{
return eqs[idx];
}
void swapRows(int i, int j)
{
assert(i >= 0 && i < int(eqs.size()) && j >= 0 && j < int(eqs.size()));
assert(eqs[i].ndim() == eqs[j].ndim());
swap(eqs[i], eqs[j]); // very cheap operation
}
/// Turns linear system into triangular form in-place.
/// Assumes all rows have the same number of variables.
void computeTriangularForm()
{
// eliminating i-th variable from rows i+1 and below
for (int i = 0; i < eqs.front().ndim(); ++i)
{
// trying to find row with non-zero coefficient at i-th variable
int rowWithIthVar = -1;
for (int j = 0; j < int(eqs.size()); ++j)
{
const int idx = eqs[j].firstNonZeroIndex();
if (idx == -1)
continue;
// rows below i-1 can't have i-1 as leading variable
assert(i == 0 || j < i || idx >= i);
if (idx == i)
{
rowWithIthVar = j; // found row with leading i-th variable
break;
}
}
if (rowWithIthVar == -1)
{
// i-th variable already eliminated from the system
continue;
}
// swap row with "current" row
if (rowWithIthVar != i)
swapRows(i, rowWithIthVar);
// subtract found row from all rows below
for (int j = i + 1; j < int(eqs.size()); ++j)
{
const auto coeff = (-1.0f / eqs[i][i]) * eqs[j][i];
eqs[j].add(eqs[i], coeff);
}
}
}
/// Computes reduced row-echelon form in-place.
void computeRREF()
{
computeTriangularForm();
// iterate from last to first row, eliminating leading variable from rows above
for (int i = int(eqs.size()) - 1; i >= 0; --i)
{
const int idx = eqs[i].firstNonZeroIndex();
if (idx == -1) // no variables (0 = 0 or 0 = k)
continue;
// make sure coefficient at leading variable is one
eqs[i] *= 1.0f / eqs[i][idx];
// subtract row from all rows above
for (int j = i - 1; j >= 0; --j)
eqs[j].add(eqs[i], -eqs[j][idx]);
}
}
public:
friend std::ostream & operator<<(std::ostream &stream, const LinearSystem<T> &s)
{
for (const auto &eq : s.eqs)
stream << eq << std::endl;
return stream;
}
private:
std::vector<LinearEquation<T>> eqs;
};
}<commit_msg>Added linear system solution<commit_after>#pragma once
#include <map>
#include <linal/linear_equation.hpp>
namespace Linal
{
enum class SolutionType
{
UNKNOWN,
UNIQUE,
PARAMETRIZATION,
NO_SOLUTIONS,
};
template <typename T>
class LinearSystemSolution
{
public:
LinearSystemSolution(SolutionType type, std::map<int, T> values = std::map<int, T>())
: type{ type }
, values{ std::move(values) }
{
}
public:
friend std::ostream & operator<<(std::ostream &stream, const LinearSystemSolution<T> &s)
{
stream << "[Type: " << int(s.type) << " values: {";
for (const auto &value : s.values)
stream << value.first << ": " << value.second << ", ";
stream << "}";
return stream;
}
public:
std::map<int, T> values;
SolutionType type = SolutionType::UNKNOWN;
};
template <typename T>
class LinearSystem
{
public:
LinearSystem(std::initializer_list<LinearEquation<T>> l)
: eqs(l.size())
{
/* Currently there's no way to move from initializer_list, so we're actually copying.
* http://stackoverflow.com/questions/8193102/initializer-list-and-move-semantics
*/
std::move(l.begin(), l.end(), eqs.begin());
}
const LinearEquation<T> & operator[](int idx) const
{
return eqs[idx];
}
LinearEquation<T> & operator[](int idx)
{
return eqs[idx];
}
void swapRows(int i, int j)
{
assert(i >= 0 && i < int(eqs.size()) && j >= 0 && j < int(eqs.size()));
assert(eqs[i].ndim() == eqs[j].ndim());
swap(eqs[i], eqs[j]); // very cheap operation
}
/// Turns linear system into triangular form in-place.
/// Assumes all rows have the same number of variables.
void computeTriangularForm()
{
// eliminating i-th variable from rows i+1 and below
for (int i = 0; i < eqs.front().ndim(); ++i)
{
// trying to find row with non-zero coefficient at i-th variable
int rowWithIthVar = -1;
for (int j = 0; j < int(eqs.size()); ++j)
{
const int idx = eqs[j].firstNonZeroIndex();
if (idx == -1)
continue;
// rows below i-1 can't have i-1 as leading variable
assert(i == 0 || j < i || idx >= i);
if (idx == i)
{
rowWithIthVar = j; // found row with leading i-th variable
break;
}
}
if (rowWithIthVar == -1)
{
// i-th variable already eliminated from the system
continue;
}
// swap row with "current" row
if (rowWithIthVar != i)
swapRows(i, rowWithIthVar);
// subtract found row from all rows below
for (int j = i + 1; j < int(eqs.size()); ++j)
{
const auto coeff = (-1.0f / eqs[i][i]) * eqs[j][i];
eqs[j].add(eqs[i], coeff);
}
}
}
/// Computes reduced row-echelon form in-place.
void computeRREF()
{
computeTriangularForm();
// iterate from last to first row, eliminating leading variable from rows above
for (int i = int(eqs.size()) - 1; i >= 0; --i)
{
const int idx = eqs[i].firstNonZeroIndex();
if (idx == -1) // no variables (0 = 0 or 0 = k)
continue;
// make sure coefficient at leading variable is one
eqs[i] *= 1.0f / eqs[i][idx];
// subtract row from all rows above
for (int j = i - 1; j >= 0; --j)
eqs[j].add(eqs[i], -eqs[j][idx]);
}
}
auto computeSolution()
{
computeRREF();
std::map<int, T> values;
for (const auto &eq : eqs)
{
const int idx = eq.firstNonZeroIndex();
if (idx == -1)
{
// row 0x + 0y + 0z = ?
if (eq.constTerm() != 0) // contradiction
return LinearSystemSolution<T>(SolutionType::NO_SOLUTIONS);
continue;
}
assert(!values.count(idx));
values[idx] = eq.constTerm();
}
const SolutionType type = (values.size() == eqs.front().ndim()) ? SolutionType::UNIQUE : SolutionType::PARAMETRIZATION;
return LinearSystemSolution<T>(type, std::move(values));
}
public:
friend std::ostream & operator<<(std::ostream &stream, const LinearSystem<T> &s)
{
for (const auto &eq : s.eqs)
stream << eq << std::endl;
return stream;
}
private:
std::vector<LinearEquation<T>> eqs;
};
}<|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.
*/
#include "DataOutputStream.h"
#include <activemq/util/Config.h>
using namespace activemq;
using namespace activemq::io;
////////////////////////////////////////////////////////////////////////////////
DataOutputStream::DataOutputStream( OutputStream* outputStream, bool own )
: FilterOutputStream( outputStream, own )
{
// Init the written count
written = 0;
}
////////////////////////////////////////////////////////////////////////////////
DataOutputStream::~DataOutputStream()
{
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::write( const unsigned char c ) throw ( IOException ) {
try {
outputStream->write( c );
written++;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::write( const std::vector<unsigned char>& buffer )
throw ( IOException ) {
try {
if( buffer.size() == 0 ){
// nothing to write.
return;
}
outputStream->write( &buffer[0], buffer.size() );
written += buffer.size();
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::write( const unsigned char* buffer, std::size_t len )
throw ( IOException ) {
try {
outputStream->write( buffer, len );
written += len;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::write( const unsigned char* buffer,
std::size_t offset,
std::size_t len ) throw ( IOException )
{
try {
outputStream->write( buffer+offset, len );
written += len;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeBoolean( bool value ) throw ( IOException ) {
try {
unsigned char ivalue = 0;
value == true ? ivalue = 1 : ivalue = 0;
outputStream->write( ivalue );
written++;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeByte( unsigned char value ) throw ( IOException ) {
try {
outputStream->write( value );
written++;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeChar( char value ) throw ( IOException ) {
try {
write( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeShort( short value ) throw ( IOException ) {
try {
unsigned char buffer[sizeof(value)];
buffer[0] = (value & 0xFF00) >> 8;
buffer[1] = (value & 0x00FF) >> 0;
outputStream->write( buffer, sizeof(value) );
written += sizeof( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeUnsignedShort( unsigned short value )
throw ( IOException )
{
try {
unsigned char buffer[sizeof(value)];
buffer[0] = (value & 0xFF00) >> 8;
buffer[1] = (value & 0x00FF) >> 0;
outputStream->write( buffer, sizeof(value) );
written += sizeof( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeInt( int value ) throw ( IOException ) {
try {
unsigned char buffer[sizeof(value)];
buffer[0] = (value & 0xFF000000) >> 24;
buffer[1] = (value & 0x00FF0000) >> 16;
buffer[2] = (value & 0x0000FF00) >> 8;
buffer[3] = (value & 0x000000FF) >> 0;
outputStream->write( buffer, sizeof(value) );
written += sizeof( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeLong( long long value ) throw ( IOException ) {
try {
unsigned char buffer[sizeof(value)];
buffer[0] = (value & 0xFF00000000000000ULL) >> 56;
buffer[1] = (value & 0x00FF000000000000ULL) >> 48;
buffer[2] = (value & 0x0000FF0000000000ULL) >> 40;
buffer[3] = (value & 0x000000FF00000000ULL) >> 32;
buffer[4] = (value & 0x00000000FF000000ULL) >> 24;
buffer[5] = (value & 0x0000000000FF0000ULL) >> 16;
buffer[6] = (value & 0x000000000000FF00ULL) >> 8;
buffer[7] = (value & 0x00000000000000FFULL) >> 0;
outputStream->write( buffer, sizeof(value) );
written += sizeof( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeFloat( float value ) throw ( IOException ) {
try {
unsigned int lvalue = 0;
memcpy( &lvalue, &value, sizeof( float ) );
this->writeInt( lvalue );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeDouble( double value ) throw ( IOException ) {
try {
unsigned long long lvalue = 0;
memcpy( &lvalue, &value, sizeof( double ) );
this->writeLong( lvalue );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeBytes( const std::string& value ) throw ( IOException ) {
try {
// do not add one so that we don't write the NULL
this->write( (const unsigned char*)value.c_str(), value.length() );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeChars( const std::string& value ) throw ( IOException ) {
try {
// add one so that we write the NULL
this->write( (const unsigned char*)value.c_str(), value.length() + 1 );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeUTF( const std::string& value ) throw ( IOException ) {
try {
this->writeUnsignedShort( (unsigned short)value.length() );
this->write( (const unsigned char*)value.c_str(), value.length() );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
<commit_msg>Get rid of a Windows Compiler warning.<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.
*/
#include "DataOutputStream.h"
#include <activemq/util/Config.h>
using namespace activemq;
using namespace activemq::io;
////////////////////////////////////////////////////////////////////////////////
DataOutputStream::DataOutputStream( OutputStream* outputStream, bool own )
: FilterOutputStream( outputStream, own )
{
// Init the written count
written = 0;
}
////////////////////////////////////////////////////////////////////////////////
DataOutputStream::~DataOutputStream()
{
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::write( const unsigned char c ) throw ( IOException ) {
try {
outputStream->write( c );
written++;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::write( const std::vector<unsigned char>& buffer )
throw ( IOException ) {
try {
if( buffer.size() == 0 ){
// nothing to write.
return;
}
outputStream->write( &buffer[0], buffer.size() );
written += buffer.size();
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::write( const unsigned char* buffer, std::size_t len )
throw ( IOException ) {
try {
outputStream->write( buffer, len );
written += len;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::write( const unsigned char* buffer,
std::size_t offset,
std::size_t len ) throw ( IOException )
{
try {
outputStream->write( buffer+offset, len );
written += len;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeBoolean( bool value ) throw ( IOException ) {
try {
unsigned char ivalue = 0;
value == true ? ivalue = 1 : ivalue = 0;
outputStream->write( ivalue );
written++;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeByte( unsigned char value ) throw ( IOException ) {
try {
outputStream->write( value );
written++;
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeChar( char value ) throw ( IOException ) {
try {
write( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeShort( short value ) throw ( IOException ) {
try {
unsigned char buffer[sizeof(value)];
buffer[0] = (value & 0xFF00) >> 8;
buffer[1] = (value & 0x00FF) >> 0;
outputStream->write( buffer, sizeof(value) );
written += sizeof( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeUnsignedShort( unsigned short value )
throw ( IOException )
{
try {
unsigned char buffer[sizeof(value)];
buffer[0] = (value & 0xFF00) >> 8;
buffer[1] = (value & 0x00FF) >> 0;
outputStream->write( buffer, sizeof(value) );
written += sizeof( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeInt( int value ) throw ( IOException ) {
try {
unsigned char buffer[sizeof(value)];
buffer[0] = (value & 0xFF000000) >> 24;
buffer[1] = (value & 0x00FF0000) >> 16;
buffer[2] = (value & 0x0000FF00) >> 8;
buffer[3] = (value & 0x000000FF) >> 0;
outputStream->write( buffer, sizeof(value) );
written += sizeof( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeLong( long long value ) throw ( IOException ) {
try {
unsigned char buffer[sizeof(value)];
buffer[0] = (unsigned char)((value & 0xFF00000000000000ULL) >> 56);
buffer[1] = (unsigned char)((value & 0x00FF000000000000ULL) >> 48);
buffer[2] = (unsigned char)((value & 0x0000FF0000000000ULL) >> 40);
buffer[3] = (unsigned char)((value & 0x000000FF00000000ULL) >> 32);
buffer[4] = (unsigned char)((value & 0x00000000FF000000ULL) >> 24);
buffer[5] = (unsigned char)((value & 0x0000000000FF0000ULL) >> 16);
buffer[6] = (unsigned char)((value & 0x000000000000FF00ULL) >> 8);
buffer[7] = (unsigned char)((value & 0x00000000000000FFULL) >> 0);
outputStream->write( buffer, sizeof(value) );
written += sizeof( value );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeFloat( float value ) throw ( IOException ) {
try {
unsigned int lvalue = 0;
memcpy( &lvalue, &value, sizeof( float ) );
this->writeInt( lvalue );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeDouble( double value ) throw ( IOException ) {
try {
unsigned long long lvalue = 0;
memcpy( &lvalue, &value, sizeof( double ) );
this->writeLong( lvalue );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeBytes( const std::string& value ) throw ( IOException ) {
try {
// do not add one so that we don't write the NULL
this->write( (const unsigned char*)value.c_str(), value.length() );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeChars( const std::string& value ) throw ( IOException ) {
try {
// add one so that we write the NULL
this->write( (const unsigned char*)value.c_str(), value.length() + 1 );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
////////////////////////////////////////////////////////////////////////////////
void DataOutputStream::writeUTF( const std::string& value ) throw ( IOException ) {
try {
this->writeUnsignedShort( (unsigned short)value.length() );
this->write( (const unsigned char*)value.c_str(), value.length() );
}
AMQ_CATCH_RETHROW( IOException )
AMQ_CATCHALL_THROW( IOException )
}
<|endoftext|> |
<commit_before>/*
* TTBlue Limiter Object
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTLimiter.h"
#define thisTTClass TTLimiter
#define thisTTClassName "limiter"
#define thisTTClassTags "audio, processor, dynamics, limiter"
TT_AUDIO_CONSTRUCTOR
, recover(0.0), lookaheadBufferIndex(0), lookaheadBuffer(NULL), gain(NULL), last(0.0)
, dcBlocker(NULL), preamp(NULL), maxBufferSize(512), attrMode(TT("exponential"))
{
TTUInt16 initialMaxNumChannels = arguments;
// register our attributes
registerAttribute(TT("Preamp"), kTypeFloat64, NULL, (TTGetterMethod)&TTLimiter::getPreamp, (TTSetterMethod)&TTLimiter::setPreamp);
registerAttribute(TT("Postamp"), kTypeFloat64, &attrPostamp, (TTGetterMethod)&TTLimiter::getPostamp, (TTSetterMethod)&TTLimiter::setPostamp);
registerAttribute(TT("Threshold"), kTypeFloat64, &attrThreshold, (TTGetterMethod)&TTLimiter::getThreshold, (TTSetterMethod)&TTLimiter::setThreshold);
registerAttribute(TT("Lookahead"), kTypeUInt32, &attrLookahead, (TTSetterMethod)&TTLimiter::setLookahead);
registerAttribute(TT("Release"), kTypeFloat64, &attrRelease, (TTSetterMethod)&TTLimiter::setRelease);
registerAttribute(TT("Mode"), kTypeSymbol, &attrMode, (TTSetterMethod)&TTLimiter::setMode);
registerAttribute(TT("DcBlocker"), kTypeBoolean, &attrDCBlocker, (TTSetterMethod)&TTLimiter::setDCBlocker);
// register for notifications from the parent class so we can allocate memory as required
registerMessageWithArgument(updateMaxNumChannels);
// register for notifications from the parent class so we can update the release/recover values
registerMessageSimple(updateSr);
// clear the history
addMessage(Clear);
TTObjectInstantiate(kTTSym_dcblock, &dcBlocker, initialMaxNumChannels);
TTObjectInstantiate(kTTSym_gain, &preamp, initialMaxNumChannels);
// Set Defaults...
setAttributeValue(TT("MaxNumChannels"), initialMaxNumChannels);
setAttributeValue(TT("Threshold"), 0.0);
setAttributeValue(TT("Preamp"), 0.0);
setAttributeValue(TT("Postamp"), 0.0);
setAttributeValue(TT("Lookahead"), 100);
setAttributeValue(TT("Mode"), TT("exponential"));
setAttributeValue(TT("Release"), 1000.0);
setAttributeValue(TT("DcBlocker"), kTTBoolYes);
setAttributeValue(TT("Bypass"), kTTBoolNo);
Clear();
setProcessMethod(processAudio);
}
TTLimiter::~TTLimiter()
{
short i;
for (i=0; i<maxNumChannels; i++)
delete [] lookaheadBuffer[i];
delete [] lookaheadBuffer;
delete [] gain;
TTObjectRelease(&dcBlocker);
TTObjectRelease(&preamp);
}
// TODO: These message receiver args should be reversed -- this is a change that should be applied throughout TTBlue
TTErr TTLimiter::updateMaxNumChannels(const TTValue& oldMaxNumChannels)
{
TTUInt16 channel;
TTUInt16 numChannels = oldMaxNumChannels;
if (lookaheadBuffer) {
for (channel=0; channel<numChannels; channel++)
delete [] lookaheadBuffer[channel];
delete [] lookaheadBuffer;
}
delete gain;
gain = new TTSampleValue[maxBufferSize];
lookaheadBuffer = new TTSampleValuePtr[maxNumChannels];
for (channel=0; channel<maxNumChannels; channel++)
lookaheadBuffer[channel] = new TTSampleValue[maxBufferSize];
Clear();
dcBlocker->setAttributeValue(TT("MaxNumChannels"), maxNumChannels);
preamp->setAttributeValue(TT("MaxNumChannels"), maxNumChannels);
return kTTErrNone;
}
TTErr TTLimiter::updateSr()
{
setRecover();
return kTTErrNone;
}
TTErr TTLimiter::setPreamp(const TTValue& newValue)
{
return preamp->setAttributeValue(TT("Gain"), const_cast<TTValue&>(newValue));
}
TTErr TTLimiter::getPreamp(TTValue& value)
{
return preamp->getAttributeValue(TT("Gain"), value);
}
TTErr TTLimiter::setPostamp(const TTValue& newValue)
{
attrPostamp = dbToLinear(newValue);
return kTTErrNone;
}
TTErr TTLimiter::getPostamp(TTValue& value)
{
value = linearToDb(attrPostamp);
return kTTErrNone;
}
TTErr TTLimiter::setThreshold(const TTValue& newValue)
{
attrThreshold = dbToLinear(newValue);
return kTTErrNone;
}
TTErr TTLimiter::getThreshold(TTValue& value)
{
value = linearToDb(attrThreshold);
return kTTErrNone;
}
TTErr TTLimiter::setLookahead(TTValue& newValue)
{
attrLookahead = TTClip(TTUInt32(newValue), TTUInt32(1), maxBufferSize-1);
lookaheadInv = 1.0 / TTFloat64(attrLookahead);
return kTTErrNone;
}
TTErr TTLimiter::setRelease(TTValue& newValue)
{
attrRelease = newValue;
setRecover();
return kTTErrNone;
}
TTErr TTLimiter::setMode(TTValue& newValue)
{
attrMode = newValue;
if (attrMode == TT("linear"))
isLinear = true;
else
isLinear = false;
setRecover();
return kTTErrNone;
}
TTErr TTLimiter::setDCBlocker(TTValue& newValue)
{
attrDCBlocker = newValue;
return dcBlocker->setAttributeValue(TT("Bypass"), !attrDCBlocker);
}
TTErr TTLimiter::Clear()
{
TTUInt32 i;
TTUInt32 channel;
for (i=0; i<maxBufferSize; i++) {
for (channel=0; channel < maxNumChannels; channel++)
lookaheadBuffer[channel][i] = 0.0;
gain[i] = 1.0; // gain is shared across channels
}
lookaheadBufferIndex = 0; // was bp
last = 1.0;
setRecover();
dcBlocker->sendMessage(TT("Clear"));
return kTTErrNone;
}
// set variables related to the time it takes for the limiter to recover from a peak in the audio
// it is based on the release time attr, which is specified in seconds
void TTLimiter::setRecover()
{
recover = 1000.0 / (attrRelease * sr);
if (attrMode == TT("linear"))
recover = recover * 0.5;
else
recover = recover * 0.707;
}
TTErr TTLimiter::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs = in.getVectorSizeAsInt();
TTUInt16 i, j;
TTSampleValue tempSample;
TTSampleValue hotSample;
TTFloat64 maybe,
curgain,
newgain,
inc,
acc;
TTInt16 flag,
lookaheadBufferPlayback,
ind;
TTUInt16 numchannels = TTAudioSignal::getMinChannelCount(in, out);
TTUInt16 channel;
// Pre-Process the input
dcBlocker->process(in, out); // filter out DC-Offsets (unless it is bypassed)
preamp->process(out, in); // copy output back to input for the rest of this process
for (i=0; i<vs; i++) {
hotSample = 0.0;
// Analysis Stage ...
for (channel=0; channel<numchannels; channel++) {
tempSample = in.mSampleVectors[channel][i];
lookaheadBuffer[channel][lookaheadBufferIndex] = tempSample * attrPostamp;
tempSample = fabs(tempSample);
if (tempSample > hotSample)
hotSample = tempSample;
}
if (isLinear)
tempSample = last + recover;
else {
if (last > 0.01)
tempSample = last + recover * last;
else
tempSample = last + recover;
}
if (tempSample > attrThreshold)
maybe = attrThreshold;
else
maybe = tempSample;
gain[lookaheadBufferIndex] = maybe;
lookaheadBufferPlayback = lookaheadBufferIndex - attrLookahead;
if (lookaheadBufferPlayback < 0)
lookaheadBufferPlayback += attrLookahead;
// Process Stage ...
// this ***very slow*** : with a lookahead of 100, and vs = 64, we loop 640 times!
if (hotSample * maybe > attrThreshold) {
curgain = attrThreshold / hotSample;
inc = (attrThreshold - curgain);
acc = 0;
flag = 0;
for (j=0; flag==0 && j<attrLookahead; j++) {
ind = lookaheadBufferIndex - j;
if (ind<0)
ind += maxBufferSize;
if (isLinear) //TODO: can't we move this condition outside the loop? isLinear won't change during a vs [NP]
newgain = curgain + inc * acc;
else
newgain = curgain + inc * (acc * acc);
if (newgain < gain[ind])
gain[ind] = newgain;
else
flag = 1;
acc = acc + lookaheadInv;
}
}
for (channel=0; channel<numchannels; channel++) {
out.mSampleVectors[channel][i] = lookaheadBuffer[channel][lookaheadBufferPlayback] * gain[lookaheadBufferPlayback];
}
last = gain[lookaheadBufferIndex];
lookaheadBufferIndex++;
if (lookaheadBufferIndex >= attrLookahead)
lookaheadBufferIndex = 0;
}
return kTTErrNone;
}
<commit_msg>TTLimiter: indentation 'fixes'<commit_after>/*
* TTBlue Limiter Object
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTLimiter.h"
#define thisTTClass TTLimiter
#define thisTTClassName "limiter"
#define thisTTClassTags "audio, processor, dynamics, limiter"
TT_AUDIO_CONSTRUCTOR
, recover(0.0), lookaheadBufferIndex(0), lookaheadBuffer(NULL), gain(NULL), last(0.0)
, dcBlocker(NULL), preamp(NULL), maxBufferSize(512), attrMode(TT("exponential"))
{
TTUInt16 initialMaxNumChannels = arguments;
// register our attributes
registerAttribute(TT("Preamp"), kTypeFloat64, NULL, (TTGetterMethod)&TTLimiter::getPreamp, (TTSetterMethod)&TTLimiter::setPreamp);
registerAttribute(TT("Postamp"), kTypeFloat64, &attrPostamp, (TTGetterMethod)&TTLimiter::getPostamp, (TTSetterMethod)&TTLimiter::setPostamp);
registerAttribute(TT("Threshold"), kTypeFloat64, &attrThreshold, (TTGetterMethod)&TTLimiter::getThreshold, (TTSetterMethod)&TTLimiter::setThreshold);
registerAttribute(TT("Lookahead"), kTypeUInt32, &attrLookahead, (TTSetterMethod)&TTLimiter::setLookahead);
registerAttribute(TT("Release"), kTypeFloat64, &attrRelease, (TTSetterMethod)&TTLimiter::setRelease);
registerAttribute(TT("Mode"), kTypeSymbol, &attrMode, (TTSetterMethod)&TTLimiter::setMode);
registerAttribute(TT("DcBlocker"), kTypeBoolean, &attrDCBlocker, (TTSetterMethod)&TTLimiter::setDCBlocker);
// register for notifications from the parent class so we can allocate memory as required
registerMessageWithArgument(updateMaxNumChannels);
// register for notifications from the parent class so we can update the release/recover values
registerMessageSimple(updateSr);
// clear the history
addMessage(Clear);
TTObjectInstantiate(kTTSym_dcblock, &dcBlocker, initialMaxNumChannels);
TTObjectInstantiate(kTTSym_gain, &preamp, initialMaxNumChannels);
// Set Defaults...
setAttributeValue(TT("MaxNumChannels"), initialMaxNumChannels);
setAttributeValue(TT("Threshold"), 0.0);
setAttributeValue(TT("Preamp"), 0.0);
setAttributeValue(TT("Postamp"), 0.0);
setAttributeValue(TT("Lookahead"), 100);
setAttributeValue(TT("Mode"), TT("exponential"));
setAttributeValue(TT("Release"), 1000.0);
setAttributeValue(TT("DcBlocker"), kTTBoolYes);
setAttributeValue(TT("Bypass"), kTTBoolNo);
Clear();
setProcessMethod(processAudio);
}
TTLimiter::~TTLimiter()
{
short i;
for (i=0; i<maxNumChannels; i++)
delete [] lookaheadBuffer[i];
delete [] lookaheadBuffer;
delete [] gain;
TTObjectRelease(&dcBlocker);
TTObjectRelease(&preamp);
}
// TODO: These message receiver args should be reversed -- this is a change that should be applied throughout TTBlue
TTErr TTLimiter::updateMaxNumChannels(const TTValue& oldMaxNumChannels)
{
TTUInt16 channel;
TTUInt16 numChannels = oldMaxNumChannels;
if (lookaheadBuffer) {
for (channel=0; channel<numChannels; channel++)
delete [] lookaheadBuffer[channel];
delete [] lookaheadBuffer;
}
delete gain;
gain = new TTSampleValue[maxBufferSize];
lookaheadBuffer = new TTSampleValuePtr[maxNumChannels];
for (channel=0; channel<maxNumChannels; channel++)
lookaheadBuffer[channel] = new TTSampleValue[maxBufferSize];
Clear();
dcBlocker->setAttributeValue(TT("MaxNumChannels"), maxNumChannels);
preamp->setAttributeValue(TT("MaxNumChannels"), maxNumChannels);
return kTTErrNone;
}
TTErr TTLimiter::updateSr()
{
setRecover();
return kTTErrNone;
}
TTErr TTLimiter::setPreamp(const TTValue& newValue)
{
return preamp->setAttributeValue(TT("Gain"), const_cast<TTValue&>(newValue));
}
TTErr TTLimiter::getPreamp(TTValue& value)
{
return preamp->getAttributeValue(TT("Gain"), value);
}
TTErr TTLimiter::setPostamp(const TTValue& newValue)
{
attrPostamp = dbToLinear(newValue);
return kTTErrNone;
}
TTErr TTLimiter::getPostamp(TTValue& value)
{
value = linearToDb(attrPostamp);
return kTTErrNone;
}
TTErr TTLimiter::setThreshold(const TTValue& newValue)
{
attrThreshold = dbToLinear(newValue);
return kTTErrNone;
}
TTErr TTLimiter::getThreshold(TTValue& value)
{
value = linearToDb(attrThreshold);
return kTTErrNone;
}
TTErr TTLimiter::setLookahead(TTValue& newValue)
{
attrLookahead = TTClip(TTUInt32(newValue), TTUInt32(1), maxBufferSize-1);
lookaheadInv = 1.0 / TTFloat64(attrLookahead);
return kTTErrNone;
}
TTErr TTLimiter::setRelease(TTValue& newValue)
{
attrRelease = newValue;
setRecover();
return kTTErrNone;
}
TTErr TTLimiter::setMode(TTValue& newValue)
{
attrMode = newValue;
if (attrMode == TT("linear"))
isLinear = true;
else
isLinear = false;
setRecover();
return kTTErrNone;
}
TTErr TTLimiter::setDCBlocker(TTValue& newValue)
{
attrDCBlocker = newValue;
return dcBlocker->setAttributeValue(TT("Bypass"), !attrDCBlocker);
}
TTErr TTLimiter::Clear()
{
TTUInt32 i;
TTUInt32 channel;
for (i=0; i<maxBufferSize; i++) {
for (channel=0; channel < maxNumChannels; channel++)
lookaheadBuffer[channel][i] = 0.0;
gain[i] = 1.0; // gain is shared across channels
}
lookaheadBufferIndex = 0; // was bp
last = 1.0;
setRecover();
dcBlocker->sendMessage(TT("Clear"));
return kTTErrNone;
}
// set variables related to the time it takes for the limiter to recover from a peak in the audio
// it is based on the release time attr, which is specified in seconds
void TTLimiter::setRecover()
{
recover = 1000.0 / (attrRelease * sr);
if (attrMode == TT("linear"))
recover = recover * 0.5;
else
recover = recover * 0.707;
}
TTErr TTLimiter::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
TTAudioSignal& in = inputs->getSignal(0);
TTAudioSignal& out = outputs->getSignal(0);
TTUInt16 vs = in.getVectorSizeAsInt();
TTUInt16 i, j;
TTSampleValue tempSample;
TTSampleValue hotSample;
TTFloat64 maybe,
curgain,
newgain,
inc,
acc;
TTInt16 flag,
lookaheadBufferPlayback,
ind;
TTUInt16 numchannels = TTAudioSignal::getMinChannelCount(in, out);
TTUInt16 channel;
// Pre-Process the input
dcBlocker->process(in, out); // filter out DC-Offsets (unless it is bypassed)
preamp->process(out, in); // copy output back to input for the rest of this process
for (i=0; i<vs; i++) {
hotSample = 0.0;
// Analysis Stage ...
for (channel=0; channel<numchannels; channel++) {
tempSample = in.mSampleVectors[channel][i];
lookaheadBuffer[channel][lookaheadBufferIndex] = tempSample * attrPostamp;
tempSample = fabs(tempSample);
if (tempSample > hotSample)
hotSample = tempSample;
}
if (isLinear)
tempSample = last + recover;
else {
if (last > 0.01)
tempSample = last + recover * last;
else
tempSample = last + recover;
}
if (tempSample > attrThreshold)
maybe = attrThreshold;
else
maybe = tempSample;
gain[lookaheadBufferIndex] = maybe;
lookaheadBufferPlayback = lookaheadBufferIndex - attrLookahead;
if (lookaheadBufferPlayback < 0)
lookaheadBufferPlayback += attrLookahead;
// Process Stage ...
// this ***very slow*** : with a lookahead of 100, and vs = 64, we loop 640 times!
if (hotSample * maybe > attrThreshold) {
curgain = attrThreshold / hotSample;
inc = (attrThreshold - curgain);
acc = 0;
flag = 0;
for (j=0; flag==0 && j<attrLookahead; j++) {
ind = lookaheadBufferIndex - j;
if (ind<0)
ind += maxBufferSize;
if (isLinear) //TODO: can't we move this condition outside the loop? isLinear won't change during a vs [NP]
newgain = curgain + inc * acc;
else
newgain = curgain + inc * (acc * acc);
if (newgain < gain[ind])
gain[ind] = newgain;
else
flag = 1;
acc = acc + lookaheadInv;
}
}
// Actual application of the gain
for (channel=0; channel<numchannels; channel++) {
out.mSampleVectors[channel][i] = lookaheadBuffer[channel][lookaheadBufferPlayback] * gain[lookaheadBufferPlayback];
}
last = gain[lookaheadBufferIndex];
lookaheadBufferIndex++;
if (lookaheadBufferIndex >= attrLookahead)
lookaheadBufferIndex = 0;
}
return kTTErrNone;
}
<|endoftext|> |
<commit_before>/**
* \file SD1OverdriveFilter.cpp
*/
#include "SD1OverdriveFilter.h"
#include <boost/math/special_functions/sign.hpp>
#include "../Tools/exp.h"
#include "../Tools/ScalarNewtonRaphson.h"
namespace ATK
{
template<typename DataType_>
class SD1OverdriveFunction
{
public:
typedef DataType_ DataType;
protected:
DataType A;
DataType B;
DataType R1;
DataType Q;
DataType drive;
DataType is;
DataType vt;
DataType oldy0;
DataType oldexpy0;
DataType oldinvexpy0;
DataType oldy1;
DataType oldexpy1;
DataType oldinvexpy1;
Exp<DataType> exp;
public:
SD1OverdriveFunction(DataType dt, DataType R, DataType C, DataType R1, DataType Q, DataType is, DataType vt)
:R1(R1), Q(Q), drive(0.5), is(is), vt(vt), exp(32, 1024*1024)
{
A = dt / (2 * C) + R;
B = dt / (2 * C) - R;
oldy0 = oldy1 = 0;
oldexpy0 = oldinvexpy0 = oldexpy1 = oldinvexpy1 = 1;
}
void set_drive(DataType drive)
{
this->drive = (R1 + drive * Q);
}
std::pair<DataType, DataType> operator()(DataType x0, DataType x1, DataType y0, DataType y1)
{
y0 -= x0;
y1 -= x1;
DataType expdiode_y1_p = exp(y1 / vt);
DataType expdiode_y1_m = 1 / expdiode_y1_p;
DataType expdiode_y0_p;
DataType expdiode_y0_m;
if(y0 == oldy0)
{
expdiode_y0_p = oldexpy0;
expdiode_y0_m = oldinvexpy0;
}
else if(y0 == oldy1)
{
expdiode_y0_p = oldexpy1;
expdiode_y0_m = oldinvexpy1;
}
else
{
expdiode_y0_p = exp(y0 / vt);
expdiode_y0_m = 1 / expdiode_y0_p;
}
oldy0 = y0;
oldexpy0 = expdiode_y0_p;
oldinvexpy0 = expdiode_y0_m;
oldy1 = y1;
oldexpy1 = expdiode_y1_p;
oldinvexpy1 = expdiode_y1_m;
std::pair<DataType, DataType> diode1 = std::make_pair(is * (expdiode_y1_p - 2 * expdiode_y1_m + 1), is * (expdiode_y1_p + 2 * expdiode_y1_m) / vt);
DataType diode0 = is * (expdiode_y0_p - 2 * expdiode_y0_m + 1);
return std::make_pair(x0 - x1 + y1 * (A / drive) + y0 * (B / drive) + A * diode1.first + B * diode0, (A / drive) + A * diode1.second);
}
};
template <typename DataType>
SD1OverdriveFilter<DataType>::SD1OverdriveFilter(int nb_channels)
:TypedBaseFilter<DataType>(nb_channels, nb_channels)
{
optimizer.reset(new ScalarNewtonRaphson<SD1OverdriveFunction<DataType> >(function));
}
template <typename DataType>
SD1OverdriveFilter<DataType>::~SD1OverdriveFilter()
{
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::setup()
{
Parent::setup();
function.reset(new SD1OverdriveFunction<DataType>(1./input_sampling_rate, 100e3, 0.047e-6, 33e3, 1e6, 1e-12, 26e-3));
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::set_drive(DataType drive)
{
function->set_drive(drive);
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::process_impl(std::int64_t size)
{
assert(nb_input_ports == nb_output_ports);
for(int channel = 0; channel < nb_input_ports; ++channel)
{
for(std::int64_t i = 0; i < size; ++i)
{
outputs[channel][i] = optimizer->optimize(converted_inputs[channel][i]);
}
}
}
template class SD1OverdriveFilter<float>;
template class SD1OverdriveFilter<double>;
}
<commit_msg>Fixing issue with forgetting drive value<commit_after>/**
* \file SD1OverdriveFilter.cpp
*/
#include "SD1OverdriveFilter.h"
#include <boost/math/special_functions/sign.hpp>
#include "../Tools/exp.h"
#include "../Tools/ScalarNewtonRaphson.h"
namespace ATK
{
template<typename DataType_>
class SD1OverdriveFunction
{
public:
typedef DataType_ DataType;
protected:
DataType A;
DataType B;
DataType R1;
DataType Q;
DataType drive;
DataType is;
DataType vt;
DataType oldy0;
DataType oldexpy0;
DataType oldinvexpy0;
DataType oldy1;
DataType oldexpy1;
DataType oldinvexpy1;
Exp<DataType> exp;
public:
SD1OverdriveFunction(DataType dt, DataType R, DataType C, DataType R1, DataType Q, DataType is, DataType vt)
:R1(R1), Q(Q), drive(0.5), is(is), vt(vt), exp(32, 1024*1024)
{
A = dt / (2 * C) + R;
B = dt / (2 * C) - R;
oldy0 = oldy1 = 0;
oldexpy0 = oldinvexpy0 = oldexpy1 = oldinvexpy1 = 1;
}
void set_drive(DataType drive)
{
this->drive = (R1 + drive * Q);
}
std::pair<DataType, DataType> operator()(DataType x0, DataType x1, DataType y0, DataType y1)
{
y0 -= x0;
y1 -= x1;
DataType expdiode_y1_p = exp(y1 / vt);
DataType expdiode_y1_m = 1 / expdiode_y1_p;
DataType expdiode_y0_p;
DataType expdiode_y0_m;
if(y0 == oldy0)
{
expdiode_y0_p = oldexpy0;
expdiode_y0_m = oldinvexpy0;
}
else if(y0 == oldy1)
{
expdiode_y0_p = oldexpy1;
expdiode_y0_m = oldinvexpy1;
}
else
{
expdiode_y0_p = exp(y0 / vt);
expdiode_y0_m = 1 / expdiode_y0_p;
}
oldy0 = y0;
oldexpy0 = expdiode_y0_p;
oldinvexpy0 = expdiode_y0_m;
oldy1 = y1;
oldexpy1 = expdiode_y1_p;
oldinvexpy1 = expdiode_y1_m;
std::pair<DataType, DataType> diode1 = std::make_pair(is * (expdiode_y1_p - 2 * expdiode_y1_m + 1), is * (expdiode_y1_p + 2 * expdiode_y1_m) / vt);
DataType diode0 = is * (expdiode_y0_p - 2 * expdiode_y0_m + 1);
return std::make_pair(x0 - x1 + y1 * (A / drive) + y0 * (B / drive) + A * diode1.first + B * diode0, (A / drive) + A * diode1.second);
}
};
template <typename DataType>
SD1OverdriveFilter<DataType>::SD1OverdriveFilter(int nb_channels)
:TypedBaseFilter<DataType>(nb_channels, nb_channels)
{
optimizer.reset(new ScalarNewtonRaphson<SD1OverdriveFunction<DataType> >(function));
}
template <typename DataType>
SD1OverdriveFilter<DataType>::~SD1OverdriveFilter()
{
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::setup()
{
Parent::setup();
function.reset(new SD1OverdriveFunction<DataType>(1./input_sampling_rate, 100e3, 0.047e-6, 33e3, 1e6, 1e-12, 26e-3));
function->set_drive(drive);
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::set_drive(DataType drive)
{
function->set_drive(drive);
}
template <typename DataType>
void SD1OverdriveFilter<DataType>::process_impl(std::int64_t size)
{
assert(nb_input_ports == nb_output_ports);
for(int channel = 0; channel < nb_input_ports; ++channel)
{
for(std::int64_t i = 0; i < size; ++i)
{
outputs[channel][i] = optimizer->optimize(converted_inputs[channel][i]);
}
}
}
template class SD1OverdriveFilter<float>;
template class SD1OverdriveFilter<double>;
}
<|endoftext|> |
<commit_before>#include "ui_calcbmi.h"
CalcBMI::CalcBMI(QWidget *parent) :
QDialog(parent),
ui(new Ui::CalcBMI)
{
ui->setupUi(this);
}
CalcBMI::~CalcBMI()
{
delete ui;
}
void CalcBMI::UpdateMethod()
{
}
void CalcBMI::on_closeButton_clicked()
{
CloseWindow(this);
}
<commit_msg>fixed build<commit_after>#include "ui_calcbmi.h"
#include "calcbmi.h"
CalcBMI::CalcBMI(QWidget *parent) :
QDialog(parent),
ui(new Ui::CalcBMI)
{
ui->setupUi(this);
}
CalcBMI::~CalcBMI()
{
delete ui;
}
void CalcBMI::UpdateMethod()
{
}
void CalcBMI::on_closeButton_clicked()
{
CloseWindow(this);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_MESH_OPERATORS
#define MFEM_MESH_OPERATORS
#include "../config/config.hpp"
#include "../general/array.hpp"
#include "mesh.hpp"
#include "../fem/estimators.hpp"
#include <limits>
namespace mfem
{
/** @brief The MeshOperator class serves as base for mesh manipulation classes.
The purpose of the class is to provide a common abstraction for various
AMR mesh control schemes. The typical use in an AMR loop is illustrated
in examples 6/6p and 15/15p.
A more general loop that also supports sequences of mesh operators with
multiple updates looks like this:
\code
for (...)
{
// computations on the current mesh ...
while (mesh_operator->Apply(mesh))
{
// update FiniteElementSpaces and interpolate GridFunctions ...
if (mesh_operator->Continue()) { break; }
}
if (mesh_operator->Stop()) { break; }
}
\endcode
*/
class MeshOperator
{
private:
int mod;
protected:
friend class MeshOperatorSequence;
/** @brief Implementation of the mesh operation. Invoked by the Apply()
public method.
@return Combination of ActionInfo constants. */
virtual int ApplyImpl(Mesh &mesh) = 0;
/// Constructor to be used by derived classes.
MeshOperator() : mod(NONE) { }
public:
/** @brief Action and information constants and masks.
Combinations of constants are returned by the Apply() virtual method and
can be accessed directly with GetActionInfo() or indirectly with methods
like Stop(), Continue(), etc. The information bits (MASK_INFO) can be set
only when the update bit is set (see MASK_UPDATE). */
enum Action
{
NONE = 0, /**< continue with computations without updating spaces
or grid-functions, i.e. the mesh was not modified */
CONTINUE = 1, /**< update spaces and grid-functions and continue
computations with the new mesh */
STOP = 2, ///< a stopping criterion was satisfied
REPEAT = 3, /**< update spaces and grid-functions and call the
operator Apply() method again */
MASK_UPDATE = 1, ///< bit mask for the "update" bit
MASK_ACTION = 3 ///< bit mask for all "action" bits
};
enum Info
{
REFINED = 4*1, ///< the mesh was refined
DEREFINED = 4*2, ///< the mesh was de-refined
REBALANCED = 4*3, ///< the mesh was rebalanced
MASK_INFO = ~3 ///< bit mask for all "info" bits
};
/** @brief Perform the mesh operation.
@return true if FiniteElementSpaces and GridFunctions need to be updated.
*/
bool Apply(Mesh &mesh) { return ((mod = ApplyImpl(mesh)) & MASK_UPDATE); }
/** @brief Check if STOP action is requested, e.g. stopping criterion is
satisfied. */
bool Stop() const { return ((mod & MASK_ACTION) == STOP); }
/** @brief Check if REPEAT action is requested, i.e. FiniteElementSpaces and
GridFunctions need to be updated, and Apply() must be called again. */
bool Repeat() const { return ((mod & MASK_ACTION) == REPEAT); }
/** @brief Check if CONTINUE action is requested, i.e. FiniteElementSpaces
and GridFunctions need to be updated and computations should continue. */
bool Continue() const { return ((mod & MASK_ACTION) == CONTINUE); }
/// Check if the mesh was refined.
bool Refined() const { return ((mod & MASK_INFO) == REFINED); }
/// Check if the mesh was de-refined.
bool Derefined() const { return ((mod & MASK_INFO) == DEREFINED); }
/// Check if the mesh was rebalanced.
bool Rebalanced() const { return ((mod & MASK_INFO) == REBALANCED); }
/** @brief Get the full ActionInfo value generated by the last call to
Apply(). */
int GetActionInfo() const { return mod; }
/// Reset the MeshOperator.
virtual void Reset() = 0;
/// The destructor is virtual.
virtual ~MeshOperator() { }
};
/** Composition of MeshOperators into a sequence. Use the Append() method to
create the sequence. */
class MeshOperatorSequence : public MeshOperator
{
protected:
int step;
Array<MeshOperator*> sequence; ///< MeshOperators sequence, owned by us.
/// Do not allow copy construction, due to assumed ownership.
MeshOperatorSequence(const MeshOperatorSequence &) { }
/** @brief Apply the MeshOperatorSequence.
@return ActionInfo value corresponding to the last applied operator from
the sequence. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Constructor. Use the Append() method to create the sequence.
MeshOperatorSequence() : step(-1) { }
/// Delete all operators from the sequence.
virtual ~MeshOperatorSequence();
/** @brief Add an operator to the end of the sequence.
The MeshOperatorSequence assumes ownership of the operator. */
void Append(MeshOperator *mc) { sequence.Append(mc); }
/// Access the underlying sequence.
Array<MeshOperator*> &GetSequence() { return sequence; }
/// Reset all MeshOperators in the sequence.
virtual void Reset();
};
/** @brief Mesh refinement operator using an error threshold.
This class uses the given ErrorEstimator to estimate local element errors
and then marks for refinement all elements i such that loc_err_i > threshold.
The threshold is computed as
\code
threshold = max(total_err * total_fraction * pow(num_elements,-1.0/p),
local_err_goal);
\endcode
where p (=total_norm_p), total_fraction, and local_err_goal are settable
parameters, total_err = (sum_i local_err_i^p)^{1/p}, when p < inf,
or total_err = max_i local_err_i, when p = inf.
*/
class ThresholdRefiner : public MeshOperator
{
protected:
ErrorEstimator &estimator;
AnisotropicErrorEstimator *aniso_estimator;
double total_norm_p;
double total_err_goal;
double total_fraction;
double local_err_goal;
long max_elements;
double threshold;
long num_marked_elements;
Array<Refinement> marked_elements;
long current_sequence;
int non_conforming;
int nc_limit;
double GetNorm(const Vector &local_err, Mesh &mesh) const;
/** @brief Apply the operator to the mesh.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Construct a ThresholdRefiner using the given ErrorEstimator.
ThresholdRefiner(ErrorEstimator &est);
// default destructor (virtual)
/** @brief Set the exponent, p, of the discrete p-norm used to compute the
total error from the local element errors. */
void SetTotalErrorNormP(double norm_p = infinity())
{ total_norm_p = norm_p; }
/** @brief Set the total error stopping criterion: stop when
total_err <= total_err_goal. The default value is zero. */
void SetTotalErrorGoal(double err_goal) { total_err_goal = err_goal; }
/** @brief Set the total fraction used in the computation of the threshold.
The default value is 1/2.
@note If fraction == 0, total_err is essentially ignored in the threshold
computation, i.e. threshold = local error goal. */
void SetTotalErrorFraction(double fraction) { total_fraction = fraction; }
/** @brief Set the local stopping criterion: stop when
local_err_i <= local_err_goal. The default value is zero.
@note If local_err_goal == 0, it is essentially ignored in the threshold
computation. */
void SetLocalErrorGoal(double err_goal) { local_err_goal = err_goal; }
/** @brief Set the maximum number of elements stopping criterion: stop when
the input mesh has num_elements >= max_elem. The default value is
LONG_MAX. */
void SetMaxElements(long max_elem) { max_elements = max_elem; }
/// Use nonconforming refinement, if possible (triangles, quads, hexes).
void PreferNonconformingRefinement() { non_conforming = 1; }
/** @brief Use conforming refinement, if possible (triangles, tetrahedra)
-- this is the default. */
void PreferConformingRefinement() { non_conforming = -1; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). */
void SetNCLimit(int nc_limit)
{
MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit");
this->nc_limit = nc_limit;
}
/// Get the number of marked elements in the last Apply() call.
long GetNumMarkedElements() const { return num_marked_elements; }
/// Get the threshold used in the last Apply() call.
double GetThreshold() const { return threshold; }
/// Reset the associated estimator.
virtual void Reset();
};
// TODO: BulkRefiner to refine a portion of the global error
/** @brief De-refinement operator using an error threshold.
This de-refinement operator marks elements in the hierarchy whose children
are leaves and their combined error is below a given threshold. The
errors of the children are combined by one of the following operations:
- op = 0: minimum of the errors
- op = 1: sum of the errors (default)
- op = 2: maximum of the errors. */
class ThresholdDerefiner : public MeshOperator
{
protected:
ErrorEstimator &estimator;
double threshold;
int nc_limit, op;
/** @brief Apply the operator to the mesh.
@return DEREFINED + CONTINUE if some elements were de-refined; NONE
otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Construct a ThresholdDerefiner using the given ErrorEstimator.
ThresholdDerefiner(ErrorEstimator &est)
: estimator(est)
{
threshold = 0.0;
nc_limit = 0;
op = 1;
}
// default destructor (virtual)
/// Set the de-refinement threshold. The default value is zero.
void SetThreshold(double thresh) { threshold = thresh; }
void SetOp(int op) { this->op = op; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). */
void SetNCLimit(int nc_limit)
{
MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit");
this->nc_limit = nc_limit;
}
/// Reset the associated estimator.
virtual void Reset() { estimator.Reset(); }
};
/** @brief Refinement operator to control data oscillation.
This class computes osc_K(f) := || h ⋅ (I - Π) f ||_K at each element K.
Here, Π is the L2-projection and ||⋅||_K is the L2-norm, restricted to the
element K. All elements satisfying the inequality
\code
osc_K(f) > threshold ⋅ ||f|| / sqrt(n_el),
\endcode
are refined. Here, threshold is a postive parameter, ||⋅|| is the L2-norm
over the entire domain Ω, and n_el is the number of elements in the mesh.
Note that if osc(f) = threshold ⋅ ||f|| / sqrt(n_el) for each K, then
\code
osc(f) = sqrt( sum_K osc_K^2(f)) = threshold ⋅ ||f||.
\endcode
This is the reason for the 1/sqrt(n_el) factor. */
class CoefficientRefiner : public MeshOperator
{
protected:
int nc_limit = 1;
int nonconforming = -1;
int order;
long max_elements = std::numeric_limits<long>::max();
double threshold = 1.0e-2;
double global_osc = 0.0;
Array<int> mesh_refinements;
Vector element_oscs;
Coefficient *coeff = NULL;
GridFunction *gf;
const IntegrationRule *ir_default[Geometry::NumGeom];
const IntegrationRule **irs = NULL;
/** @brief Apply the operator to the mesh once.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Constructor
CoefficientRefiner(int order_) : order(order_) { }
/** @brief Apply the operator to the mesh max_it times or until tolerance
* achieved.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int PreprocessMesh(Mesh &mesh, int max_it);
int PreprocessMesh(Mesh &mesh)
{
int max_it = 10;
return PreprocessMesh(mesh, max_it);
}
/// Set the refinement threshold. The default value is 1.0e-2.
void SetThreshold(double threshold_) { threshold = threshold_; }
/** @brief Set the maximum number of elements stopping criterion: stop when
the input mesh has num_elements >= max_elem. The default value is
LONG_MAX. */
void SetMaxElements(long max_elements_) { max_elements = max_elements_; }
/// Set the function f
void SetCoefficient(Coefficient &coeff_)
{
element_oscs.Destroy();
global_osc = 0.0;
coeff = &coeff_;
}
/// Reset the oscillation order
void SetOrder(double order_) { order = order_; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). The default value is 1, which helps ensure appropriate
refinements in pathological situations where the default quadrature
order is too low. */
void SetNCLimit(int nc_limit_)
{
MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
nc_limit = nc_limit_;
}
// Set a custom integration rule
void SetIntRule(const IntegrationRule *irs_[]) { irs = irs_; }
// Return the value of the global relative data oscillation
const double GetOsc() { return global_osc; }
// Return the local relative data oscillation errors
const Vector & GetLocalOscs() const
{
MFEM_ASSERT(element_oscs.Size() > 0,
"Local oscillations have not been computed yet")
return element_oscs;
}
/// Reset
virtual void Reset();
};
/** @brief ParMesh rebalancing operator.
If the mesh is a parallel mesh, perform rebalancing; otherwise, do nothing.
*/
class Rebalancer : public MeshOperator
{
protected:
/** @brief Rebalance a parallel mesh (only non-conforming parallel meshes are
supported).
@return CONTINUE + REBALANCE on success, NONE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Empty.
virtual void Reset() { }
};
} // namespace mfem
#endif // MFEM_MESH_OPERATORS
<commit_msg>initialize gf<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_MESH_OPERATORS
#define MFEM_MESH_OPERATORS
#include "../config/config.hpp"
#include "../general/array.hpp"
#include "mesh.hpp"
#include "../fem/estimators.hpp"
#include <limits>
namespace mfem
{
/** @brief The MeshOperator class serves as base for mesh manipulation classes.
The purpose of the class is to provide a common abstraction for various
AMR mesh control schemes. The typical use in an AMR loop is illustrated
in examples 6/6p and 15/15p.
A more general loop that also supports sequences of mesh operators with
multiple updates looks like this:
\code
for (...)
{
// computations on the current mesh ...
while (mesh_operator->Apply(mesh))
{
// update FiniteElementSpaces and interpolate GridFunctions ...
if (mesh_operator->Continue()) { break; }
}
if (mesh_operator->Stop()) { break; }
}
\endcode
*/
class MeshOperator
{
private:
int mod;
protected:
friend class MeshOperatorSequence;
/** @brief Implementation of the mesh operation. Invoked by the Apply()
public method.
@return Combination of ActionInfo constants. */
virtual int ApplyImpl(Mesh &mesh) = 0;
/// Constructor to be used by derived classes.
MeshOperator() : mod(NONE) { }
public:
/** @brief Action and information constants and masks.
Combinations of constants are returned by the Apply() virtual method and
can be accessed directly with GetActionInfo() or indirectly with methods
like Stop(), Continue(), etc. The information bits (MASK_INFO) can be set
only when the update bit is set (see MASK_UPDATE). */
enum Action
{
NONE = 0, /**< continue with computations without updating spaces
or grid-functions, i.e. the mesh was not modified */
CONTINUE = 1, /**< update spaces and grid-functions and continue
computations with the new mesh */
STOP = 2, ///< a stopping criterion was satisfied
REPEAT = 3, /**< update spaces and grid-functions and call the
operator Apply() method again */
MASK_UPDATE = 1, ///< bit mask for the "update" bit
MASK_ACTION = 3 ///< bit mask for all "action" bits
};
enum Info
{
REFINED = 4*1, ///< the mesh was refined
DEREFINED = 4*2, ///< the mesh was de-refined
REBALANCED = 4*3, ///< the mesh was rebalanced
MASK_INFO = ~3 ///< bit mask for all "info" bits
};
/** @brief Perform the mesh operation.
@return true if FiniteElementSpaces and GridFunctions need to be updated.
*/
bool Apply(Mesh &mesh) { return ((mod = ApplyImpl(mesh)) & MASK_UPDATE); }
/** @brief Check if STOP action is requested, e.g. stopping criterion is
satisfied. */
bool Stop() const { return ((mod & MASK_ACTION) == STOP); }
/** @brief Check if REPEAT action is requested, i.e. FiniteElementSpaces and
GridFunctions need to be updated, and Apply() must be called again. */
bool Repeat() const { return ((mod & MASK_ACTION) == REPEAT); }
/** @brief Check if CONTINUE action is requested, i.e. FiniteElementSpaces
and GridFunctions need to be updated and computations should continue. */
bool Continue() const { return ((mod & MASK_ACTION) == CONTINUE); }
/// Check if the mesh was refined.
bool Refined() const { return ((mod & MASK_INFO) == REFINED); }
/// Check if the mesh was de-refined.
bool Derefined() const { return ((mod & MASK_INFO) == DEREFINED); }
/// Check if the mesh was rebalanced.
bool Rebalanced() const { return ((mod & MASK_INFO) == REBALANCED); }
/** @brief Get the full ActionInfo value generated by the last call to
Apply(). */
int GetActionInfo() const { return mod; }
/// Reset the MeshOperator.
virtual void Reset() = 0;
/// The destructor is virtual.
virtual ~MeshOperator() { }
};
/** Composition of MeshOperators into a sequence. Use the Append() method to
create the sequence. */
class MeshOperatorSequence : public MeshOperator
{
protected:
int step;
Array<MeshOperator*> sequence; ///< MeshOperators sequence, owned by us.
/// Do not allow copy construction, due to assumed ownership.
MeshOperatorSequence(const MeshOperatorSequence &) { }
/** @brief Apply the MeshOperatorSequence.
@return ActionInfo value corresponding to the last applied operator from
the sequence. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Constructor. Use the Append() method to create the sequence.
MeshOperatorSequence() : step(-1) { }
/// Delete all operators from the sequence.
virtual ~MeshOperatorSequence();
/** @brief Add an operator to the end of the sequence.
The MeshOperatorSequence assumes ownership of the operator. */
void Append(MeshOperator *mc) { sequence.Append(mc); }
/// Access the underlying sequence.
Array<MeshOperator*> &GetSequence() { return sequence; }
/// Reset all MeshOperators in the sequence.
virtual void Reset();
};
/** @brief Mesh refinement operator using an error threshold.
This class uses the given ErrorEstimator to estimate local element errors
and then marks for refinement all elements i such that loc_err_i > threshold.
The threshold is computed as
\code
threshold = max(total_err * total_fraction * pow(num_elements,-1.0/p),
local_err_goal);
\endcode
where p (=total_norm_p), total_fraction, and local_err_goal are settable
parameters, total_err = (sum_i local_err_i^p)^{1/p}, when p < inf,
or total_err = max_i local_err_i, when p = inf.
*/
class ThresholdRefiner : public MeshOperator
{
protected:
ErrorEstimator &estimator;
AnisotropicErrorEstimator *aniso_estimator;
double total_norm_p;
double total_err_goal;
double total_fraction;
double local_err_goal;
long max_elements;
double threshold;
long num_marked_elements;
Array<Refinement> marked_elements;
long current_sequence;
int non_conforming;
int nc_limit;
double GetNorm(const Vector &local_err, Mesh &mesh) const;
/** @brief Apply the operator to the mesh.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Construct a ThresholdRefiner using the given ErrorEstimator.
ThresholdRefiner(ErrorEstimator &est);
// default destructor (virtual)
/** @brief Set the exponent, p, of the discrete p-norm used to compute the
total error from the local element errors. */
void SetTotalErrorNormP(double norm_p = infinity())
{ total_norm_p = norm_p; }
/** @brief Set the total error stopping criterion: stop when
total_err <= total_err_goal. The default value is zero. */
void SetTotalErrorGoal(double err_goal) { total_err_goal = err_goal; }
/** @brief Set the total fraction used in the computation of the threshold.
The default value is 1/2.
@note If fraction == 0, total_err is essentially ignored in the threshold
computation, i.e. threshold = local error goal. */
void SetTotalErrorFraction(double fraction) { total_fraction = fraction; }
/** @brief Set the local stopping criterion: stop when
local_err_i <= local_err_goal. The default value is zero.
@note If local_err_goal == 0, it is essentially ignored in the threshold
computation. */
void SetLocalErrorGoal(double err_goal) { local_err_goal = err_goal; }
/** @brief Set the maximum number of elements stopping criterion: stop when
the input mesh has num_elements >= max_elem. The default value is
LONG_MAX. */
void SetMaxElements(long max_elem) { max_elements = max_elem; }
/// Use nonconforming refinement, if possible (triangles, quads, hexes).
void PreferNonconformingRefinement() { non_conforming = 1; }
/** @brief Use conforming refinement, if possible (triangles, tetrahedra)
-- this is the default. */
void PreferConformingRefinement() { non_conforming = -1; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). */
void SetNCLimit(int nc_limit)
{
MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit");
this->nc_limit = nc_limit;
}
/// Get the number of marked elements in the last Apply() call.
long GetNumMarkedElements() const { return num_marked_elements; }
/// Get the threshold used in the last Apply() call.
double GetThreshold() const { return threshold; }
/// Reset the associated estimator.
virtual void Reset();
};
// TODO: BulkRefiner to refine a portion of the global error
/** @brief De-refinement operator using an error threshold.
This de-refinement operator marks elements in the hierarchy whose children
are leaves and their combined error is below a given threshold. The
errors of the children are combined by one of the following operations:
- op = 0: minimum of the errors
- op = 1: sum of the errors (default)
- op = 2: maximum of the errors. */
class ThresholdDerefiner : public MeshOperator
{
protected:
ErrorEstimator &estimator;
double threshold;
int nc_limit, op;
/** @brief Apply the operator to the mesh.
@return DEREFINED + CONTINUE if some elements were de-refined; NONE
otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Construct a ThresholdDerefiner using the given ErrorEstimator.
ThresholdDerefiner(ErrorEstimator &est)
: estimator(est)
{
threshold = 0.0;
nc_limit = 0;
op = 1;
}
// default destructor (virtual)
/// Set the de-refinement threshold. The default value is zero.
void SetThreshold(double thresh) { threshold = thresh; }
void SetOp(int op) { this->op = op; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). */
void SetNCLimit(int nc_limit)
{
MFEM_ASSERT(nc_limit >= 0, "Invalid NC limit");
this->nc_limit = nc_limit;
}
/// Reset the associated estimator.
virtual void Reset() { estimator.Reset(); }
};
/** @brief Refinement operator to control data oscillation.
This class computes osc_K(f) := || h ⋅ (I - Π) f ||_K at each element K.
Here, Π is the L2-projection and ||⋅||_K is the L2-norm, restricted to the
element K. All elements satisfying the inequality
\code
osc_K(f) > threshold ⋅ ||f|| / sqrt(n_el),
\endcode
are refined. Here, threshold is a postive parameter, ||⋅|| is the L2-norm
over the entire domain Ω, and n_el is the number of elements in the mesh.
Note that if osc(f) = threshold ⋅ ||f|| / sqrt(n_el) for each K, then
\code
osc(f) = sqrt( sum_K osc_K^2(f)) = threshold ⋅ ||f||.
\endcode
This is the reason for the 1/sqrt(n_el) factor. */
class CoefficientRefiner : public MeshOperator
{
protected:
int nc_limit = 1;
int nonconforming = -1;
int order;
long max_elements = std::numeric_limits<long>::max();
double threshold = 1.0e-2;
double global_osc = 0.0;
Array<int> mesh_refinements;
Vector element_oscs;
Coefficient *coeff = NULL;
GridFunction *gf = NULL;
const IntegrationRule *ir_default[Geometry::NumGeom];
const IntegrationRule **irs = NULL;
/** @brief Apply the operator to the mesh once.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Constructor
CoefficientRefiner(int order_) : order(order_) { }
/** @brief Apply the operator to the mesh max_it times or until tolerance
* achieved.
@return STOP if a stopping criterion is satisfied or no elements were
marked for refinement; REFINED + CONTINUE otherwise. */
virtual int PreprocessMesh(Mesh &mesh, int max_it);
int PreprocessMesh(Mesh &mesh)
{
int max_it = 10;
return PreprocessMesh(mesh, max_it);
}
/// Set the refinement threshold. The default value is 1.0e-2.
void SetThreshold(double threshold_) { threshold = threshold_; }
/** @brief Set the maximum number of elements stopping criterion: stop when
the input mesh has num_elements >= max_elem. The default value is
LONG_MAX. */
void SetMaxElements(long max_elements_) { max_elements = max_elements_; }
/// Set the function f
void SetCoefficient(Coefficient &coeff_)
{
element_oscs.Destroy();
global_osc = 0.0;
coeff = &coeff_;
}
/// Reset the oscillation order
void SetOrder(double order_) { order = order_; }
/** @brief Set the maximum ratio of refinement levels of adjacent elements
(0 = unlimited). The default value is 1, which helps ensure appropriate
refinements in pathological situations where the default quadrature
order is too low. */
void SetNCLimit(int nc_limit_)
{
MFEM_ASSERT(nc_limit_ >= 0, "Invalid NC limit");
nc_limit = nc_limit_;
}
// Set a custom integration rule
void SetIntRule(const IntegrationRule *irs_[]) { irs = irs_; }
// Return the value of the global relative data oscillation
const double GetOsc() { return global_osc; }
// Return the local relative data oscillation errors
const Vector & GetLocalOscs() const
{
MFEM_ASSERT(element_oscs.Size() > 0,
"Local oscillations have not been computed yet")
return element_oscs;
}
/// Reset
virtual void Reset();
};
/** @brief ParMesh rebalancing operator.
If the mesh is a parallel mesh, perform rebalancing; otherwise, do nothing.
*/
class Rebalancer : public MeshOperator
{
protected:
/** @brief Rebalance a parallel mesh (only non-conforming parallel meshes are
supported).
@return CONTINUE + REBALANCE on success, NONE otherwise. */
virtual int ApplyImpl(Mesh &mesh);
public:
/// Empty.
virtual void Reset() { }
};
} // namespace mfem
#endif // MFEM_MESH_OPERATORS
<|endoftext|> |
<commit_before>#include "istream/istream_catch.hxx"
#include "istream/istream_string.hxx"
#include "istream/istream.hxx"
#include <glib.h>
#include <stdio.h>
#define EXPECTED_RESULT "foo"
static struct istream *
create_input(struct pool *pool)
{
return istream_string_new(pool, "foo");
}
static GError *
catch_callback(GError *error, gcc_unused void *ctx)
{
fprintf(stderr, "caught: %s\n", error->message);
g_error_free(error);
return nullptr;
}
static struct istream *
create_test(struct pool *pool, struct istream *input)
{
return istream_catch_new(pool, input, catch_callback, nullptr);
}
#define NO_AVAILABLE_CALL
#include "t_istream_filter.hxx"
<commit_msg>test/t_istream_catch: longer input string to trigger assertion failure<commit_after>#include "istream/istream_catch.hxx"
#include "istream/istream_string.hxx"
#include "istream/istream.hxx"
#include <glib.h>
#include <stdio.h>
/* an input string longer than the "space" buffer (128 bytes) to
trigger bugs due to truncated OnData() buffers */
#define EXPECTED_RESULT "long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long long"
static struct istream *
create_input(struct pool *pool)
{
return istream_string_new(pool, EXPECTED_RESULT);
}
static GError *
catch_callback(GError *error, gcc_unused void *ctx)
{
fprintf(stderr, "caught: %s\n", error->message);
g_error_free(error);
return nullptr;
}
static struct istream *
create_test(struct pool *pool, struct istream *input)
{
return istream_catch_new(pool, input, catch_callback, nullptr);
}
#define NO_AVAILABLE_CALL
#include "t_istream_filter.hxx"
<|endoftext|> |
<commit_before>#include "rasterizer.h"
#include "transform_controller.hpp"
#include "object_utilities.h"
using namespace rasterizer;
Application* app;
void MainLoop();
int main(int argc, char *argv[])
{
app = Application::GetInstance();
app->CreateApplication("plane", 800, 600);
app->SetRunLoop(MainLoop);
app->RunLoop();
return 0;
}
struct Vertex
{
Vector3 position;
Vector4 color;
Vector2 texCoord;
};
struct VaryingData
{
Vector4 position;
//Vector4 color;
Vector2 texCoord;
static std::vector<VaryingDataLayout> GetLayout()
{
static std::vector<VaryingDataLayout> layout = {
{ 0, VaryingDataDeclUsage_SVPOSITION, VaryingDataDeclFormat_Vector4 },
//{ 16, VaryingDataDeclUsage_COLOR, VaryingDataDeclFormat_Vector4 },
{ 16, VaryingDataDeclUsage_TEXCOORD, VaryingDataDeclFormat_Vector2 }
};
return layout;
}
};
struct PlaneShader : Shader<Vertex, VaryingData>
{
TexturePtr mainTex;
Vector2 ddx, ddy;
VaryingData vert(const Vertex& input) override
{
VaryingData output;
output.position = _MATRIX_MVP.MultiplyPoint(input.position);
output.texCoord = input.texCoord;
//output.color = input.color;
return output;
}
void passQuad(const Quad<VaryingData*>& quad) override
{
ddx = quad[1]->texCoord - quad[0]->texCoord;
ddy = quad[2]->texCoord - quad[0]->texCoord;
}
Color frag(const VaryingData& input) override
{
return Tex2D(mainTex, input.texCoord, ddx, ddy);
}
};
void MainLoop()
{
static bool isInitilized = false;
static Transform objectTrans;
static Transform cameraTrans;
static TransformController objectCtrl;
static std::vector<Vertex> vertices;
static std::vector<u16> indices;
static MaterialPtr material;
static PlaneShader shader;
Canvas* canvas = app->GetCanvas();
if (!isInitilized)
{
isInitilized = true;
Rasterizer::Initialize();
Rasterizer::canvas = canvas;
auto camera = CameraPtr(new Camera());
camera->SetPerspective(60.f, 1.33333f, 0.3f, 2000.f);
cameraTrans.position = Vector3(0.f, 0.f, 2.f);
camera->SetLookAt(cameraTrans);
Rasterizer::camera = camera;
material = MaterialPtr(new Material());
material->diffuseTexture = Texture::LoadTexture("resources/teapot/default.png");
material->diffuseTexture->GenerateMipmaps();
shader.mainTex = material->diffuseTexture;
shader.varyingDataDecl = VaryingData::GetLayout();
shader.varyingDataSize = sizeof(VaryingData);
assert(shader.varyingDataSize == 24);
MeshPtr mesh = CreatePlane();
vertices.clear();
indices.clear();
int vertexCount = mesh->GetVertexCount();
for (int i = 0; i < vertexCount; ++i)
{
vertices.emplace_back(Vertex{ mesh->vertices[i], mesh->colors[i], mesh->texcoords[i] });
}
for (auto idx : mesh->indices) indices.emplace_back((u16)idx);
}
canvas->Clear();
Rasterizer::PrepareRender();
objectCtrl.MouseRotate(objectTrans, false);
Rasterizer::transform = objectTrans.GetMatrix();
Rasterizer::renderData.AssignVertexBuffer(vertices);
Rasterizer::renderData.AssignIndexBuffer(indices);
Rasterizer::SetShader(&shader);
Rasterizer::Submit();
Rasterizer::Render();
canvas->Present();
}
<commit_msg>normal map<commit_after>#include "rasterizer.h"
#include "transform_controller.hpp"
#include "object_utilities.h"
using namespace rasterizer;
Application* app;
void MainLoop();
int main(int argc, char *argv[])
{
app = Application::GetInstance();
app->CreateApplication("plane", 800, 600);
app->SetRunLoop(MainLoop);
app->RunLoop();
return 0;
}
struct Vertex
{
Vector3 position;
Vector2 texCoord;
Vector3 normal;
Vector4 tangent;
};
struct VaryingData
{
Vector4 position;
Vector2 texCoord;
Vector3 normal;
Vector3 tangent;
Vector3 bitangent;
static std::vector<VaryingDataLayout> GetLayout()
{
static std::vector<VaryingDataLayout> layout = {
{ 0, VaryingDataDeclUsage_SVPOSITION, VaryingDataDeclFormat_Vector4 },
{ 16, VaryingDataDeclUsage_TEXCOORD, VaryingDataDeclFormat_Vector2 },
{ 24, VaryingDataDeclUsage_TEXCOORD, VaryingDataDeclFormat_Vector3 },
{ 36, VaryingDataDeclUsage_TEXCOORD, VaryingDataDeclFormat_Vector3 },
{ 48, VaryingDataDeclUsage_TEXCOORD, VaryingDataDeclFormat_Vector3 }
};
return layout;
}
};
struct PlaneShader : Shader<Vertex, VaryingData>
{
Vector3 lightDir = Vector3(1.f, 1.f, 1.f).Normalize();
TexturePtr mainTex;
TexturePtr normalTex;
Vector2 ddx, ddy;
VaryingData vert(const Vertex& input) override
{
VaryingData output;
output.position = _MATRIX_MVP.MultiplyPoint(input.position);
output.texCoord = input.texCoord;
output.normal = _Object2World.MultiplyVector(input.normal);
output.tangent = _Object2World.MultiplyVector(input.tangent.xyz);
output.bitangent = output.normal.Cross(output.tangent) * input.tangent.w;
return output;
}
void passQuad(const Quad<VaryingData*>& quad) override
{
ddx = quad[1]->texCoord - quad[0]->texCoord;
ddy = quad[2]->texCoord - quad[0]->texCoord;
}
Color frag(const VaryingData& input) override
{
Color color = Tex2D(mainTex, input.texCoord, ddx, ddy);
Matrix4x4 tbn = GetTangentSpace(input.tangent, input.bitangent, input.normal);
Vector3 normal = UnpackNormal(Tex2D(normalTex, input.texCoord, ddx, ddy), tbn);
color.rgb *= Mathf::Max(0.f, lightDir.Dot(normal));
return color;
}
};
void MainLoop()
{
static bool isInitilized = false;
static Transform objectTrans;
static Transform cameraTrans;
static TransformController objectCtrl;
static std::vector<Vertex> vertices;
static std::vector<u16> indices;
static MaterialPtr material;
static PlaneShader shader;
Canvas* canvas = app->GetCanvas();
if (!isInitilized)
{
isInitilized = true;
Rasterizer::Initialize();
Rasterizer::canvas = canvas;
auto camera = CameraPtr(new Camera());
camera->SetPerspective(60.f, 1.33333f, 0.3f, 2000.f);
cameraTrans.position = Vector3(0.f, 0.f, 2.f);
camera->SetLookAt(cameraTrans);
Rasterizer::camera = camera;
material = MaterialPtr(new Material());
material->diffuseTexture = Texture::LoadTexture("resources/teapot/default.png");
material->diffuseTexture->GenerateMipmaps();
material->normalTexture = Texture::LoadTexture("resources/crytek-sponza/textures/background_bump.png");
material->normalTexture->ConvertBumpToNormal();
shader.mainTex = material->diffuseTexture;
shader.normalTex = material->normalTexture;
shader.varyingDataDecl = VaryingData::GetLayout();
shader.varyingDataSize = sizeof(VaryingData);
assert(shader.varyingDataSize == 60);
MeshPtr mesh = CreatePlane();
mesh->CalculateTangents();
vertices.clear();
indices.clear();
int vertexCount = mesh->GetVertexCount();
for (int i = 0; i < vertexCount; ++i)
{
vertices.emplace_back(Vertex{ mesh->vertices[i], mesh->texcoords[i], mesh->normals[i], mesh->tangents[i] });
}
for (auto idx : mesh->indices) indices.emplace_back((u16)idx);
}
canvas->Clear();
Rasterizer::PrepareRender();
objectCtrl.MouseRotate(objectTrans, false);
Rasterizer::transform = objectTrans.GetMatrix();
Rasterizer::renderData.AssignVertexBuffer(vertices);
Rasterizer::renderData.AssignIndexBuffer(indices);
Rasterizer::SetShader(&shader);
Rasterizer::Submit();
Rasterizer::Render();
canvas->Present();
}
<|endoftext|> |
<commit_before><commit_msg>AES and DES are working, there's still something wrong with variable-key-length ciphers suchs as RC2 and RC4 as well as both triple DES variants<commit_after><|endoftext|> |
<commit_before>#ifndef MANIFOLDS_FUNCTIONS_MULTI_MATRIX_REDUCTION_HH
#define MANIFOLDS_FUNCTIONS_MULTI_MATRIX_REDUCTION_HH
#include "multi_matrix.hh"
#include "function.hh"
#include <boost/mpl/find.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/end.hpp>
#include <utility>
namespace manifolds
{
template <int n1, int n2>
struct ReduxPair
{
static const int first = n1;
static const int second = n2;
};
template <class ... ReductionPairs>
struct Reduction : Function
{
template <class Arg, class Array, class ... Indices,
class = typename std::enable_if<
(sizeof...(Indices) == Arg::dimensions)
>::type>
static auto CoeffFromArray(void*,Arg arg, Array a,
Indices...indices)
{
return arg.Coeff(indices...);
}
template <class Arg, class Array, class ... Indices,
class = typename std::enable_if<
(sizeof...(Indices) != Arg::dimensions)
>::type>
static auto CoeffFromArray(int*,Arg arg, Array a,
Indices ... indices)
{
return CoeffFromArray(arg, a, indices...,
a[sizeof...(Indices)]);
}
template <class Vector, int index>
using is_not_in =
typename boost::is_same<
typename boost::mpl::find<
Vector, int_<index>
>::type,
typename boost::mpl::end<Vector>::type
>::type;
template <class MMatrix,
class Skips,
class IndicesTuple = std::tuple<>,
int index = 0,
bool = MMatrix::dimensions == index>
struct output_type
{
typedef int_<
MMatrix::template dimension<index>::value> dim;
typedef typename std::conditional<
is_not_in<Skips, index>::value,
decltype(push_back(std::declval<IndicesTuple>(),
dim())),
IndicesTuple
>::type next_tuple;
typedef typename output_type<
MMatrix,
Skips,
next_tuple,
index+1
>::type type;
};
template <class MMatrix, class Skips,
int index, int ... dimensions>
struct output_type<
MMatrix, Skips, std::tuple<int_<dimensions>...>,
index, true>
{
typedef MultiMatrix<
typename MMatrix::CoefficientType,
dimensions...> type;
};
template <class Array>
static bool inc_pair(Array & a, int b, int c, int dim)
{
++a[b];
++a[c];
return a[b] == dim;
}
template <class Arg>
auto operator()(Arg arg) const
{
static const bool all_good =
and_<bool_<
Arg::template dimension<
ReductionPairs::first>::value ==
Arg::template dimension<
ReductionPairs::second>::value>...>::value;
static_assert(all_good, "Can only contract indices "
"of the same dimension");
static std::array<std::pair<int,int>,
sizeof...(ReductionPairs)> reduxes =
{std::make_pair(ReductionPairs::first,
ReductionPairs::second)...};
int in_indices[Arg::dimensions] = {};
typename output_type<
Arg,
boost::mpl::vector<
int_<ReductionPairs::first>...,
int_<ReductionPairs::second>...
>
>::type result;
int out_indices[decltype(result)::dimensions] = {};
while(true)
{
while(true)
{
result.Coeff(out_indices) +=
arg.Coeff(in_indices);
unsigned index = 0;
while(inc_pair(in_indices, reduxes[index].first,
reduxes[index].second,
arg.Dimension(reduxes[index].second)))
{
in_indices[reduxes[index].first] = 0;
in_indices[reduxes[index].second] = 0;
if(++index == sizeof...(ReductionPairs))
{
goto output_index_done;
}
}
}
output_index_done:
int index = 0;
while(true)
{
if(std::find_if(reduxes.begin(), reduxes.end(),
[index](auto x)
{return x.first == index ||
x.second == index;}) ==
reduxes.end())
{
if(++in_indices[index] == arg.Dimension(index))
{
int smaller_ones = 0;
for(auto x : reduxes)
{
smaller_ones +=
(x.first < index) +
(x.second < index);
}
in_indices[index] =
out_indices[index-smaller_ones] = 0;
if(++index == (int)Arg::dimensions)
return result;
}
else
{
int smaller_ones = 0;
for(auto x : reduxes)
{
smaller_ones +=
(x.first < index) +
(x.second < index);
}
++out_indices[index-smaller_ones];
break;
}
}
else if(++index == (int)Arg::dimensions)
return result;
}
}
}
};
}
#endif
<commit_msg>Fixing clang warning<commit_after>#ifndef MANIFOLDS_FUNCTIONS_MULTI_MATRIX_REDUCTION_HH
#define MANIFOLDS_FUNCTIONS_MULTI_MATRIX_REDUCTION_HH
#include "multi_matrix.hh"
#include "function.hh"
#include <boost/mpl/find.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/end.hpp>
#include <utility>
namespace manifolds
{
template <int n1, int n2>
struct ReduxPair
{
static const int first = n1;
static const int second = n2;
};
template <class ... ReductionPairs>
struct Reduction : Function
{
template <class Arg, class Array, class ... Indices,
class = typename std::enable_if<
(sizeof...(Indices) == Arg::dimensions)
>::type>
static auto CoeffFromArray(void*,Arg arg, Array a,
Indices...indices)
{
return arg.Coeff(indices...);
}
template <class Arg, class Array, class ... Indices,
class = typename std::enable_if<
(sizeof...(Indices) != Arg::dimensions)
>::type>
static auto CoeffFromArray(int*,Arg arg, Array a,
Indices ... indices)
{
return CoeffFromArray(arg, a, indices...,
a[sizeof...(Indices)]);
}
template <class Vector, int index>
using is_not_in =
typename boost::is_same<
typename boost::mpl::find<
Vector, int_<index>
>::type,
typename boost::mpl::end<Vector>::type
>::type;
template <class MMatrix,
class Skips,
class IndicesTuple = std::tuple<>,
int index = 0,
bool = MMatrix::dimensions == index>
struct output_type
{
typedef int_<
MMatrix::template dimension<index>::value> dim;
typedef typename std::conditional<
is_not_in<Skips, index>::value,
decltype(push_back(std::declval<IndicesTuple>(),
dim())),
IndicesTuple
>::type next_tuple;
typedef typename output_type<
MMatrix,
Skips,
next_tuple,
index+1
>::type type;
};
template <class MMatrix, class Skips,
int index, int ... dimensions>
struct output_type<
MMatrix, Skips, std::tuple<int_<dimensions>...>,
index, true>
{
typedef MultiMatrix<
typename MMatrix::CoefficientType,
dimensions...> type;
};
template <class Array>
static bool inc_pair(Array & a, int b, int c, int dim)
{
++a[b];
++a[c];
return a[b] == dim;
}
template <class Arg>
auto operator()(Arg arg) const
{
static const bool all_good =
and_<bool_<
Arg::template dimension<
ReductionPairs::first>::value ==
Arg::template dimension<
ReductionPairs::second>::value>...>::value;
static_assert(all_good, "Can only contract indices "
"of the same dimension");
static std::array<std::pair<int,int>,
sizeof...(ReductionPairs)> reduxes =
{{std::make_pair(ReductionPairs::first,
ReductionPairs::second)...}};
int in_indices[Arg::dimensions] = {};
typename output_type<
Arg,
boost::mpl::vector<
int_<ReductionPairs::first>...,
int_<ReductionPairs::second>...
>
>::type result;
int out_indices[decltype(result)::dimensions] = {};
while(true)
{
while(true)
{
result.Coeff(out_indices) +=
arg.Coeff(in_indices);
unsigned index = 0;
while(inc_pair(in_indices, reduxes[index].first,
reduxes[index].second,
arg.Dimension(reduxes[index].second)))
{
in_indices[reduxes[index].first] = 0;
in_indices[reduxes[index].second] = 0;
if(++index == sizeof...(ReductionPairs))
{
goto output_index_done;
}
}
}
output_index_done:
int index = 0;
while(true)
{
if(std::find_if(reduxes.begin(), reduxes.end(),
[index](auto x)
{return x.first == index ||
x.second == index;}) ==
reduxes.end())
{
if(++in_indices[index] == arg.Dimension(index))
{
int smaller_ones = 0;
for(auto x : reduxes)
{
smaller_ones +=
(x.first < index) +
(x.second < index);
}
in_indices[index] =
out_indices[index-smaller_ones] = 0;
if(++index == (int)Arg::dimensions)
return result;
}
else
{
int smaller_ones = 0;
for(auto x : reduxes)
{
smaller_ones +=
(x.first < index) +
(x.second < index);
}
++out_indices[index-smaller_ones];
break;
}
}
else if(++index == (int)Arg::dimensions)
return result;
}
}
}
};
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake 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.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_GL_DATA_FORMAT_HPP__
#define LASERCAKE_GL_DATA_FORMAT_HPP__
// This header does not use GL types (GLfloat, GLubyte) in order to
// be agnostic between GLEW and Qt's opinions of OpenGL headers.
// gl_data_preparation.cpp static_asserts that they're the types we
// expect.
// (This might not be necessary currently, but doesn't hurt anything
// (that I know of).)
#include <string>
#include <vector>
#include "cxx11/array.hpp"
#include <ostream>
#include <stdlib.h> //malloc
#include <string.h> //memcpy
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/matrix_access.hpp>
#include "world_constants.hpp"
namespace gl_data_format {
typedef float header_GLfloat;
typedef unsigned char header_GLubyte;
// These are to be passed as part of arrays to OpenGL.
// Thus their data format/layout makes a difference.
// TODO maybe make vector3<GLfloat> and vertex the same thing?
// Is vector3<GLfloat>'s layout required to be the same as that of
// this struct? I believe so. typedef vector3<GLfloat> vertex; ?
// TODO use glm types?
struct vertex {
vertex() {}
vertex(header_GLfloat x, header_GLfloat y, header_GLfloat z) : x(x), y(y), z(z) {}
/* implicit conversion */ vertex(vector3<header_GLfloat> const& v) : x(v.x), y(v.y), z(v.z) {}
/* implicit conversion */ vertex(glm::vec3 const& v) : x(v.x), y(v.y), z(v.z) {}
/* implicit conversion */ vertex(glm::dvec3 const& v) : x(v.x), y(v.y), z(v.z) {}
header_GLfloat x, y, z;
};
static_assert(sizeof(vertex) == 3*sizeof(header_GLfloat), "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, vertex const& v) {
// TODO does the float precision we output here matter?
return os << '(' << v.x << ", " << v.y << ", " << v.z << ')';
}
struct color {
color() {}
// Use hex RGBA values as familiar from e.g. CSS.
// e.g. 0x00ff0077 is pure green at 50% opacity.
explicit color(uint32_t rgba)
: r(header_GLubyte(rgba >> 24)), g(header_GLubyte(rgba >> 16)),
b(header_GLubyte(rgba >> 8)), a(header_GLubyte(rgba)) {}
color(header_GLubyte r, header_GLubyte g, header_GLubyte b, header_GLubyte a)
: r(r), g(g), b(b), a(a) {}
// random Web forums thought a factor of 255.0 was correct, but is it exactly the right conversion?
color(header_GLfloat r, header_GLfloat g, header_GLfloat b, header_GLfloat a)
: r(header_GLubyte(r*255)), g(header_GLubyte(g*255)), b(header_GLubyte(b*255)), a(header_GLubyte(a*255)) {}
header_GLubyte r, g, b, a;
};
static_assert(sizeof(color) == 4*sizeof(header_GLubyte), "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, color const& c) {
// TODO does the float precision we output here matter?
return os << "rgba(" << std::hex << int(c.r) << int(c.g) << int(c.b) << int(c.a) << std::dec << ')';
}
struct vertex_with_color {
vertex_with_color() {}
vertex_with_color(vertex v, color c) : c(c), v(v) {}
vertex_with_color(header_GLfloat x, header_GLfloat y, header_GLfloat z, color c)
: c(c), v(x,y,z) {}
color c;
vertex v;
};
static_assert(sizeof(vertex_with_color) == 16, "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, vertex_with_color const& vc) {
// TODO does the float precision we output here matter?
return os << vc.c << '~' << vc.v;
}
struct gl_call_data {
typedef uint32_t size_type;
size_type count;
size_type alloced;
vertex_with_color* vertices;
//vertex_with_color* vertices_end;
static const size_type default_size = 5;
static const size_type expand_multiplier = 4;
gl_call_data()
: count(0),
alloced(default_size),
vertices((vertex_with_color*)malloc(default_size*sizeof(vertex_with_color))) {
assert(vertices);
}
gl_call_data(gl_call_data&& other)
: count(other.count),
alloced(other.alloced),
vertices(other.vertices) {
other.vertices = nullptr;
}
gl_call_data(gl_call_data const& other)
: count(other.count),
alloced(other.alloced),
vertices((vertex_with_color*)malloc(other.alloced*sizeof(vertex_with_color))) {
assert(vertices);
memcpy(vertices, other.vertices, count*sizeof(vertex_with_color));
}
gl_call_data& operator=(gl_call_data const& other) {
free(vertices);
count = other.count;
alloced = other.alloced;
vertices = ((vertex_with_color*)malloc(other.alloced*sizeof(vertex_with_color)));
assert(vertices);
memcpy(vertices, other.vertices, count*sizeof(vertex_with_color));
return *this;
}
gl_call_data& operator=(gl_call_data&& other) {
free(vertices);
count = other.count;
alloced = other.alloced;
vertices = other.vertices;
other.vertices = nullptr;
return *this;
}
~gl_call_data() { free(vertices); }
void push_vertex(vertex_with_color const& v) {
if(count == alloced) do_realloc(alloced * expand_multiplier);
vertices[count] = v;
++count;
}
void push_vertex(vertex const& v, color const& c) {
if(count == alloced) do_realloc(alloced * expand_multiplier);
vertices[count].c = c;
vertices[count].v = v;
++count;
}
void reserve_new_slots(size_type num_slots) {
const size_type new_count = count + num_slots;
if(new_count > alloced) do_realloc(new_count * expand_multiplier);
count = new_count;
}
size_type size() const { return count; }
void do_realloc(size_type new_size) {
assert(new_size > alloced);
vertex_with_color* new_vertices = (vertex_with_color*)malloc(new_size * sizeof(vertex_with_color));
assert(new_vertices);
memcpy(new_vertices, vertices, count*sizeof(vertex_with_color));
free(vertices);
vertices = new_vertices;
alloced = new_size;
}
};
struct gl_collection {
// Points and lines are for debugging, because they don't change size at distance,
// and TODO can be represented reasonably by triangles.
// Triangles are legit.
// Quads are TODO OpenGL prefers you to use triangles (esp. OpenGL ES) and
// they'll be converted at some point.
gl_call_data points;
gl_call_data lines;
gl_call_data triangles;
gl_call_data quads;
};
//The gl_collection:s with higher indices here are intended to be
//further away and rendered first (therefore covered up most
//by everything else that's closer).
typedef std::vector<gl_collection> gl_collectionplex;
struct heads_up_display_text {
// text may contain newlines, and will also
// be soft-wrapped to fit on the screen.
std::string text;
color c;
std::string font_name;
int point_size;
int horizontal_margin_in_pixels;
int vertical_margin_in_pixels;
};
struct gl_all_data {
gl_collectionplex stuff_to_draw_as_gl_collections_by_distance;
color tint_everything_with_this_color;
heads_up_display_text hud_text;
vector3<header_GLfloat> facing;
vector3<header_GLfloat> facing_up;
};
const int32_t fovy_degrees = 80;
const non_normalized_rational<int32_t> pretend_aspect_ratio_value_when_culling(2,1);
const distance near_clipping_plane = tile_width / 10;
const distance far_clipping_plane = tile_width * 300;
// TODO: we can, with some more work,
// use non-floating-point matrices for several things.
// Which would allow main-simulation code to filter based on
// view frustums, for example.
inline glm::mat4 make_projection_matrix(float aspect_ratio) {
return glm::perspective(
float(fovy_degrees),
float(aspect_ratio),
get_primitive_float(near_clipping_plane/fine_distance_units),
get_primitive_float(far_clipping_plane/fine_distance_units)
);
}
const vector3<float> view_from(0);
inline glm::mat4 make_view_matrix(vector3<float> view_towards, vector3<float> up) {
return glm::lookAt(
glm::vec3(view_from.x, view_from.y, view_from.z),
glm::vec3(view_towards.x, view_towards.y, view_towards.z),
glm::vec3(up.x, up.y, up.z)
);
}
// TODO glm has glm::detail::tmat4x4<> etc, needed to templatize
// this, if I want to templatize it.
struct frustum {
enum direction {
// Windows headers define NEAR and FAR
// and I don't want to tempt any dragons by #undef'ing
// them, so just add an underscore to those names here.
LEFT, RIGHT, BOTTOM, TOP, NEAR_, FAR_
};
array<glm::vec4, 6> half_spaces;
};
inline frustum make_frustum_from_matrix(glm::mat4 m) {
frustum result;
result.half_spaces[frustum::LEFT] = glm::normalize(glm::row(m, 3) + glm::row(m, 0));
result.half_spaces[frustum::RIGHT] = glm::normalize(glm::row(m, 3) - glm::row(m, 0));
result.half_spaces[frustum::BOTTOM] = glm::normalize(glm::row(m, 3) + glm::row(m, 1));
result.half_spaces[frustum::TOP] = glm::normalize(glm::row(m, 3) - glm::row(m, 1));
result.half_spaces[frustum::NEAR_] = glm::normalize(glm::row(m, 3) + glm::row(m, 2));
result.half_spaces[frustum::FAR_] = glm::normalize(glm::row(m, 3) - glm::row(m, 2));
return result;
}
} // end namespace gl_data_format
#endif
<commit_msg>fix color ostreaming for near-0-value components.<commit_after>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake 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.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_GL_DATA_FORMAT_HPP__
#define LASERCAKE_GL_DATA_FORMAT_HPP__
// This header does not use GL types (GLfloat, GLubyte) in order to
// be agnostic between GLEW and Qt's opinions of OpenGL headers.
// gl_data_preparation.cpp static_asserts that they're the types we
// expect.
// (This might not be necessary currently, but doesn't hurt anything
// (that I know of).)
#include <string>
#include <vector>
#include "cxx11/array.hpp"
#include <ostream>
#include <stdlib.h> //malloc
#include <string.h> //memcpy
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/matrix_access.hpp>
#include "world_constants.hpp"
namespace gl_data_format {
typedef float header_GLfloat;
typedef unsigned char header_GLubyte;
// These are to be passed as part of arrays to OpenGL.
// Thus their data format/layout makes a difference.
// TODO maybe make vector3<GLfloat> and vertex the same thing?
// Is vector3<GLfloat>'s layout required to be the same as that of
// this struct? I believe so. typedef vector3<GLfloat> vertex; ?
// TODO use glm types?
struct vertex {
vertex() {}
vertex(header_GLfloat x, header_GLfloat y, header_GLfloat z) : x(x), y(y), z(z) {}
/* implicit conversion */ vertex(vector3<header_GLfloat> const& v) : x(v.x), y(v.y), z(v.z) {}
/* implicit conversion */ vertex(glm::vec3 const& v) : x(v.x), y(v.y), z(v.z) {}
/* implicit conversion */ vertex(glm::dvec3 const& v) : x(v.x), y(v.y), z(v.z) {}
header_GLfloat x, y, z;
};
static_assert(sizeof(vertex) == 3*sizeof(header_GLfloat), "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, vertex const& v) {
// TODO does the float precision we output here matter?
return os << '(' << v.x << ", " << v.y << ", " << v.z << ')';
}
struct color {
color() {}
// Use hex RGBA values as familiar from e.g. CSS.
// e.g. 0x00ff0077 is pure green at 50% opacity.
explicit color(uint32_t rgba)
: r(header_GLubyte(rgba >> 24)), g(header_GLubyte(rgba >> 16)),
b(header_GLubyte(rgba >> 8)), a(header_GLubyte(rgba)) {}
color(header_GLubyte r, header_GLubyte g, header_GLubyte b, header_GLubyte a)
: r(r), g(g), b(b), a(a) {}
// random Web forums thought a factor of 255.0 was correct, but is it exactly the right conversion?
color(header_GLfloat r, header_GLfloat g, header_GLfloat b, header_GLfloat a)
: r(header_GLubyte(r*255)), g(header_GLubyte(g*255)), b(header_GLubyte(b*255)), a(header_GLubyte(a*255)) {}
header_GLubyte r, g, b, a;
};
static_assert(sizeof(color) == 4*sizeof(header_GLubyte), "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, color const& c) {
// TODO does the float precision we output here matter?
const char oldfill = os.fill('0');
const std::ios::fmtflags oldflags = os.setf(std::ios::hex, std::ios::basefield);
os << "rgba(";
os.width(2); os << int(c.r);
os.width(2); os << int(c.g);
os.width(2); os << int(c.b);
os.width(2); os << int(c.a);
os << ')';
os.flags(oldflags);
os.fill(oldfill);
return os;
}
struct vertex_with_color {
vertex_with_color() {}
vertex_with_color(vertex v, color c) : c(c), v(v) {}
vertex_with_color(header_GLfloat x, header_GLfloat y, header_GLfloat z, color c)
: c(c), v(x,y,z) {}
color c;
vertex v;
};
static_assert(sizeof(vertex_with_color) == 16, "OpenGL needs this data layout.");
inline std::ostream& operator<<(std::ostream& os, vertex_with_color const& vc) {
// TODO does the float precision we output here matter?
return os << vc.c << '~' << vc.v;
}
struct gl_call_data {
typedef uint32_t size_type;
size_type count;
size_type alloced;
vertex_with_color* vertices;
//vertex_with_color* vertices_end;
static const size_type default_size = 5;
static const size_type expand_multiplier = 4;
gl_call_data()
: count(0),
alloced(default_size),
vertices((vertex_with_color*)malloc(default_size*sizeof(vertex_with_color))) {
assert(vertices);
}
gl_call_data(gl_call_data&& other)
: count(other.count),
alloced(other.alloced),
vertices(other.vertices) {
other.vertices = nullptr;
}
gl_call_data(gl_call_data const& other)
: count(other.count),
alloced(other.alloced),
vertices((vertex_with_color*)malloc(other.alloced*sizeof(vertex_with_color))) {
assert(vertices);
memcpy(vertices, other.vertices, count*sizeof(vertex_with_color));
}
gl_call_data& operator=(gl_call_data const& other) {
free(vertices);
count = other.count;
alloced = other.alloced;
vertices = ((vertex_with_color*)malloc(other.alloced*sizeof(vertex_with_color)));
assert(vertices);
memcpy(vertices, other.vertices, count*sizeof(vertex_with_color));
return *this;
}
gl_call_data& operator=(gl_call_data&& other) {
free(vertices);
count = other.count;
alloced = other.alloced;
vertices = other.vertices;
other.vertices = nullptr;
return *this;
}
~gl_call_data() { free(vertices); }
void push_vertex(vertex_with_color const& v) {
if(count == alloced) do_realloc(alloced * expand_multiplier);
vertices[count] = v;
++count;
}
void push_vertex(vertex const& v, color const& c) {
if(count == alloced) do_realloc(alloced * expand_multiplier);
vertices[count].c = c;
vertices[count].v = v;
++count;
}
void reserve_new_slots(size_type num_slots) {
const size_type new_count = count + num_slots;
if(new_count > alloced) do_realloc(new_count * expand_multiplier);
count = new_count;
}
size_type size() const { return count; }
void do_realloc(size_type new_size) {
assert(new_size > alloced);
vertex_with_color* new_vertices = (vertex_with_color*)malloc(new_size * sizeof(vertex_with_color));
assert(new_vertices);
memcpy(new_vertices, vertices, count*sizeof(vertex_with_color));
free(vertices);
vertices = new_vertices;
alloced = new_size;
}
};
struct gl_collection {
// Points and lines are for debugging, because they don't change size at distance,
// and TODO can be represented reasonably by triangles.
// Triangles are legit.
// Quads are TODO OpenGL prefers you to use triangles (esp. OpenGL ES) and
// they'll be converted at some point.
gl_call_data points;
gl_call_data lines;
gl_call_data triangles;
gl_call_data quads;
};
//The gl_collection:s with higher indices here are intended to be
//further away and rendered first (therefore covered up most
//by everything else that's closer).
typedef std::vector<gl_collection> gl_collectionplex;
struct heads_up_display_text {
// text may contain newlines, and will also
// be soft-wrapped to fit on the screen.
std::string text;
color c;
std::string font_name;
int point_size;
int horizontal_margin_in_pixels;
int vertical_margin_in_pixels;
};
struct gl_all_data {
gl_collectionplex stuff_to_draw_as_gl_collections_by_distance;
color tint_everything_with_this_color;
heads_up_display_text hud_text;
vector3<header_GLfloat> facing;
vector3<header_GLfloat> facing_up;
};
const int32_t fovy_degrees = 80;
const non_normalized_rational<int32_t> pretend_aspect_ratio_value_when_culling(2,1);
const distance near_clipping_plane = tile_width / 10;
const distance far_clipping_plane = tile_width * 300;
// TODO: we can, with some more work,
// use non-floating-point matrices for several things.
// Which would allow main-simulation code to filter based on
// view frustums, for example.
inline glm::mat4 make_projection_matrix(float aspect_ratio) {
return glm::perspective(
float(fovy_degrees),
float(aspect_ratio),
get_primitive_float(near_clipping_plane/fine_distance_units),
get_primitive_float(far_clipping_plane/fine_distance_units)
);
}
const vector3<float> view_from(0);
inline glm::mat4 make_view_matrix(vector3<float> view_towards, vector3<float> up) {
return glm::lookAt(
glm::vec3(view_from.x, view_from.y, view_from.z),
glm::vec3(view_towards.x, view_towards.y, view_towards.z),
glm::vec3(up.x, up.y, up.z)
);
}
// TODO glm has glm::detail::tmat4x4<> etc, needed to templatize
// this, if I want to templatize it.
struct frustum {
enum direction {
// Windows headers define NEAR and FAR
// and I don't want to tempt any dragons by #undef'ing
// them, so just add an underscore to those names here.
LEFT, RIGHT, BOTTOM, TOP, NEAR_, FAR_
};
array<glm::vec4, 6> half_spaces;
};
inline frustum make_frustum_from_matrix(glm::mat4 m) {
frustum result;
result.half_spaces[frustum::LEFT] = glm::normalize(glm::row(m, 3) + glm::row(m, 0));
result.half_spaces[frustum::RIGHT] = glm::normalize(glm::row(m, 3) - glm::row(m, 0));
result.half_spaces[frustum::BOTTOM] = glm::normalize(glm::row(m, 3) + glm::row(m, 1));
result.half_spaces[frustum::TOP] = glm::normalize(glm::row(m, 3) - glm::row(m, 1));
result.half_spaces[frustum::NEAR_] = glm::normalize(glm::row(m, 3) + glm::row(m, 2));
result.half_spaces[frustum::FAR_] = glm::normalize(glm::row(m, 3) - glm::row(m, 2));
return result;
}
} // end namespace gl_data_format
#endif
<|endoftext|> |
<commit_before>// MFEM Example 1 - Parallel NURBS Version
//
// Compile with: make nurbs_ex1p
//
// Sample runs: mpirun -np 4 nurbs_ex1p -m ../../data/square-disc.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/star.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/escher.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/fichera.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-p2.vtk -o 2
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-p3.mesh -o 3
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/disc-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/pipe-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/ball-nurbs.mesh -o 2
// mpirun -np 4 nurbs_ex1p -m ../../data/star-surf.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-surf.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/inline-segment.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/amr-quad.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/amr-hex.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/mobius-strip.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/mobius-strip.mesh -o -1 -sc
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options.
const char *mesh_file = "../../data/star.mesh";
Array<int> order(1);
order[0] = 1;
bool static_cond = false;
bool visualization = 1;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 3. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 4. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 10,000 elements.
{
int ref_levels =
(int)floor(log(10000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 5. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
delete mesh;
if (!pmesh->NURBSext)
{
int par_ref_levels = 2;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh->UniformRefinement();
}
}
// 6. Define a parallel finite element space on the parallel mesh. Here we
// use continuous Lagrange finite elements of the specified order. If
// order < 1, we instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec;
NURBSExtension *NURBSext = NULL;
int own_fec = 0;
if (order[0] == -1) // Isoparametric
{
if (pmesh->GetNodes())
{
fec = pmesh->GetNodes()->OwnFEC();
own_fec = 0;
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
cout <<"Mesh does not have FEs --> Assume order 1.\n";
fec = new H1_FECollection(1, dim);
own_fec = 1;
}
}
else if (pmesh->NURBSext && (order[0] > 0) ) // Subparametric NURBS
{
fec = new NURBSFECollection(order[0]);
own_fec = 1;
int nkv = pmesh->NURBSext->GetNKV();
if (order.Size() == 1)
{
int tmp = order[0];
order.SetSize(nkv);
order = tmp;
}
if (order.Size() != nkv ) { mfem_error("Wrong number of orders set."); }
NURBSext = new NURBSExtension(pmesh->NURBSext, order);
}
else
{
if (order.Size() > 1) { cout <<"Wrong number of orders set, needs one.\n"; }
fec = new H1_FECollection(abs(order[0]), dim);
own_fec = 1;
}
ParFiniteElementSpace *fespace = new ParFiniteElementSpace(pmesh,NURBSext,fec);
HYPRE_Int size = fespace->GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl;
}
// 7. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined
// by marking all the boundary attributes from the mesh as essential
// (Dirichlet) and converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (pmesh->bdr_attributes.Size())
{
Array<int> ess_bdr(pmesh->bdr_attributes.Max());
ess_bdr = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 8. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system, which in this case is
// (1,phi_i) where phi_i are the basis functions in fespace.
ParLinearForm *b = new ParLinearForm(fespace);
ConstantCoefficient one(1.0);
b->AddDomainIntegrator(new DomainLFIntegrator(one));
b->Assemble();
// 9. Define the solution vector x as a parallel finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
ParGridFunction x(fespace);
x = 0.0;
// 10. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
ParBilinearForm *a = new ParBilinearForm(fespace);
a->AddDomainIntegrator(new DiffusionIntegrator(one));
// 11. Assemble the parallel bilinear form and the corresponding linear
// system, applying any necessary transformations such as: parallel
// assembly, eliminating boundary conditions, applying conforming
// constraints for non-conforming AMR, static condensation, etc.
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
HypreParMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
if (myid == 0)
{
cout << "Size of linear system: " << A.GetGlobalNumRows() << endl;
}
// 12. Define and apply a parallel PCG solver for AX=B with the BoomerAMG
// preconditioner from hypre.
HypreSolver *amg = new HypreBoomerAMG(A);
HyprePCG *pcg = new HyprePCG(A);
pcg->SetTol(1e-12);
pcg->SetMaxIter(200);
pcg->SetPrintLevel(2);
pcg->SetPreconditioner(*amg);
pcg->Mult(B, X);
// 13. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a->RecoverFEMSolution(X, *b, x);
// 14. Save the refined mesh and the solution in parallel. This output can
// be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
{
ostringstream mesh_name, sol_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
sol_name << "sol." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh->Print(mesh_ofs);
ofstream sol_ofs(sol_name.str().c_str());
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 15. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << *pmesh << x << flush;
}
// 16. Save data in the VisIt format
VisItDataCollection visit_dc("Example1-Parallel", pmesh);
visit_dc.RegisterField("solution", &x);
visit_dc.Save();
// 17. Free the used memory.
delete pcg;
delete amg;
delete a;
delete b;
delete fespace;
if (own_fec) { delete fec; }
delete pmesh;
MPI_Finalize();
return 0;
}
<commit_msg>Add no ibp to parallel example<commit_after>// MFEM Example 1 - Parallel NURBS Version
//
// Compile with: make nurbs_ex1p
//
// Sample runs: mpirun -np 4 nurbs_ex1p -m ../../data/square-disc.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/star.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/escher.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/fichera.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-p2.vtk -o 2
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-p3.mesh -o 3
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/disc-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/pipe-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/ball-nurbs.mesh -o 2
// mpirun -np 4 nurbs_ex1p -m ../../data/star-surf.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-surf.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/inline-segment.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/amr-quad.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/amr-hex.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/mobius-strip.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/mobius-strip.mesh -o -1 -sc
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/disc-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/pipe-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/beam-hex-nurbs.mesh -pm 1 -ps 2
// mpirun -np 4 nurbs_ex1p -m square-nurbs.mesh -o 2 -no-ibp
// mpirun -np 4 nurbs_ex1p -m cube-nurbs.mesh -o 2 -no-ibp
// mpirun -np 4 nurbs_ex1p -m pipe-nurbs-2d.mesh -o 2 -no-ibp
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
/** Class for integrating the bilinear form a(u,v) := (Q Laplace u, v) where Q
can be a scalar coefficient. */
class Diffusion2Integrator: public BilinearFormIntegrator
{
private:
#ifndef MFEM_THREAD_SAFE
Vector shape,laplace;
#endif
Coefficient *Q;
public:
/// Construct a diffusion integrator with coefficient Q = 1
Diffusion2Integrator() { Q = NULL; }
/// Construct a diffusion integrator with a scalar coefficient q
Diffusion2Integrator (Coefficient &q) : Q(&q) { }
/** Given a particular Finite Element
computes the element stiffness matrix elmat. */
virtual void AssembleElementMatrix(const FiniteElement &el,
ElementTransformation &Trans,
DenseMatrix &elmat)
{
int nd = el.GetDof();
int dim = el.GetDim();
int spaceDim = Trans.GetSpaceDim();
bool square = (dim == spaceDim);
double w;
#ifdef MFEM_THREAD_SAFE
Vector shape[nd];
Vector laplace(nd);
#else
shape.SetSize(nd);
laplace.SetSize(nd);
#endif
elmat.SetSize(nd);
const IntegrationRule *ir = IntRule;
if (ir == NULL)
{
int order;
if (el.Space() == FunctionSpace::Pk)
{
order = 2*el.GetOrder() - 2;
}
else
{
order = 2*el.GetOrder() + dim - 1;
}
if (el.Space() == FunctionSpace::rQk)
{
ir = &RefinedIntRules.Get(el.GetGeomType(),order);
}
else
{
ir = &IntRules.Get(el.GetGeomType(),order);
}
}
elmat = 0.0;
for (int i = 0; i < ir->GetNPoints(); i++)
{
const IntegrationPoint &ip = ir->IntPoint(i);
Trans.SetIntPoint(&ip);
w = -ip.weight * Trans.Weight();
el.CalcShape(ip, shape);
el.CalcPhysLaplacian(Trans, laplace);
if (Q)
{
w *= Q->Eval(Trans, ip);
}
for (int j = 0; j < nd; j++)
{
for (int i = 0; i < nd; i++)
{
elmat(i, j) += w*shape(i)*laplace(j);
}
}
}
}
};
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options.
const char *mesh_file = "../../data/star.mesh";
Array<int> order(1);
order[0] = 1;
bool static_cond = false;
bool visualization = 1;
bool ibp = 1;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&ibp, "-ibp", "--ibp", "-no-ibp",
"--no-ibp",
"Selects the standard weak form (IBP) or the nonstandard (NO-IBP).");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 3. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 4. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 10,000 elements.
{
int ref_levels =
(int)floor(log(10000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 5. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
delete mesh;
if (!pmesh->NURBSext)
{
int par_ref_levels = 2;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh->UniformRefinement();
}
}
// 6. Define a parallel finite element space on the parallel mesh. Here we
// use continuous Lagrange finite elements of the specified order. If
// order < 1, we instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec;
NURBSExtension *NURBSext = NULL;
int own_fec = 0;
if (order[0] == -1) // Isoparametric
{
if (pmesh->GetNodes())
{
fec = pmesh->GetNodes()->OwnFEC();
own_fec = 0;
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
cout <<"Mesh does not have FEs --> Assume order 1.\n";
fec = new H1_FECollection(1, dim);
own_fec = 1;
}
}
else if (pmesh->NURBSext && (order[0] > 0) ) // Subparametric NURBS
{
fec = new NURBSFECollection(order[0]);
own_fec = 1;
int nkv = pmesh->NURBSext->GetNKV();
if (order.Size() == 1)
{
int tmp = order[0];
order.SetSize(nkv);
order = tmp;
}
if (order.Size() != nkv ) { mfem_error("Wrong number of orders set."); }
NURBSext = new NURBSExtension(pmesh->NURBSext, order);
}
else
{
if (order.Size() > 1) { cout <<"Wrong number of orders set, needs one.\n"; }
fec = new H1_FECollection(abs(order[0]), dim);
own_fec = 1;
}
ParFiniteElementSpace *fespace = new ParFiniteElementSpace(pmesh,NURBSext,fec);
HYPRE_Int size = fespace->GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl;
}
if (!ibp)
{
if (!pmesh->NURBSext)
{
cout << "No integration by parts requires a NURBS mesh."<< endl;
return 2;
}
if (pmesh->NURBSext->GetNP()>1)
{
cout << "No integration by parts requires a NURBS mesh, with only 1 patch."<<
endl;
cout << "A C_1 discretisation is required."<< endl;
cout << "Currently only C_0 multipatch coupling implemented."<< endl;
return 3;
}
if (order[0]<2)
{
cout << "No integration by parts requires at least quadratic NURBS."<< endl;
cout << "A C_1 discretisation is required."<< endl;
return 4;
}
}
// 7. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined
// by marking all the boundary attributes from the mesh as essential
// (Dirichlet) and converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (pmesh->bdr_attributes.Size())
{
Array<int> ess_bdr(pmesh->bdr_attributes.Max());
ess_bdr = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 8. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system, which in this case is
// (1,phi_i) where phi_i are the basis functions in fespace.
ParLinearForm *b = new ParLinearForm(fespace);
ConstantCoefficient one(1.0);
b->AddDomainIntegrator(new DomainLFIntegrator(one));
b->Assemble();
// 9. Define the solution vector x as a parallel finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
ParGridFunction x(fespace);
x = 0.0;
// 10. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
ParBilinearForm *a = new ParBilinearForm(fespace);
if (ibp)
{
a->AddDomainIntegrator(new DiffusionIntegrator(one));
}
else
{
a->AddDomainIntegrator(new Diffusion2Integrator(one));
}
// 11. Assemble the parallel bilinear form and the corresponding linear
// system, applying any necessary transformations such as: parallel
// assembly, eliminating boundary conditions, applying conforming
// constraints for non-conforming AMR, static condensation, etc.
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
HypreParMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
if (myid == 0)
{
cout << "Size of linear system: " << A.GetGlobalNumRows() << endl;
}
// 12. Define and apply a parallel PCG solver for AX=B with the BoomerAMG
// preconditioner from hypre.
HypreSolver *amg = new HypreBoomerAMG(A);
HyprePCG *pcg = new HyprePCG(A);
pcg->SetTol(1e-12);
pcg->SetMaxIter(200);
pcg->SetPrintLevel(2);
pcg->SetPreconditioner(*amg);
pcg->Mult(B, X);
// 13. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a->RecoverFEMSolution(X, *b, x);
// 14. Save the refined mesh and the solution in parallel. This output can
// be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
{
ostringstream mesh_name, sol_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
sol_name << "sol." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh->Print(mesh_ofs);
ofstream sol_ofs(sol_name.str().c_str());
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 15. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << *pmesh << x << flush;
}
// 16. Save data in the VisIt format
VisItDataCollection visit_dc("Example1-Parallel", pmesh);
visit_dc.RegisterField("solution", &x);
visit_dc.Save();
// 17. Free the used memory.
delete pcg;
delete amg;
delete a;
delete b;
delete fespace;
if (own_fec) { delete fec; }
delete pmesh;
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>// In many works of James and John Whitney trigonomic equations are used to generate animation
// This sketch shows a simple Lissajous curve animation to explain the principle
// ToDo: hmm... why no workin' ?
[[pPhase]]
[[plissajouRatioX]]
[[plissajouRatioY]]
[[pDensity]]
<commit_msg>ExampleCode for LissamojiWhitney<commit_after>// In many works of James and John Whitney trigonomic equations are used to generate animation
// This sketch shows a simple Lissajous curve animation to explain the principle
// Moving the eyes on the curve is done by animating the phase of the trigonomic functions
// Depending on the animation speed parameter the phase value is incremented with each new frame
animSpeed[1] = 60 * pAnimSpeed;
pPhase.set(( ofGetFrameNum() % animSpeed[1] ) * TWO_PI / animSpeed[1]);
// The shape of a Lissajous curve is highly sensitive to
// the relation of the frequencies used in the equations for X and Y
// The values that define this relation are randomly chosen every 3 seconds here
if( ( ofGetElapsedTimeMillis() - timerLastTime ) > 3000 ){
plissajouRatioX.set(ofRandom(1,plissajouRatioX.getMax()));
plissajouRatioY.set(ofRandom(1,plissajouRatioY.getMax()));
timerLastTime = ofGetElapsedTimeMillis();
}
// Calculate the spacing of each element on the curve
spacingOnCurve = TWO_PI / [[Density]]
// Calculate the position and draw each element
for (int i = 0; i < [[Density]] ; i++) {
// amplitude * sin ( angle + phase )
x = [[Amplitude]] * cos( [[Lissajous Ratio X]] * spacingOnCurve * i + [[Phase]]);
y = [[Amplitude]] * sin( [[Lissajous Ratio Y]] * spacingOnCurve * i + [[Phase]]);
// calculate the size of each element
iconWidth = eyesImg.getWidth() * Image Scale;
iconHeight = eyesImg.getHeight() * Image Scale;
// draw the element
eyesImg.draw(x-iconWidth/2, y-iconHeight/2, iconWidth, iconHeight);
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: btndlg.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 17:48:34 $
*
* 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 _SV_BTNDLG_HXX
#define _SV_BTNDLG_HXX
#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
struct ImplBtnDlgItem;
class ImplBtnDlgItemList;
class PushButton;
// ----------------------
// - ButtonDialog-Types -
// ----------------------
#define BUTTONDIALOG_BUTTON_NOTFOUND ((USHORT)0xFFFF)
#define BUTTONDIALOG_DEFBUTTON ((USHORT)0x0001)
#define BUTTONDIALOG_OKBUTTON ((USHORT)0x0002)
#define BUTTONDIALOG_CANCELBUTTON ((USHORT)0x0004)
#define BUTTONDIALOG_HELPBUTTON ((USHORT)0x0008)
#define BUTTONDIALOG_FOCUSBUTTON ((USHORT)0x0010)
// ----------------
// - ButtonDialog -
// ----------------
class VCL_DLLPUBLIC ButtonDialog : public Dialog
{
private:
ImplBtnDlgItemList* mpItemList;
Size maPageSize;
Size maCtrlSize;
long mnButtonSize;
USHORT mnCurButtonId;
USHORT mnFocusButtonId;
BOOL mbFormat;
Link maClickHdl;
SAL_DLLPRIVATE void ImplInitButtonDialogData();
SAL_DLLPRIVATE PushButton* ImplCreatePushButton( USHORT nBtnFlags );
SAL_DLLPRIVATE ImplBtnDlgItem* ImplGetItem( USHORT nId ) const;
DECL_DLLPRIVATE_LINK( ImplClickHdl, PushButton* pBtn );
SAL_DLLPRIVATE void ImplPosControls();
// Copy assignment is forbidden and not implemented.
SAL_DLLPRIVATE ButtonDialog( const ButtonDialog & );
SAL_DLLPRIVATE ButtonDialog& operator=( const ButtonDialog& );
protected:
ButtonDialog( WindowType nType );
SAL_DLLPRIVATE long ImplGetButtonSize();
public:
ButtonDialog( Window* pParent, WinBits nStyle = WB_STDDIALOG );
ButtonDialog( Window* pParent, const ResId& rResId );
~ButtonDialog();
virtual void Resize();
virtual void StateChanged( StateChangedType nStateChange );
virtual void Click();
void SetPageSizePixel( const Size& rSize ) { maPageSize = rSize; }
const Size& GetPageSizePixel() const { return maPageSize; }
USHORT GetCurButtonId() const { return mnCurButtonId; }
void AddButton( const XubString& rText, USHORT nId, USHORT nBtnFlags, long nSepPixel = 0 );
void AddButton( StandardButtonType eType, USHORT nId, USHORT nBtnFlags, long nSepPixel = 0 );
void AddButton( PushButton* pBtn, USHORT nId, USHORT nBtnFlags, long nSepPixel = 0 );
void RemoveButton( USHORT nId );
void Clear();
USHORT GetButtonCount() const;
USHORT GetButtonId( USHORT nButton ) const;
PushButton* GetPushButton( USHORT nId ) const;
void SetButtonText( USHORT nId, const XubString& rText );
XubString GetButtonText( USHORT nId ) const;
void SetButtonHelpText( USHORT nId, const XubString& rText );
XubString GetButtonHelpText( USHORT nId ) const;
void SetButtonHelpId( USHORT nId, ULONG nHelpId );
ULONG GetButtonHelpId( USHORT nId ) const;
void SetFocusButton( USHORT nId = BUTTONDIALOG_BUTTON_NOTFOUND ) { mnFocusButtonId = nId; }
USHORT GetFocusButton() const { return mnFocusButtonId; }
void SetClickHdl( const Link& rLink ) { maClickHdl = rLink; }
const Link& GetClickHdl() const { return maClickHdl; }
};
#endif // _SV_BTNDLG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.320); FILE MERGED 2008/04/01 13:01:06 thb 1.2.320.2: #i85898# Stripping all external header guards 2008/03/28 15:44:09 rt 1.2.320.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: btndlg.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 _SV_BTNDLG_HXX
#define _SV_BTNDLG_HXX
#include <vcl/sv.h>
#include <vcl/dllapi.h>
#include <vcl/dialog.hxx>
struct ImplBtnDlgItem;
class ImplBtnDlgItemList;
class PushButton;
// ----------------------
// - ButtonDialog-Types -
// ----------------------
#define BUTTONDIALOG_BUTTON_NOTFOUND ((USHORT)0xFFFF)
#define BUTTONDIALOG_DEFBUTTON ((USHORT)0x0001)
#define BUTTONDIALOG_OKBUTTON ((USHORT)0x0002)
#define BUTTONDIALOG_CANCELBUTTON ((USHORT)0x0004)
#define BUTTONDIALOG_HELPBUTTON ((USHORT)0x0008)
#define BUTTONDIALOG_FOCUSBUTTON ((USHORT)0x0010)
// ----------------
// - ButtonDialog -
// ----------------
class VCL_DLLPUBLIC ButtonDialog : public Dialog
{
private:
ImplBtnDlgItemList* mpItemList;
Size maPageSize;
Size maCtrlSize;
long mnButtonSize;
USHORT mnCurButtonId;
USHORT mnFocusButtonId;
BOOL mbFormat;
Link maClickHdl;
SAL_DLLPRIVATE void ImplInitButtonDialogData();
SAL_DLLPRIVATE PushButton* ImplCreatePushButton( USHORT nBtnFlags );
SAL_DLLPRIVATE ImplBtnDlgItem* ImplGetItem( USHORT nId ) const;
DECL_DLLPRIVATE_LINK( ImplClickHdl, PushButton* pBtn );
SAL_DLLPRIVATE void ImplPosControls();
// Copy assignment is forbidden and not implemented.
SAL_DLLPRIVATE ButtonDialog( const ButtonDialog & );
SAL_DLLPRIVATE ButtonDialog& operator=( const ButtonDialog& );
protected:
ButtonDialog( WindowType nType );
SAL_DLLPRIVATE long ImplGetButtonSize();
public:
ButtonDialog( Window* pParent, WinBits nStyle = WB_STDDIALOG );
ButtonDialog( Window* pParent, const ResId& rResId );
~ButtonDialog();
virtual void Resize();
virtual void StateChanged( StateChangedType nStateChange );
virtual void Click();
void SetPageSizePixel( const Size& rSize ) { maPageSize = rSize; }
const Size& GetPageSizePixel() const { return maPageSize; }
USHORT GetCurButtonId() const { return mnCurButtonId; }
void AddButton( const XubString& rText, USHORT nId, USHORT nBtnFlags, long nSepPixel = 0 );
void AddButton( StandardButtonType eType, USHORT nId, USHORT nBtnFlags, long nSepPixel = 0 );
void AddButton( PushButton* pBtn, USHORT nId, USHORT nBtnFlags, long nSepPixel = 0 );
void RemoveButton( USHORT nId );
void Clear();
USHORT GetButtonCount() const;
USHORT GetButtonId( USHORT nButton ) const;
PushButton* GetPushButton( USHORT nId ) const;
void SetButtonText( USHORT nId, const XubString& rText );
XubString GetButtonText( USHORT nId ) const;
void SetButtonHelpText( USHORT nId, const XubString& rText );
XubString GetButtonHelpText( USHORT nId ) const;
void SetButtonHelpId( USHORT nId, ULONG nHelpId );
ULONG GetButtonHelpId( USHORT nId ) const;
void SetFocusButton( USHORT nId = BUTTONDIALOG_BUTTON_NOTFOUND ) { mnFocusButtonId = nId; }
USHORT GetFocusButton() const { return mnFocusButtonId; }
void SetClickHdl( const Link& rLink ) { maClickHdl = rLink; }
const Link& GetClickHdl() const { return maClickHdl; }
};
#endif // _SV_BTNDLG_HXX
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkRefCnt.h"
#include "include/core/SkTypes.h"
#include "src/core/SkArenaAlloc.h"
#include "tests/Test.h"
#include <memory>
#include <new>
#include <type_traits>
namespace {
static int created, destroyed;
struct Foo {
Foo() : x(-2), y(-3.0f) { created++; }
Foo(int X, float Y) : x(X), y(Y) { created++; }
~Foo() { destroyed++; }
int x;
float y;
};
struct Big {
Big() {}
uint32_t array[128];
};
struct Node {
Node(Node* n) : next(n) { created++; }
~Node() {
destroyed++;
if (next) {
next->~Node();
}
}
Node *next;
};
struct Start {
~Start() {
if (start) {
start->~Node();
}
}
Node* start;
};
struct FooRefCnt : public SkRefCnt {
FooRefCnt() : x(-2), y(-3.0f) { created++; }
FooRefCnt(int X, float Y) : x(X), y(Y) { created++; }
~FooRefCnt() override { destroyed++; }
int x;
float y;
};
} // namespace
struct WithDtor {
~WithDtor() { }
};
struct alignas(8) OddAlignment {
char buf[10];
};
DEF_TEST(ArenaAlloc, r) {
{
created = 0;
destroyed = 0;
SkArenaAlloc arena{0};
REPORTER_ASSERT(r, *arena.make<int>(3) == 3);
Foo* foo = arena.make<Foo>(3, 4.0f);
REPORTER_ASSERT(r, foo->x == 3);
REPORTER_ASSERT(r, foo->y == 4.0f);
REPORTER_ASSERT(r, created == 1);
REPORTER_ASSERT(r, destroyed == 0);
arena.makeArrayDefault<int>(10);
int* zeroed = arena.makeArray<int>(10);
for (int i = 0; i < 10; i++) {
REPORTER_ASSERT(r, zeroed[i] == 0);
}
Foo* fooArray = arena.makeArrayDefault<Foo>(10);
REPORTER_ASSERT(r, fooArray[3].x == -2);
REPORTER_ASSERT(r, fooArray[4].y == -3.0f);
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 0);
arena.make<OddAlignment>();
}
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 11);
{
created = 0;
destroyed = 0;
SkSTArenaAlloc<64> arena;
REPORTER_ASSERT(r, *arena.make<int>(3) == 3);
Foo* foo = arena.make<Foo>(3, 4.0f);
REPORTER_ASSERT(r, foo->x == 3);
REPORTER_ASSERT(r, foo->y == 4.0f);
REPORTER_ASSERT(r, created == 1);
REPORTER_ASSERT(r, destroyed == 0);
arena.makeArrayDefault<int>(10);
int* zeroed = arena.makeArray<int>(10);
for (int i = 0; i < 10; i++) {
REPORTER_ASSERT(r, zeroed[i] == 0);
}
Foo* fooArray = arena.makeArrayDefault<Foo>(10);
REPORTER_ASSERT(r, fooArray[3].x == -2);
REPORTER_ASSERT(r, fooArray[4].y == -3.0f);
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 0);
arena.make<OddAlignment>();
}
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 11);
{
created = 0;
destroyed = 0;
std::unique_ptr<char[]> block{new char[1024]};
SkArenaAlloc arena{block.get(), 1024, 0};
REPORTER_ASSERT(r, *arena.make<int>(3) == 3);
Foo* foo = arena.make<Foo>(3, 4.0f);
REPORTER_ASSERT(r, foo->x == 3);
REPORTER_ASSERT(r, foo->y == 4.0f);
REPORTER_ASSERT(r, created == 1);
REPORTER_ASSERT(r, destroyed == 0);
arena.makeArrayDefault<int>(10);
int* zeroed = arena.makeArray<int>(10);
for (int i = 0; i < 10; i++) {
REPORTER_ASSERT(r, zeroed[i] == 0);
}
Foo* fooArray = arena.makeArrayDefault<Foo>(10);
REPORTER_ASSERT(r, fooArray[3].x == -2);
REPORTER_ASSERT(r, fooArray[4].y == -3.0f);
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 0);
arena.make<OddAlignment>();
}
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 11);
{
SkSTArenaAllocWithReset<64> arena;
arena.makeArrayDefault<char>(256);
arena.reset();
arena.reset();
}
{
created = 0;
destroyed = 0;
SkSTArenaAlloc<64> arena;
Start start;
Node* current = nullptr;
for (int i = 0; i < 128; i++) {
uint64_t* temp = arena.makeArrayDefault<uint64_t>(sizeof(Node) / sizeof(Node*));
current = new (temp)Node(current);
}
start.start = current;
}
{
SkSTArenaAlloc<64> arena;
auto a = arena.makeInitializedArray<int>(8, [](size_t i ) { return i; });
for (size_t i = 0; i < 8; i++) {
REPORTER_ASSERT(r, a[i] == (int)i);
}
}
REPORTER_ASSERT(r, created == 128);
REPORTER_ASSERT(r, destroyed == 128);
{
SkArenaAlloc arena(4096);
arena.makeBytesAlignedTo(4081, 8);
}
}
<commit_msg>cleanup SkArenaAlloc tests<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkRefCnt.h"
#include "include/core/SkTypes.h"
#include "src/core/SkArenaAlloc.h"
#include "tests/Test.h"
#include <memory>
#include <new>
#include <type_traits>
DEF_TEST(ArenaAlloc, r) {
static int created = 0,
destroyed = 0;
struct Foo {
Foo() : x(-2), y(-3.0f) { created++; }
Foo(int X, float Y) : x(X), y(Y) { created++; }
~Foo() { destroyed++; }
int x;
float y;
};
struct alignas(8) OddAlignment {
char buf[10];
};
created = 0;
destroyed = 0;
{
SkArenaAlloc arena{0};
REPORTER_ASSERT(r, *arena.make<int>(3) == 3);
Foo* foo = arena.make<Foo>(3, 4.0f);
REPORTER_ASSERT(r, foo->x == 3);
REPORTER_ASSERT(r, foo->y == 4.0f);
REPORTER_ASSERT(r, created == 1);
REPORTER_ASSERT(r, destroyed == 0);
arena.makeArrayDefault<int>(10);
int* zeroed = arena.makeArray<int>(10);
for (int i = 0; i < 10; i++) {
REPORTER_ASSERT(r, zeroed[i] == 0);
}
Foo* fooArray = arena.makeArrayDefault<Foo>(10);
REPORTER_ASSERT(r, fooArray[3].x == -2);
REPORTER_ASSERT(r, fooArray[4].y == -3.0f);
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 0);
arena.make<OddAlignment>();
}
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 11);
created = 0;
destroyed = 0;
{
SkSTArenaAlloc<64> arena;
REPORTER_ASSERT(r, *arena.make<int>(3) == 3);
Foo* foo = arena.make<Foo>(3, 4.0f);
REPORTER_ASSERT(r, foo->x == 3);
REPORTER_ASSERT(r, foo->y == 4.0f);
REPORTER_ASSERT(r, created == 1);
REPORTER_ASSERT(r, destroyed == 0);
arena.makeArrayDefault<int>(10);
int* zeroed = arena.makeArray<int>(10);
for (int i = 0; i < 10; i++) {
REPORTER_ASSERT(r, zeroed[i] == 0);
}
Foo* fooArray = arena.makeArrayDefault<Foo>(10);
REPORTER_ASSERT(r, fooArray[3].x == -2);
REPORTER_ASSERT(r, fooArray[4].y == -3.0f);
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 0);
arena.make<OddAlignment>();
}
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 11);
created = 0;
destroyed = 0;
{
std::unique_ptr<char[]> block{new char[1024]};
SkArenaAlloc arena{block.get(), 1024, 0};
REPORTER_ASSERT(r, *arena.make<int>(3) == 3);
Foo* foo = arena.make<Foo>(3, 4.0f);
REPORTER_ASSERT(r, foo->x == 3);
REPORTER_ASSERT(r, foo->y == 4.0f);
REPORTER_ASSERT(r, created == 1);
REPORTER_ASSERT(r, destroyed == 0);
arena.makeArrayDefault<int>(10);
int* zeroed = arena.makeArray<int>(10);
for (int i = 0; i < 10; i++) {
REPORTER_ASSERT(r, zeroed[i] == 0);
}
Foo* fooArray = arena.makeArrayDefault<Foo>(10);
REPORTER_ASSERT(r, fooArray[3].x == -2);
REPORTER_ASSERT(r, fooArray[4].y == -3.0f);
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 0);
arena.make<OddAlignment>();
}
REPORTER_ASSERT(r, created == 11);
REPORTER_ASSERT(r, destroyed == 11);
{
SkSTArenaAllocWithReset<64> arena;
arena.makeArrayDefault<char>(256);
arena.reset();
arena.reset();
}
// Make sure that multiple blocks are handled correctly.
created = 0;
destroyed = 0;
{
struct Node {
Node(Node* n) : next(n) { created++; }
~Node() { destroyed++; }
Node *next;
char filler[64];
};
SkSTArenaAlloc<64> arena;
Node* current = nullptr;
for (int i = 0; i < 128; i++) {
current = arena.make<Node>(current);
}
}
REPORTER_ASSERT(r, created == 128);
REPORTER_ASSERT(r, destroyed == 128);
// Make sure that objects and blocks are destroyed in the correct order. If they are not,
// then there will be a use after free error in asan.
created = 0;
destroyed = 0;
{
struct Node {
Node(Node* n) : next(n) { created++; }
~Node() {
destroyed++;
if (next) {
next->~Node();
}
}
Node *next;
};
SkSTArenaAlloc<64> arena;
Node* current = nullptr;
for (int i = 0; i < 128; i++) {
uint64_t* temp = arena.makeArrayDefault<uint64_t>(sizeof(Node) / sizeof(Node*));
current = new (temp)Node(current);
}
current->~Node();
}
REPORTER_ASSERT(r, created == 128);
REPORTER_ASSERT(r, destroyed == 128);
{
SkSTArenaAlloc<64> arena;
auto a = arena.makeInitializedArray<int>(8, [](size_t i ) { return i; });
for (size_t i = 0; i < 8; i++) {
REPORTER_ASSERT(r, a[i] == (int)i);
}
}
{
SkArenaAlloc arena(4096);
// Move to a 1 character boundary.
arena.make<char>();
// Allocate something with interesting alignment.
void* ptr = arena.makeBytesAlignedTo(4081, 8);
REPORTER_ASSERT(r, ((intptr_t)ptr & 7) == 0);
}
}
<|endoftext|> |
<commit_before>/**
* kunittest.cpp
*
* Copyright (C) 2004 Zack Rusin <zack@kde.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "kunittest.h"
#include "staticunittest.h"
#include "hashunittest.h"
#include "bigintunittest.h"
#include "qtester.h"
#include "tester.h"
#include <qapplication.h>
#include <qtimer.h>
#include <iostream>
using namespace std;
void KUnitTest::registerTests()
{
ADD_TEST( StaticUnitTest );
ADD_TEST( HashUnitTest );
ADD_TEST( BigIntUnitTest );
}
KUnitTest::KUnitTest()
{
QTimer::singleShot( 0, this, SLOT(checkRun()) );
registerTests();
}
void KUnitTest::checkRun()
{
if ( m_qtests.isEmpty() )
qApp->exit();
}
int KUnitTest::runTests()
{
int result = 0;
int globalSteps = 0;
int globalPasses = 0;
int globalFails = 0;
int globalXFails = 0;
int globalXPasses = 0;
int globalSkipped = 0;
cout << "# Running normal tests... #" << endl << endl;
QAsciiDictIterator<Tester> it( m_tests );
for( ; it.current(); ++it ) {
Tester* test = it.current();
test->allTests();
QStringList errorList = test->errorList();
QStringList xfailList = test->xfailList();
QStringList xpassList = test->xpassList();
QStringList skipList = test->skipList();
cout << it.currentKey() << " - ";
if ( !errorList.empty() || !xfailList.empty() ) {
++result;
int numPass = test->testsFinished() - ( test->testsFailed() + test->testsXFail() );
globalSteps += test->testsFinished();
globalPasses += numPass;
int numFail = test->testsFailed() + test->testsXFail();
globalFails += numFail;
int numXFail = test->testsXFail();
globalXFails += numXFail;
globalXPasses += test->testsXPass();
cout << numPass << " test" << ( ( 1 == numPass )?"":"s") << " passed ";
if ( 0 < test->testsXPass() ) {
cout << "(" << test->testsXPass() << " unexpected pass" << ( ( 1 == test->testsXPass() )?"":"es") << ")";
}
cout << ", " << numFail << " test" << ( ( 1 == numFail )?"":"s") << " failed";
if ( 0 < numXFail ) {
cout << " (" << numXFail << " expected failure" << ( ( 1 == numXFail )?"":"s") << ")";
}
cout << endl;
if ( 0 < test->testsXPass() ) {
cout << " Unexpected pass" << ( ( 1 == test->testsXPass() )?"":"es") << ":" << endl;
for ( QStringList::Iterator itr = xpassList.begin(); itr != xpassList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
if ( !errorList.empty() ) {
cout << " Unexpected failure" << ( ( 1 == test->testsFailed() )?"":"s") << ":" << endl;
for ( QStringList::Iterator itr = errorList.begin(); itr != errorList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
if ( 0 < numXFail ) {
cout << " Expected failure" << ( ( 1 == numXFail)?"":"s") << ":" << endl;
for ( QStringList::Iterator itr = xfailList.begin(); itr != xfailList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
} else {
// then we are dealing with no failures, but perhaps some skipped
int numSkipped = test->testsSkipped();
int numPass = test->testsFinished() - numSkipped;
cout << numPass << " test" << ((1 == numPass)?",":"s, all") << " passed";
globalPasses += numPass;
globalSkipped += numSkipped;
globalSteps += test->testsFinished();
if ( 0 < test->testsXPass() ) {
cout << " (" << test->testsXPass() << " unexpected pass" << ( ( 1 == test->testsXPass() )?"":"es") << ")";
globalXPasses += test->testsXPass();
}
if ( 0 < numSkipped ) {
cout << "; also " << numSkipped << " skipped";
}
cout << endl;
if ( 0 < test->testsXPass() ) {
cout << " Unexpected pass" << ( ( 1 == test->testsXPass() )?"":"es") << ":" << endl;
for ( QStringList::Iterator itr = xpassList.begin(); itr != xpassList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
if ( 0 < numSkipped ) {
cout << " Skipped test" << ( ( 1 == numSkipped )?"":"s") << ":" << endl;
for ( QStringList::Iterator itr = skipList.begin(); itr != skipList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
}
cout << endl;
}
cout << "# Done with normal tests:" << endl;
cout << " Total test cases: " << m_tests.count() << endl;
cout << " Total test steps : " << globalSteps << endl;
cout << " Total passed test steps (including unexpected) : " << globalPasses << endl;
cout << " Total unexpected passed test steps : " << globalXPasses << endl;
cout << " Total failed test steps (including expected) : " << globalFails << endl;
cout << " Total expected failed test steps : " << globalXFails << endl;
cout << " Total skipped test steps : " << globalSkipped << endl;
return result;
}
void KUnitTest::addTester( QTester *test )
{
m_qtests.insert( test, test );
connect( test, SIGNAL(destroyed(QObject*)),
SLOT(qtesterDone(QObject* )) );
}
void KUnitTest::qtesterDone( QObject *obj )
{
m_qtests.remove( obj );
if ( m_qtests.isEmpty() )
qApp->quit();
}
// #include "kunittest.moc"
<commit_msg>Delete the unittest list. This helps to reduce the noise when using valgrind on the tests.<commit_after>/**
* kunittest.cpp
*
* Copyright (C) 2004 Zack Rusin <zack@kde.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "kunittest.h"
#include "staticunittest.h"
#include "hashunittest.h"
#include "bigintunittest.h"
#include "qtester.h"
#include "tester.h"
#include <qapplication.h>
#include <qtimer.h>
#include <iostream>
using namespace std;
void KUnitTest::registerTests()
{
ADD_TEST( StaticUnitTest );
ADD_TEST( HashUnitTest );
ADD_TEST( BigIntUnitTest );
}
KUnitTest::KUnitTest()
{
QTimer::singleShot( 0, this, SLOT(checkRun()) );
m_tests.setAutoDelete( TRUE );
m_qtests.setAutoDelete( TRUE );
registerTests();
}
void KUnitTest::checkRun()
{
if ( m_qtests.isEmpty() )
qApp->exit();
}
int KUnitTest::runTests()
{
int result = 0;
int globalSteps = 0;
int globalPasses = 0;
int globalFails = 0;
int globalXFails = 0;
int globalXPasses = 0;
int globalSkipped = 0;
cout << "# Running normal tests... #" << endl << endl;
QAsciiDictIterator<Tester> it( m_tests );
for( ; it.current(); ++it ) {
Tester* test = it.current();
test->allTests();
QStringList errorList = test->errorList();
QStringList xfailList = test->xfailList();
QStringList xpassList = test->xpassList();
QStringList skipList = test->skipList();
cout << it.currentKey() << " - ";
if ( !errorList.empty() || !xfailList.empty() ) {
++result;
int numPass = test->testsFinished() - ( test->testsFailed() + test->testsXFail() );
globalSteps += test->testsFinished();
globalPasses += numPass;
int numFail = test->testsFailed() + test->testsXFail();
globalFails += numFail;
int numXFail = test->testsXFail();
globalXFails += numXFail;
globalXPasses += test->testsXPass();
cout << numPass << " test" << ( ( 1 == numPass )?"":"s") << " passed ";
if ( 0 < test->testsXPass() ) {
cout << "(" << test->testsXPass() << " unexpected pass" << ( ( 1 == test->testsXPass() )?"":"es") << ")";
}
cout << ", " << numFail << " test" << ( ( 1 == numFail )?"":"s") << " failed";
if ( 0 < numXFail ) {
cout << " (" << numXFail << " expected failure" << ( ( 1 == numXFail )?"":"s") << ")";
}
cout << endl;
if ( 0 < test->testsXPass() ) {
cout << " Unexpected pass" << ( ( 1 == test->testsXPass() )?"":"es") << ":" << endl;
for ( QStringList::Iterator itr = xpassList.begin(); itr != xpassList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
if ( !errorList.empty() ) {
cout << " Unexpected failure" << ( ( 1 == test->testsFailed() )?"":"s") << ":" << endl;
for ( QStringList::Iterator itr = errorList.begin(); itr != errorList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
if ( 0 < numXFail ) {
cout << " Expected failure" << ( ( 1 == numXFail)?"":"s") << ":" << endl;
for ( QStringList::Iterator itr = xfailList.begin(); itr != xfailList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
} else {
// then we are dealing with no failures, but perhaps some skipped
int numSkipped = test->testsSkipped();
int numPass = test->testsFinished() - numSkipped;
cout << numPass << " test" << ((1 == numPass)?",":"s, all") << " passed";
globalPasses += numPass;
globalSkipped += numSkipped;
globalSteps += test->testsFinished();
if ( 0 < test->testsXPass() ) {
cout << " (" << test->testsXPass() << " unexpected pass" << ( ( 1 == test->testsXPass() )?"":"es") << ")";
globalXPasses += test->testsXPass();
}
if ( 0 < numSkipped ) {
cout << "; also " << numSkipped << " skipped";
}
cout << endl;
if ( 0 < test->testsXPass() ) {
cout << " Unexpected pass" << ( ( 1 == test->testsXPass() )?"":"es") << ":" << endl;
for ( QStringList::Iterator itr = xpassList.begin(); itr != xpassList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
if ( 0 < numSkipped ) {
cout << " Skipped test" << ( ( 1 == numSkipped )?"":"s") << ":" << endl;
for ( QStringList::Iterator itr = skipList.begin(); itr != skipList.end(); ++itr ) {
cout << "\t" << (*itr).latin1() << endl;
}
}
}
cout << endl;
}
cout << "# Done with normal tests:" << endl;
cout << " Total test cases: " << m_tests.count() << endl;
cout << " Total test steps : " << globalSteps << endl;
cout << " Total passed test steps (including unexpected) : " << globalPasses << endl;
cout << " Total unexpected passed test steps : " << globalXPasses << endl;
cout << " Total failed test steps (including expected) : " << globalFails << endl;
cout << " Total expected failed test steps : " << globalXFails << endl;
cout << " Total skipped test steps : " << globalSkipped << endl;
return result;
}
void KUnitTest::addTester( QTester *test )
{
m_qtests.insert( test, test );
connect( test, SIGNAL(destroyed(QObject*)),
SLOT(qtesterDone(QObject* )) );
}
void KUnitTest::qtesterDone( QObject *obj )
{
m_qtests.remove( obj );
if ( m_qtests.isEmpty() )
qApp->quit();
}
// #include "kunittest.moc"
<|endoftext|> |
<commit_before>#include "MarginManager.h"
#include <algorithm>
NotifyCategoryDef(MarginManager, "");
TypeHandle MarginManager::_type_handle;
MarginManager* MarginManager::_global_ptr = nullptr;
MarginManager::MarginManager() : PandaNode("mrmanager") {
MarginManager_cat.debug() << "__init__()" << std::endl;
}
MarginManager::~MarginManager() {
}
void MarginManager::set_cell_available(int cell_index, bool available) {
MarginManager_cat.debug() << "set_cell_available(" << cell_index << " " << available << ")" << std::endl;
MarginCell* cell = m_cells.at(cell_index);
if ((cell == nullptr) || (cell == NULL)) {
return;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return;
cell->set_available(available);
reorganize();
}
void MarginManager::set_cell_available(MarginCell* cell, bool available) {
MarginManager_cat.debug() << "set_cell_available(" << "MarginCell cell" << " " << available << ")" << std::endl;
if ((cell == nullptr) || (cell == NULL)) {
return;
}
cell->set_available(available);
reorganize();
}
void MarginManager::remove_cell(int cell_index) {
MarginManager_cat.debug() << "remove_cell(" << cell_index << ")" << std::endl;
MarginCell* cell = m_cells.at(cell_index);
if ((cell == nullptr) || (cell == NULL)) {
return;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return;
m_cells.erase(it);
reorganize();
}
void MarginManager::remove_cell(MarginCell* cell) {
MarginManager_cat.debug() << "remove_cell(MarginCell cell)" << std::endl;
if ((cell == nullptr) || (cell == NULL)) {
return;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return;
m_cells.erase(it);
reorganize();
}
void MarginManager::add_visible_popup(MarginPopup* popup) {
MarginManager_cat.debug() << "add_visible_popup(MarginPopup popup)" << std::endl;
if ((popup == nullptr) || (popup == NULL)) {
return;
}
m_popups.push_back(popup);
reorganize();
}
void MarginManager::remove_visible_popup(MarginPopup* popup) {
MarginManager_cat.debug() << "remove_visible_popup(MarginPopup popup)" << std::endl;
if ((popup == nullptr) || (popup == NULL)) {
return;
}
popup_vec_t::iterator it = std::find(m_popups.begin(), m_popups.end(), popup);
if (it == m_popups.end())
return;
m_popups.erase(it);
reorganize();
}
void MarginManager::reorganize() {
MarginManager_cat.debug() << "reorganize()" << std::endl;
cell_vec_t active_cells;
for (cell_vec_t::iterator it = m_cells.begin(); it != m_cells.end(); ++it) {
if ((*it)->is_available())
active_cells.push_back(*it);
}
popup_vec_t popups = m_popups;
std::sort(popups.begin(), popups.end(), _sort_key);
popups.resize(active_cells.size());
cell_vec_t free_cells;
for (cell_vec_t::iterator it = active_cells.begin(); it != active_cells.end(); ++it) {
MarginCell* cell = *it;
if (cell != nullptr && cell != NULL) {
if (!cell->has_content()) {
free_cells.push_back(cell);
} else if (std::find(popups.begin(), popups.end(), cell->get_content()) != popups.end()) {
popups.erase(std::find(popups.begin(), popups.end(), cell->get_content()));
} else {
cell->set_content(nullptr);
free_cells.push_back(cell);
}
}
}
assert(free_cells.size() >= popups.size());
std::random_shuffle(free_cells.begin(), free_cells.end());
for (popup_vec_t::const_iterator it = popups.begin(); it != popups.end(); it++) {
MarginPopup* popup = *it;
if (popup != nullptr && popup != NULL) {
MarginCell* last_cell = popup->get_last_cell();
if (last_cell != nullptr && last_cell != NULL && std::find(free_cells.begin(), free_cells.end(), last_cell) != free_cells.end() && last_cell->is_free()) {
last_cell->set_content(popup);
free_cells.erase(std::find(free_cells.begin(), free_cells.end(), last_cell));
} else {
free_cells.back()->set_content(popup);
free_cells.pop_back();
}
}
}
}
MarginCell* MarginManager::add_grid_cell(float x, float y, float left, float right, float bottom, float top) {
MarginManager_cat.debug() << "add_grid_cell(" << x << " " << y << " " << left << " " << right << " " << bottom << " " << top << ")" << std::endl;
double v7; // st7@1 MAPDST
double v8; // st5@1 MAPDST
double v12; // st6@1 MAPDST
float f_top; // ST0C_4@1
float f_bottom; // ST08_4@1
float f_right; // ST04_4@1
float v17; // [sp+1Ch] [bp+Ch]@1 MAPDST
float f_left; // [sp+20h] [bp+10h]@1 MAPDST
v7 = left;
f_left = right - left;
v17 = f_left / 6.0;
f_left = top - bottom;
f_left = f_left / 6.0;
v8 = v7 + v17 * x;
v7 = v17;
v17 = v8;
v12 = f_left;
f_left = bottom + f_left * y;
v8 = v12 + f_left;
v12 = f_left;
f_left = v8;
f_left = f_left - 0.009999999776482582;
f_top = f_left;
f_left = v12 + 0.009999999776482582;
f_bottom = f_left;
f_left = v7 + v17;
f_left = f_left - 0.009999999776482582;
f_right = f_left;
f_left = v17 + 0.009999999776482582;
return add_cell(f_left, f_right, f_bottom, f_top);
}
MarginCell* MarginManager::add_cell(float left, float right, float bottom, float top) {
MarginManager_cat.debug() << "add_cell(" << left << " " << right << " " << bottom << " " << top << ")" << std::endl;
float padding = .125;
float scale = .2;
float x_start = left + scale / 2. + padding;
float y_start = bottom + scale / 2. + padding;
float x_end = right - scale / 2. - padding;
float y_end = top - scale / 2. - padding;
float x_inc = (x_end - x_start) / 5.;
float y_inc = (y_end - y_start) / 3.5;
float x2 = x_start + x_inc;
float y2 = y_start + y_inc;
MarginCell* cell = new MarginCell(this);
cell->reparent_to(NodePath(this->get_parent(0)));
cell->set_scale(scale);
cell->set_pos(x2, 0, y2);
cell->set_available(true);
m_cells.push_back(cell);
reorganize();
return cell;
}
bool MarginManager::_sort_key(MarginPopup* lhs, MarginPopup* rhs) {
MarginManager_cat.debug() << "_sort_key(MarginPopup lhs, MarginPopup rhs)" << std::endl;
if (((lhs == nullptr) || (rhs == nullptr)) || ((lhs == NULL) || (rhs == NULL))) {
return false;
}
return lhs->get_priority() < rhs->get_priority();
}
bool MarginManager::get_cell_available(int cell_index) {
MarginManager_cat.debug() << "get_cell_available(" << cell_index << ")" << std::endl;
MarginCell* cell = m_cells.at(cell_index);
if ((cell == nullptr) || (cell == NULL)) {
return false;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return false;
return cell->get_available();
}
bool MarginManager::get_cell_available(MarginCell* cell) {
MarginManager_cat.debug() << "get_cell_available(MarginCell cell)" << std::endl;
if ((cell == nullptr) || (cell == NULL)) {
return false;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return false;
return cell->get_available();
}
MarginManager* MarginManager::get_global_ptr() {
if ((_global_ptr == nullptr) || (_global_ptr == NULL)) {
_global_ptr = new MarginManager;
}
return _global_ptr;
}<commit_msg>Simplify add_grid_cell<commit_after>#include "MarginManager.h"
#include <algorithm>
NotifyCategoryDef(MarginManager, "");
TypeHandle MarginManager::_type_handle;
MarginManager* MarginManager::_global_ptr = nullptr;
MarginManager::MarginManager() : PandaNode("mrmanager") {
MarginManager_cat.debug() << "__init__()" << std::endl;
}
MarginManager::~MarginManager() {
}
void MarginManager::set_cell_available(int cell_index, bool available) {
MarginManager_cat.debug() << "set_cell_available(" << cell_index << " " << available << ")" << std::endl;
MarginCell* cell = m_cells.at(cell_index);
if ((cell == nullptr) || (cell == NULL)) {
return;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return;
cell->set_available(available);
reorganize();
}
void MarginManager::set_cell_available(MarginCell* cell, bool available) {
MarginManager_cat.debug() << "set_cell_available(" << "MarginCell cell" << " " << available << ")" << std::endl;
if ((cell == nullptr) || (cell == NULL)) {
return;
}
cell->set_available(available);
reorganize();
}
void MarginManager::remove_cell(int cell_index) {
MarginManager_cat.debug() << "remove_cell(" << cell_index << ")" << std::endl;
MarginCell* cell = m_cells.at(cell_index);
if ((cell == nullptr) || (cell == NULL)) {
return;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return;
m_cells.erase(it);
reorganize();
}
void MarginManager::remove_cell(MarginCell* cell) {
MarginManager_cat.debug() << "remove_cell(MarginCell cell)" << std::endl;
if ((cell == nullptr) || (cell == NULL)) {
return;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return;
m_cells.erase(it);
reorganize();
}
void MarginManager::add_visible_popup(MarginPopup* popup) {
MarginManager_cat.debug() << "add_visible_popup(MarginPopup popup)" << std::endl;
if ((popup == nullptr) || (popup == NULL)) {
return;
}
m_popups.push_back(popup);
reorganize();
}
void MarginManager::remove_visible_popup(MarginPopup* popup) {
MarginManager_cat.debug() << "remove_visible_popup(MarginPopup popup)" << std::endl;
if ((popup == nullptr) || (popup == NULL)) {
return;
}
popup_vec_t::iterator it = std::find(m_popups.begin(), m_popups.end(), popup);
if (it == m_popups.end())
return;
m_popups.erase(it);
reorganize();
}
void MarginManager::reorganize() {
MarginManager_cat.debug() << "reorganize()" << std::endl;
cell_vec_t active_cells;
for (cell_vec_t::iterator it = m_cells.begin(); it != m_cells.end(); ++it) {
if ((*it)->is_available())
active_cells.push_back(*it);
}
popup_vec_t popups = m_popups;
std::sort(popups.begin(), popups.end(), _sort_key);
popups.resize(active_cells.size());
cell_vec_t free_cells;
for (cell_vec_t::iterator it = active_cells.begin(); it != active_cells.end(); ++it) {
MarginCell* cell = *it;
if (cell != nullptr && cell != NULL) {
if (!cell->has_content()) {
free_cells.push_back(cell);
} else if (std::find(popups.begin(), popups.end(), cell->get_content()) != popups.end()) {
popups.erase(std::find(popups.begin(), popups.end(), cell->get_content()));
} else {
cell->set_content(nullptr);
free_cells.push_back(cell);
}
}
}
assert(free_cells.size() >= popups.size());
std::random_shuffle(free_cells.begin(), free_cells.end());
for (popup_vec_t::const_iterator it = popups.begin(); it != popups.end(); it++) {
MarginPopup* popup = *it;
if (popup != nullptr && popup != NULL) {
MarginCell* last_cell = popup->get_last_cell();
if (last_cell != nullptr && last_cell != NULL && std::find(free_cells.begin(), free_cells.end(), last_cell) != free_cells.end() && last_cell->is_free()) {
last_cell->set_content(popup);
free_cells.erase(std::find(free_cells.begin(), free_cells.end(), last_cell));
} else {
free_cells.back()->set_content(popup);
free_cells.pop_back();
}
}
}
}
MarginCell* MarginManager::add_grid_cell(float x, float y, float left, float right, float bottom, float top) {
MarginManager_cat.debug() << "add_grid_cell(" << x << " " << y << " " << left << " " << right << " " << bottom << " " << top << ")" << std::endl;
float f_top;
float f_bottom;
float f_right;
float f_left;
f_top = ((bottom + ((top - bottom) / 6.0) * y) * 2) - 0x2386F2626E6516;
f_bottom = ((bottom + ((top - bottom) / 6.0) * y) * 2) + 0x2386F2626E6516;
f_right = ((right - left) / 6.0) + (left + ((right - left) / 6.0) * x) - 0x2386F2626E6516;
f_left = (left + ((right - left) / 6.0) * x) + 0x2386F2626E6516;
return add_cell(f_left, f_right, f_bottom, f_top);
}
MarginCell* MarginManager::add_cell(float left, float right, float bottom, float top) {
MarginManager_cat.debug() << "add_cell(" << left << " " << right << " " << bottom << " " << top << ")" << std::endl;
float padding = .125;
float scale = .2;
float x_start = left + scale / 2. + padding;
float y_start = bottom + scale / 2. + padding;
float x_end = right - scale / 2. - padding;
float y_end = top - scale / 2. - padding;
float x_inc = (x_end - x_start) / 5.;
float y_inc = (y_end - y_start) / 3.5;
float x2 = x_start + x_inc;
float y2 = y_start + y_inc;
MarginCell* cell = new MarginCell(this);
cell->reparent_to(NodePath(this->get_parent(0)));
cell->set_scale(scale);
cell->set_pos(x2, 0, y2);
cell->set_available(true);
m_cells.push_back(cell);
reorganize();
return cell;
}
bool MarginManager::_sort_key(MarginPopup* lhs, MarginPopup* rhs) {
MarginManager_cat.debug() << "_sort_key(MarginPopup lhs, MarginPopup rhs)" << std::endl;
if (((lhs == nullptr) || (rhs == nullptr)) || ((lhs == NULL) || (rhs == NULL))) {
return false;
}
return lhs->get_priority() < rhs->get_priority();
}
bool MarginManager::get_cell_available(int cell_index) {
MarginManager_cat.debug() << "get_cell_available(" << cell_index << ")" << std::endl;
MarginCell* cell = m_cells.at(cell_index);
if ((cell == nullptr) || (cell == NULL)) {
return false;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return false;
return cell->get_available();
}
bool MarginManager::get_cell_available(MarginCell* cell) {
MarginManager_cat.debug() << "get_cell_available(MarginCell cell)" << std::endl;
if ((cell == nullptr) || (cell == NULL)) {
return false;
}
cell_vec_t::iterator it = std::find(m_cells.begin(), m_cells.end(), cell);
if (it == m_cells.end())
return false;
return cell->get_available();
}
MarginManager* MarginManager::get_global_ptr() {
if ((_global_ptr == nullptr) || (_global_ptr == NULL)) {
_global_ptr = new MarginManager;
}
return _global_ptr;
}<|endoftext|> |
<commit_before>/*
Resembla
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RESEMBLA_LETTER_WEIGHT_HPP
#define RESEMBLA_LETTER_WEIGHT_HPP
#include <string>
#include <exception>
#include <unordered_map>
#include "../string_util.hpp"
#include "../csv_reader.hpp"
namespace resembla {
// simple weight function for sets of letters
template<typename string_type>
struct LetterWeight
{
using value_type = typename string_type::value_type;
LetterWeight(double base_weight, double delete_insert_ratio, const std::string& letter_weight_file_path):
base_weight(base_weight), delete_insert_ratio(delete_insert_ratio)
{
if(letter_weight_file_path.empty()){
return;
}
for(const auto& columns: CsvReader<>(letter_weight_file_path, 2)){
auto letters = cast_string<string_type>(columns[0]);
auto weight = std::stod(columns[1]);
for(auto c: letters){
letter_weights[c] = weight;
}
}
}
double operator()(const value_type c, bool is_original = false, size_t total = -1, size_t position = -1) const
{
(void)total;
(void)position;
double w = base_weight;
if(is_original){
w *= delete_insert_ratio;
}
auto p = letter_weights.find(c);
if(p != std::end(letter_weights)){
w *= p->second;
}
return w;
}
protected:
double base_weight;
double delete_insert_ratio;
std::unordered_map<value_type, double> letter_weights;
};
}
#endif
<commit_msg>delete unused includes<commit_after>/*
Resembla
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RESEMBLA_LETTER_WEIGHT_HPP
#define RESEMBLA_LETTER_WEIGHT_HPP
#include <string>
#include <unordered_map>
#include "../string_util.hpp"
#include "../csv_reader.hpp"
namespace resembla {
// simple weight function for sets of letters
template<typename string_type>
struct LetterWeight
{
using value_type = typename string_type::value_type;
LetterWeight(double base_weight, double delete_insert_ratio,
const std::string& letter_weight_file_path):
base_weight(base_weight), delete_insert_ratio(delete_insert_ratio)
{
if(letter_weight_file_path.empty()){
return;
}
for(const auto& columns: CsvReader<>(letter_weight_file_path, 2)){
auto letters = cast_string<string_type>(columns[0]);
auto weight = std::stod(columns[1]);
for(auto c: letters){
letter_weights[c] = weight;
}
}
}
double operator()(const value_type c, bool is_original = false,
size_t total = -1, size_t position = -1) const
{
(void)total;
(void)position;
double w = base_weight;
if(is_original){
w *= delete_insert_ratio;
}
auto p = letter_weights.find(c);
if(p != std::end(letter_weights)){
w *= p->second;
}
return w;
}
protected:
double base_weight;
double delete_insert_ratio;
std::unordered_map<value_type, double> letter_weights;
};
}
#endif
<|endoftext|> |
<commit_before>#include "kwm.h"
const std::string KwmCurrentVersion = "Kwm Version 1.0.5";
const std::string PlistFile = "com.koekeishiya.kwm.plist";
CFMachPortRef EventTap;
kwm_path KWMPath = {};
kwm_code KWMCode = {};
kwm_screen KWMScreen = {};
kwm_toggles KWMToggles = {};
kwm_prefix KWMPrefix = {};
kwm_focus KWMFocus = {};
std::vector<hotkey> KwmHotkeys;
std::map<unsigned int, screen_info> DisplayMap;
std::vector<window_info> WindowLst;
std::vector<int> FloatingWindowLst;
std::vector<std::string> FloatingAppLst;
std::map<std::string, int> CapturedAppLst;
std::map<std::string, std::vector<CFTypeRef> > AllowedWindowRoles;
space_tiling_option KwmSpaceMode;
focus_option KwmFocusMode;
cycle_focus_option KwmCycleMode;
pthread_t BackgroundThread;
pthread_t DaemonThread;
pthread_mutex_t BackgroundLock;
CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
pthread_mutex_lock(&BackgroundLock);
switch(Type)
{
case kCGEventTapDisabledByTimeout:
case kCGEventTapDisabledByUserInput:
{
DEBUG("Restarting Event Tap")
CGEventTapEnable(EventTap, true);
} break;
case kCGEventKeyDown:
{
if(KWMToggles.UseBuiltinHotkeys && KwmMainHotkeyTrigger(&Event))
{
pthread_mutex_unlock(&BackgroundLock);
return NULL;
}
if(KwmFocusMode == FocusModeAutofocus)
{
CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
CGEventPostToPSN(&KWMFocus.PSN, Event);
pthread_mutex_unlock(&BackgroundLock);
return NULL;
}
} break;
case kCGEventKeyUp:
{
if(KwmFocusMode == FocusModeAutofocus)
{
CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
CGEventPostToPSN(&KWMFocus.PSN, Event);
pthread_mutex_unlock(&BackgroundLock);
return NULL;
}
} break;
case kCGEventMouseMoved:
{
if(KwmFocusMode != FocusModeDisabled)
FocusWindowBelowCursor();
} break;
case kCGEventLeftMouseDown:
{
DEBUG("Left mouse button was pressed")
FocusWindowBelowCursor();
if(KWMToggles.EnableDragAndDrop && IsCursorInsideFocusedWindow())
KWMToggles.WindowDragInProgress = true;
} break;
case kCGEventLeftMouseUp:
{
if(KWMToggles.EnableDragAndDrop && KWMToggles.WindowDragInProgress)
{
if(!IsCursorInsideFocusedWindow())
ToggleFocusedWindowFloating();
KWMToggles.WindowDragInProgress = false;
}
DEBUG("Left mouse button was released")
} break;
}
pthread_mutex_unlock(&BackgroundLock);
return Event;
}
bool KwmRunLiveCodeHotkeySystem(CGEventRef *Event, modifiers *Mod, CGKeyCode Keycode)
{
std::string NewHotkeySOFileTime = KwmGetFileTime(KWMPath.HotkeySOFullPath.c_str());
if(NewHotkeySOFileTime != "file not found" &&
NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)
{
DEBUG("Reloading hotkeys.so")
UnloadKwmCode(&KWMCode);
KWMCode = LoadKwmCode();
}
if(KWMCode.IsValid)
{
// Capture custom hotkeys specified in hotkeys.cpp
if(KWMCode.KWMHotkeyCommands(*Mod, Keycode))
return true;
// Check if key should be remapped
int NewKeycode;
KWMCode.RemapKeys(Mod, Keycode, &NewKeycode);
if(NewKeycode != -1)
{
CGEventSetFlags(*Event, 0);
if(Mod->CmdKey)
CGEventSetFlags(*Event, kCGEventFlagMaskCommand);
if(Mod->AltKey)
CGEventSetFlags(*Event, kCGEventFlagMaskAlternate);
if(Mod->CtrlKey)
CGEventSetFlags(*Event, kCGEventFlagMaskControl);
if(Mod->ShiftKey)
CGEventSetFlags(*Event, kCGEventFlagMaskShift);
CGEventSetIntegerValueField(*Event, kCGKeyboardEventKeycode, NewKeycode);
}
}
return false;
}
kwm_code LoadKwmCode()
{
kwm_code Code = {};
Code.HotkeySOFileTime = KwmGetFileTime(KWMPath.HotkeySOFullPath.c_str());
Code.KwmHotkeySO = dlopen(KWMPath.HotkeySOFullPath.c_str(), RTLD_LAZY);
if(Code.KwmHotkeySO)
{
Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "KWMHotkeyCommands");
Code.RemapKeys = (kwm_key_remap*) dlsym(Code.KwmHotkeySO, "RemapKeys");
}
else
{
DEBUG("LoadKwmCode() Could not open '" << KWMPath.HotkeySOFullPath << "'")
}
Code.IsValid = (Code.KWMHotkeyCommands && Code.RemapKeys);
return Code;
}
void UnloadKwmCode(kwm_code *Code)
{
if(Code->KwmHotkeySO)
dlclose(Code->KwmHotkeySO);
Code->HotkeySOFileTime = "";
Code->KWMHotkeyCommands = 0;
Code->RemapKeys = 0;
Code->IsValid = 0;
}
std::string KwmGetFileTime(const char *File)
{
struct stat attr;
int Result = stat(File, &attr);
if(Result == -1)
return "file not found";
return ctime(&attr.st_mtime);
}
void KwmQuit()
{
exit(0);
}
void * KwmWindowMonitor(void*)
{
while(1)
{
pthread_mutex_lock(&BackgroundLock);
UpdateWindowTree();
pthread_mutex_unlock(&BackgroundLock);
usleep(200000);
}
}
bool IsPrefixOfString(std::string &Line, std::string Prefix)
{
bool Result = false;
if(Line.substr(0, Prefix.size()) == Prefix)
{
Line = Line.substr(Prefix.size()+1);
Result = true;
}
return Result;
}
void KwmReloadConfig()
{
KwmClearSettings();
KwmExecuteConfig();
}
void KwmClearSettings()
{
std::map<std::string, std::vector<CFTypeRef> >::iterator It;
for(It = AllowedWindowRoles.begin(); It != AllowedWindowRoles.end(); ++It)
{
std::vector<CFTypeRef> &WindowRoles = It->second;
for(std::size_t RoleIndex = 0; RoleIndex < WindowRoles.size(); ++RoleIndex)
CFRelease(WindowRoles[RoleIndex]);
WindowRoles.clear();
}
FloatingAppLst.clear();
KwmHotkeys.clear();
KWMPrefix.Enabled = false;
}
void KwmExecuteConfig()
{
char *HomeP = std::getenv("HOME");
if(!HomeP)
{
DEBUG("Failed to get environment variable 'HOME'")
return;
}
KWMPath.EnvHome = HomeP;
KWMPath.ConfigFolder = ".kwm";
std::ifstream ConfigFD(KWMPath.EnvHome + "/" + KWMPath.ConfigFolder + "/" + KWMPath.ConfigFile);
if(ConfigFD.fail())
{
DEBUG("Could not open " << KWMPath.EnvHome << "/" << KWMPath.ConfigFolder << "/" << KWMPath.ConfigFile
<< ", make sure the file exists." << std::endl)
return;
}
std::string Line;
while(std::getline(ConfigFD, Line))
{
if(!Line.empty() && Line[0] != '#')
{
if(IsPrefixOfString(Line, "kwmc"))
KwmInterpretCommand(Line, 0);
else if(IsPrefixOfString(Line, "sys"))
system(Line.c_str());
}
}
}
bool IsKwmAlreadyAddedToLaunchd()
{
std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;
struct stat attr;
int Result = stat(SymlinkFullPath.c_str(), &attr);
if(Result == -1)
return false;
return true;
}
void AddKwmToLaunchd()
{
if(IsKwmAlreadyAddedToLaunchd())
return;
std::string PlistFullPath = KWMPath.FilePath + "/" + PlistFile;
std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;
std::ifstream TemplateFD(KWMPath.FilePath + "/kwm_template.plist");
if(TemplateFD.fail())
return;
std::ofstream OutFD(PlistFullPath);
if(OutFD.fail())
return;
std::string Line;
std::vector<std::string> PlistContents;
while(std::getline(TemplateFD, Line))
PlistContents.push_back(Line);
DEBUG("AddKwmToLaunchd() Creating file: " << PlistFullPath)
for(std::size_t LineNumber = 0; LineNumber < PlistContents.size(); ++LineNumber)
{
if(LineNumber == 8)
OutFD << " <string>" + KWMPath.FilePath + "/kwm</string>" << std::endl;
else
OutFD << PlistContents[LineNumber] << std::endl;
}
TemplateFD.close();
OutFD.close();
std::string PerformSymlink = "mv " + PlistFullPath + " " + SymlinkFullPath;
system(PerformSymlink.c_str());
DEBUG("AddKwmToLaunchd() Moved plist to: " << SymlinkFullPath)
}
void RemoveKwmFromLaunchd()
{
if(!IsKwmAlreadyAddedToLaunchd())
return;
std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;
std::string RemoveSymlink = "rm " + SymlinkFullPath;
system(RemoveSymlink.c_str());
DEBUG("RemoveKwmFromLaunchd() Removing file: " << SymlinkFullPath)
}
bool GetKwmFilePath()
{
bool Result = false;
char PathBuf[PROC_PIDPATHINFO_MAXSIZE];
pid_t Pid = getpid();
int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));
if (Ret > 0)
{
KWMPath.FilePath = PathBuf;
std::size_t Split = KWMPath.FilePath.find_last_of("/\\");
KWMPath.FilePath = KWMPath.FilePath.substr(0, Split);
KWMPath.HotkeySOFullPath = KWMPath.FilePath + "/hotkeys.so";
Result = true;
}
return Result;
}
void KwmInit()
{
if(!CheckPrivileges())
Fatal("Could not access OSX Accessibility!");
if (pthread_mutex_init(&BackgroundLock, NULL) != 0)
Fatal("Could not create mutex!");
if(KwmStartDaemon())
pthread_create(&DaemonThread, NULL, &KwmDaemonHandleConnectionBG, NULL);
else
Fatal("Kwm: Could not start daemon..");
KWMScreen.SplitRatio = 0.5;
KWMScreen.SplitMode = -1;
KWMScreen.MarkedWindow = -1;
KWMScreen.OldScreenID = -1;
KWMScreen.PrevSpace = -1;
KWMScreen.DefaultOffset = CreateDefaultScreenOffset();
KWMScreen.MaxCount = 5;
KWMScreen.ActiveCount = 0;
KWMScreen.UpdateSpace = true;
KWMToggles.EnableTilingMode = true;
KWMToggles.UseBuiltinHotkeys = true;
KWMToggles.EnableDragAndDrop = true;
KWMToggles.UseContextMenuFix = true;
KWMToggles.UseMouseFollowsFocus = true;
KWMToggles.WindowDragInProgress = false;
KwmSpaceMode = SpaceModeBSP;
KwmFocusMode = FocusModeAutoraise;
KwmCycleMode = CycleModeScreen;
KWMPrefix.Enabled = false;
KWMPrefix.Active = false;
KWMPrefix.Timeout = 0.75;
KWMPath.ConfigFile = "kwmrc";
if(GetKwmFilePath())
KWMCode = LoadKwmCode();
KwmExecuteConfig();
GetActiveDisplays();
pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);
}
bool CheckPrivileges()
{
bool Result = false;
const void * Keys[] = { kAXTrustedCheckOptionPrompt };
const void * Values[] = { kCFBooleanTrue };
CFDictionaryRef Options;
Options = CFDictionaryCreate(kCFAllocatorDefault,
Keys, Values, sizeof(Keys) / sizeof(*Keys),
&kCFCopyStringDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
Result = AXIsProcessTrustedWithOptions(Options);
CFRelease(Options);
return Result;
}
bool CheckArguments(int argc, char **argv)
{
bool Result = false;
if(argc == 2)
{
std::string Arg = argv[1];
if(Arg == "--version")
{
std::cout << KwmCurrentVersion << std::endl;
Result = true;
}
}
return Result;
}
void Fatal(const std::string &Err)
{
std::cout << Err << std::endl;
exit(1);
}
int main(int argc, char **argv)
{
if(CheckArguments(argc, argv))
return 0;
KwmInit();
CGEventMask EventMask;
CFRunLoopSourceRef RunLoopSource;
EventMask = ((1 << kCGEventKeyDown) |
(1 << kCGEventKeyUp) |
(1 << kCGEventMouseMoved) |
(1 << kCGEventLeftMouseDown) |
(1 << kCGEventLeftMouseUp));
EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);
if(!EventTap || !CGEventTapIsEnabled(EventTap))
Fatal("ERROR: Could not create event-tap!");
RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(EventTap, true);
NSApplicationLoad();
CFRunLoopRun();
return 0;
}
<commit_msg>version 1.0.6<commit_after>#include "kwm.h"
const std::string KwmCurrentVersion = "Kwm Version 1.0.6";
const std::string PlistFile = "com.koekeishiya.kwm.plist";
CFMachPortRef EventTap;
kwm_path KWMPath = {};
kwm_code KWMCode = {};
kwm_screen KWMScreen = {};
kwm_toggles KWMToggles = {};
kwm_prefix KWMPrefix = {};
kwm_focus KWMFocus = {};
std::vector<hotkey> KwmHotkeys;
std::map<unsigned int, screen_info> DisplayMap;
std::vector<window_info> WindowLst;
std::vector<int> FloatingWindowLst;
std::vector<std::string> FloatingAppLst;
std::map<std::string, int> CapturedAppLst;
std::map<std::string, std::vector<CFTypeRef> > AllowedWindowRoles;
space_tiling_option KwmSpaceMode;
focus_option KwmFocusMode;
cycle_focus_option KwmCycleMode;
pthread_t BackgroundThread;
pthread_t DaemonThread;
pthread_mutex_t BackgroundLock;
CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
pthread_mutex_lock(&BackgroundLock);
switch(Type)
{
case kCGEventTapDisabledByTimeout:
case kCGEventTapDisabledByUserInput:
{
DEBUG("Restarting Event Tap")
CGEventTapEnable(EventTap, true);
} break;
case kCGEventKeyDown:
{
if(KWMToggles.UseBuiltinHotkeys && KwmMainHotkeyTrigger(&Event))
{
pthread_mutex_unlock(&BackgroundLock);
return NULL;
}
if(KwmFocusMode == FocusModeAutofocus)
{
CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
CGEventPostToPSN(&KWMFocus.PSN, Event);
pthread_mutex_unlock(&BackgroundLock);
return NULL;
}
} break;
case kCGEventKeyUp:
{
if(KwmFocusMode == FocusModeAutofocus)
{
CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
CGEventPostToPSN(&KWMFocus.PSN, Event);
pthread_mutex_unlock(&BackgroundLock);
return NULL;
}
} break;
case kCGEventMouseMoved:
{
if(KwmFocusMode != FocusModeDisabled)
FocusWindowBelowCursor();
} break;
case kCGEventLeftMouseDown:
{
DEBUG("Left mouse button was pressed")
FocusWindowBelowCursor();
if(KWMToggles.EnableDragAndDrop && IsCursorInsideFocusedWindow())
KWMToggles.WindowDragInProgress = true;
} break;
case kCGEventLeftMouseUp:
{
if(KWMToggles.EnableDragAndDrop && KWMToggles.WindowDragInProgress)
{
if(!IsCursorInsideFocusedWindow())
ToggleFocusedWindowFloating();
KWMToggles.WindowDragInProgress = false;
}
DEBUG("Left mouse button was released")
} break;
}
pthread_mutex_unlock(&BackgroundLock);
return Event;
}
bool KwmRunLiveCodeHotkeySystem(CGEventRef *Event, modifiers *Mod, CGKeyCode Keycode)
{
std::string NewHotkeySOFileTime = KwmGetFileTime(KWMPath.HotkeySOFullPath.c_str());
if(NewHotkeySOFileTime != "file not found" &&
NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)
{
DEBUG("Reloading hotkeys.so")
UnloadKwmCode(&KWMCode);
KWMCode = LoadKwmCode();
}
if(KWMCode.IsValid)
{
// Capture custom hotkeys specified in hotkeys.cpp
if(KWMCode.KWMHotkeyCommands(*Mod, Keycode))
return true;
// Check if key should be remapped
int NewKeycode;
KWMCode.RemapKeys(Mod, Keycode, &NewKeycode);
if(NewKeycode != -1)
{
CGEventSetFlags(*Event, 0);
if(Mod->CmdKey)
CGEventSetFlags(*Event, kCGEventFlagMaskCommand);
if(Mod->AltKey)
CGEventSetFlags(*Event, kCGEventFlagMaskAlternate);
if(Mod->CtrlKey)
CGEventSetFlags(*Event, kCGEventFlagMaskControl);
if(Mod->ShiftKey)
CGEventSetFlags(*Event, kCGEventFlagMaskShift);
CGEventSetIntegerValueField(*Event, kCGKeyboardEventKeycode, NewKeycode);
}
}
return false;
}
kwm_code LoadKwmCode()
{
kwm_code Code = {};
Code.HotkeySOFileTime = KwmGetFileTime(KWMPath.HotkeySOFullPath.c_str());
Code.KwmHotkeySO = dlopen(KWMPath.HotkeySOFullPath.c_str(), RTLD_LAZY);
if(Code.KwmHotkeySO)
{
Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "KWMHotkeyCommands");
Code.RemapKeys = (kwm_key_remap*) dlsym(Code.KwmHotkeySO, "RemapKeys");
}
else
{
DEBUG("LoadKwmCode() Could not open '" << KWMPath.HotkeySOFullPath << "'")
}
Code.IsValid = (Code.KWMHotkeyCommands && Code.RemapKeys);
return Code;
}
void UnloadKwmCode(kwm_code *Code)
{
if(Code->KwmHotkeySO)
dlclose(Code->KwmHotkeySO);
Code->HotkeySOFileTime = "";
Code->KWMHotkeyCommands = 0;
Code->RemapKeys = 0;
Code->IsValid = 0;
}
std::string KwmGetFileTime(const char *File)
{
struct stat attr;
int Result = stat(File, &attr);
if(Result == -1)
return "file not found";
return ctime(&attr.st_mtime);
}
void KwmQuit()
{
exit(0);
}
void * KwmWindowMonitor(void*)
{
while(1)
{
pthread_mutex_lock(&BackgroundLock);
UpdateWindowTree();
pthread_mutex_unlock(&BackgroundLock);
usleep(200000);
}
}
bool IsPrefixOfString(std::string &Line, std::string Prefix)
{
bool Result = false;
if(Line.substr(0, Prefix.size()) == Prefix)
{
Line = Line.substr(Prefix.size()+1);
Result = true;
}
return Result;
}
void KwmReloadConfig()
{
KwmClearSettings();
KwmExecuteConfig();
}
void KwmClearSettings()
{
std::map<std::string, std::vector<CFTypeRef> >::iterator It;
for(It = AllowedWindowRoles.begin(); It != AllowedWindowRoles.end(); ++It)
{
std::vector<CFTypeRef> &WindowRoles = It->second;
for(std::size_t RoleIndex = 0; RoleIndex < WindowRoles.size(); ++RoleIndex)
CFRelease(WindowRoles[RoleIndex]);
WindowRoles.clear();
}
FloatingAppLst.clear();
KwmHotkeys.clear();
KWMPrefix.Enabled = false;
}
void KwmExecuteConfig()
{
char *HomeP = std::getenv("HOME");
if(!HomeP)
{
DEBUG("Failed to get environment variable 'HOME'")
return;
}
KWMPath.EnvHome = HomeP;
KWMPath.ConfigFolder = ".kwm";
std::ifstream ConfigFD(KWMPath.EnvHome + "/" + KWMPath.ConfigFolder + "/" + KWMPath.ConfigFile);
if(ConfigFD.fail())
{
DEBUG("Could not open " << KWMPath.EnvHome << "/" << KWMPath.ConfigFolder << "/" << KWMPath.ConfigFile
<< ", make sure the file exists." << std::endl)
return;
}
std::string Line;
while(std::getline(ConfigFD, Line))
{
if(!Line.empty() && Line[0] != '#')
{
if(IsPrefixOfString(Line, "kwmc"))
KwmInterpretCommand(Line, 0);
else if(IsPrefixOfString(Line, "sys"))
system(Line.c_str());
}
}
}
bool IsKwmAlreadyAddedToLaunchd()
{
std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;
struct stat attr;
int Result = stat(SymlinkFullPath.c_str(), &attr);
if(Result == -1)
return false;
return true;
}
void AddKwmToLaunchd()
{
if(IsKwmAlreadyAddedToLaunchd())
return;
std::string PlistFullPath = KWMPath.FilePath + "/" + PlistFile;
std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;
std::ifstream TemplateFD(KWMPath.FilePath + "/kwm_template.plist");
if(TemplateFD.fail())
return;
std::ofstream OutFD(PlistFullPath);
if(OutFD.fail())
return;
std::string Line;
std::vector<std::string> PlistContents;
while(std::getline(TemplateFD, Line))
PlistContents.push_back(Line);
DEBUG("AddKwmToLaunchd() Creating file: " << PlistFullPath)
for(std::size_t LineNumber = 0; LineNumber < PlistContents.size(); ++LineNumber)
{
if(LineNumber == 8)
OutFD << " <string>" + KWMPath.FilePath + "/kwm</string>" << std::endl;
else
OutFD << PlistContents[LineNumber] << std::endl;
}
TemplateFD.close();
OutFD.close();
std::string PerformSymlink = "mv " + PlistFullPath + " " + SymlinkFullPath;
system(PerformSymlink.c_str());
DEBUG("AddKwmToLaunchd() Moved plist to: " << SymlinkFullPath)
}
void RemoveKwmFromLaunchd()
{
if(!IsKwmAlreadyAddedToLaunchd())
return;
std::string SymlinkFullPath = KWMPath.EnvHome + "/Library/LaunchAgents/" + PlistFile;
std::string RemoveSymlink = "rm " + SymlinkFullPath;
system(RemoveSymlink.c_str());
DEBUG("RemoveKwmFromLaunchd() Removing file: " << SymlinkFullPath)
}
bool GetKwmFilePath()
{
bool Result = false;
char PathBuf[PROC_PIDPATHINFO_MAXSIZE];
pid_t Pid = getpid();
int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));
if (Ret > 0)
{
KWMPath.FilePath = PathBuf;
std::size_t Split = KWMPath.FilePath.find_last_of("/\\");
KWMPath.FilePath = KWMPath.FilePath.substr(0, Split);
KWMPath.HotkeySOFullPath = KWMPath.FilePath + "/hotkeys.so";
Result = true;
}
return Result;
}
void KwmInit()
{
if(!CheckPrivileges())
Fatal("Could not access OSX Accessibility!");
if (pthread_mutex_init(&BackgroundLock, NULL) != 0)
Fatal("Could not create mutex!");
if(KwmStartDaemon())
pthread_create(&DaemonThread, NULL, &KwmDaemonHandleConnectionBG, NULL);
else
Fatal("Kwm: Could not start daemon..");
KWMScreen.SplitRatio = 0.5;
KWMScreen.SplitMode = -1;
KWMScreen.MarkedWindow = -1;
KWMScreen.OldScreenID = -1;
KWMScreen.PrevSpace = -1;
KWMScreen.DefaultOffset = CreateDefaultScreenOffset();
KWMScreen.MaxCount = 5;
KWMScreen.ActiveCount = 0;
KWMScreen.UpdateSpace = true;
KWMToggles.EnableTilingMode = true;
KWMToggles.UseBuiltinHotkeys = true;
KWMToggles.EnableDragAndDrop = true;
KWMToggles.UseContextMenuFix = true;
KWMToggles.UseMouseFollowsFocus = true;
KWMToggles.WindowDragInProgress = false;
KwmSpaceMode = SpaceModeBSP;
KwmFocusMode = FocusModeAutoraise;
KwmCycleMode = CycleModeScreen;
KWMPrefix.Enabled = false;
KWMPrefix.Active = false;
KWMPrefix.Timeout = 0.75;
KWMPath.ConfigFile = "kwmrc";
if(GetKwmFilePath())
KWMCode = LoadKwmCode();
KwmExecuteConfig();
GetActiveDisplays();
pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);
}
bool CheckPrivileges()
{
bool Result = false;
const void * Keys[] = { kAXTrustedCheckOptionPrompt };
const void * Values[] = { kCFBooleanTrue };
CFDictionaryRef Options;
Options = CFDictionaryCreate(kCFAllocatorDefault,
Keys, Values, sizeof(Keys) / sizeof(*Keys),
&kCFCopyStringDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
Result = AXIsProcessTrustedWithOptions(Options);
CFRelease(Options);
return Result;
}
bool CheckArguments(int argc, char **argv)
{
bool Result = false;
if(argc == 2)
{
std::string Arg = argv[1];
if(Arg == "--version")
{
std::cout << KwmCurrentVersion << std::endl;
Result = true;
}
}
return Result;
}
void Fatal(const std::string &Err)
{
std::cout << Err << std::endl;
exit(1);
}
int main(int argc, char **argv)
{
if(CheckArguments(argc, argv))
return 0;
KwmInit();
CGEventMask EventMask;
CFRunLoopSourceRef RunLoopSource;
EventMask = ((1 << kCGEventKeyDown) |
(1 << kCGEventKeyUp) |
(1 << kCGEventMouseMoved) |
(1 << kCGEventLeftMouseDown) |
(1 << kCGEventLeftMouseUp));
EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);
if(!EventTap || !CGEventTapIsEnabled(EventTap))
Fatal("ERROR: Could not create event-tap!");
RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(EventTap, true);
NSApplicationLoad();
CFRunLoopRun();
return 0;
}
<|endoftext|> |
<commit_before>// Brian Goldman
// Example of how to use Lambda functions
// Compiled using: g++ -std=c++11 lambdas.cpp
#include <iostream>
#include <algorithm>
using namespace std;
// Example of the old way to get reverse sorting
bool reverse_order(const int& first, const int& second) {
return first > second;
}
// Utility to print out the vectors
void print(const vector<int> & numbers) {
for (const auto & number : numbers) {
cout << number << ", ";
}
cout << endl;
}
int main() {
// creates a vector of numbers using C++11's initializer lists
vector<int> numbers = {8, 6, 7, 5, 3, 0, 9};
// does an implace sort
sort(numbers.begin(), numbers.end());
cout << "Smallest to largest" << endl;
print(numbers);
// Uses a regular function to sort in reverse order
sort(numbers.begin(), numbers.end(), reverse_order);
// Uses a Lambda function to sort in reverse order
sort(numbers.begin(), numbers.end(),
// This is a lambda being passed as the third argument of sort
// Lambda's have 3 parts
// * The [] is the "capture" which holds on to extra variables
// * The () is the argument list, like any other function
// * The {} is the function body, like any other function
[](const int& first, const int& second) { return first > second; }
);
cout << "Largest to smallest" << endl;
print(numbers);
int target = 7;
// Create a lambda named "from_target" which captures a reference to "target"
auto from_target = [&target](const int& first, const int& second) { return abs(target-first) < abs(target-second); };
target = 3;
sort(numbers.begin(), numbers.end(), from_target);
cout << "Ordered by absolute distance from " << target << endl;
print(numbers);
return 0;
}
<commit_msg>Added line break<commit_after>// Brian Goldman
// Example of how to use Lambda functions
// Compiled using: g++ -std=c++11 lambdas.cpp
#include <iostream>
#include <algorithm>
using namespace std;
// Example of the old way to get reverse sorting
bool reverse_order(const int& first, const int& second) {
return first > second;
}
// Utility to print out the vectors
void print(const vector<int> & numbers) {
for (const auto & number : numbers) {
cout << number << ", ";
}
cout << endl;
}
int main() {
// creates a vector of numbers using C++11's initializer lists
vector<int> numbers = {8, 6, 7, 5, 3, 0, 9};
// does an implace sort
sort(numbers.begin(), numbers.end());
cout << "Smallest to largest" << endl;
print(numbers);
// Uses a regular function to sort in reverse order
sort(numbers.begin(), numbers.end(), reverse_order);
// Uses a Lambda function to sort in reverse order
sort(numbers.begin(), numbers.end(),
// This is a lambda being passed as the third argument of sort
// Lambda's have 3 parts
// * The [] is the "capture" which holds on to extra variables
// * The () is the argument list, like any other function
// * The {} is the function body, like any other function
[](const int& first, const int& second) { return first > second; }
);
cout << "Largest to smallest" << endl;
print(numbers);
int target = 7;
// Create a lambda named "from_target" which captures a reference to "target"
auto from_target = [&target](const int& first, const int& second) {
return abs(target-first) < abs(target-second);
};
target = 3;
sort(numbers.begin(), numbers.end(), from_target);
cout << "Ordered by absolute distance from " << target << endl;
print(numbers);
return 0;
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* fflas/fflas_pftrsm.inl
* Copyright (C) 2013 Ziad Sultan
*
* Written by Ziad Sultan < Ziad.Sultan@imag.fr >
* Time-stamp: <04 Sep 14 14:49:03 Jean-Guillaume.Dumas@imag.fr>
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*.
*/
#ifndef __FFLASFFPACK_fflas_pftrsm_INL
#define __FFLASFFPACK_fflas_pftrsm_INL
#define PTRSM_HYBRID_THRESHOLD 256
#ifdef __FFLASFFPACK_USE_OPENMP
#include <omp.h>
#endif
#ifdef __FFLASFFPACK_USE_KAAPI
#include <kaapi++>
#include "fflas-ffpack/fflas/kaapi_routines.inl"
#endif
#include "fflas-ffpack/fflas/parallel.h"
namespace FFLAS {
template<class Field>
inline typename Field::Element_ptr
ftrsm( const Field& F,
const FFLAS::FFLAS_SIDE Side,
const FFLAS::FFLAS_UPLO UpLo,
const FFLAS::FFLAS_TRANSPOSE TA,
const FFLAS::FFLAS_DIAG Diag,
const size_t m,
const size_t n,
const typename Field::Element alpha,
#ifdef __FFLAS__TRSM_READONLY
typename Field::ConstElement_ptr
#else
typename Field::Element_ptr
#endif
A, const size_t lda,
typename Field::Element_ptr B, const size_t ldb,
TRSMHelper <StructureHelper::Iterative, ParSeqHelper::Parallel> & H)
// const FFLAS::CuttingStrategy method,
// const size_t numThreads)
{
if(Side == FflasRight){
ForStrategy1D iter(m, H.parseq.method, (size_t)H.parseq.numthreads);
for (iter.begin(); ! iter.end(); ++iter) {
TRSMHelper<StructureHelper::Recursive, ParSeqHelper::Sequential> SeqH (H);
TASK(READ(F, A), NOWRITE(), READWRITE(B), ftrsm, F, Side, UpLo, TA, Diag, iter.iend-iter.ibeg, n, alpha, A, lda, B + iter.ibeg*ldb, ldb, SeqH);
}
} else {
ForStrategy1D iter(n, H.parseq.method, (size_t)H.parseq.numthreads);
for (iter.begin(); ! iter.end(); ++iter) {
TRSMHelper<StructureHelper::Recursive, ParSeqHelper::Sequential> SeqH (H);
TASK(READ(F, A), NOWRITE(), READWRITE(B), ftrsm, F, Side, UpLo, TA, Diag, m, iter.iend-iter.ibeg, alpha, A , lda, B + iter.ibeg, ldb, SeqH);
}
}
WAIT;
return B;
}
template<class Field>
inline typename Field::Element_ptr
ftrsm( const Field& F,
const FFLAS::FFLAS_SIDE Side,
const FFLAS::FFLAS_UPLO UpLo,
const FFLAS::FFLAS_TRANSPOSE TA,
const FFLAS::FFLAS_DIAG Diag,
const size_t m,
const size_t n,
const typename Field::Element alpha,
#ifdef __FFLAS__TRSM_READONLY
typename Field::ConstElement_ptr
#else
typename Field::Element_ptr
#endif
A, const size_t lda,
typename Field::Element_ptr B, const size_t ldb,
TRSMHelper <StructureHelper::Hybrid, ParSeqHelper::Parallel> & H)
// const FFLAS::CuttingStrategy method,
// const size_t numThreads)
{
if(Side == FflasRight){
int nt = H.parseq.numthreads;
int nt_it,nt_rec;
if ((int)m/PTRSM_HYBRID_THRESHOLD < nt){
nt_it = ceil(double(m)/PTRSM_HYBRID_THRESHOLD);
nt_rec = ceil(double(nt)/nt_it);
} else { nt_it = nt; nt_rec = 1;}
ForStrategy1D iter(m, H.parseq.method, (size_t)nt_it);
for (iter.begin(); ! iter.end(); ++iter) {
ParSeqHelper::Parallel psh(nt_rec,CuttingStrategy::TWO_D_ADAPT);
TRSMHelper<StructureHelper::Recursive, ParSeqHelper::Parallel> SeqH (psh);
std::cerr<<"trsm_rec nt = "<<nt_rec<<std::endl;
TASK(READ(F, A), NOWRITE(), READWRITE(B), ftrsm, F, Side, UpLo, TA, Diag, iter.iend-iter.ibeg, n, alpha, A, lda, B + iter.ibeg*ldb, ldb, SeqH);
}
} else {
int nt = H.parseq.numthreads;
int nt_it=nt;
int nt_rec=1;
while(nt_it*PTRSM_HYBRID_THRESHOLD >= (int)n){
nt_it>>=1;
nt_rec<<=1;
}
nt_it<<=1;
nt_rec>>=1;
// if ((int)n/PTRSM_HYBRID_THRESHOLD < nt){
// nt_it = std::min(nt,(int)ceil(double(n)/PTRSM_HYBRID_THRESHOLD));
// nt_rec = ceil(double(nt)/nt_it);
// } else { nt_it = nt; nt_rec = 1;}
ForStrategy1D iter(n, H.parseq.method, (size_t)nt_it);
for (iter.begin(); ! iter.end(); ++iter) {
ParSeqHelper::Parallel psh(nt_rec, CuttingStrategy::TWO_D_ADAPT);
TRSMHelper<StructureHelper::Recursive, ParSeqHelper::Parallel> SeqH (psh);
//std::cerr<<"trsm_rec nt = "<<nt_rec<<std::endl;
TASK(READ(F, A), NOWRITE(), READWRITE(B), ftrsm, F, Side, UpLo, TA, Diag, m, iter.iend-iter.ibeg, alpha, A , lda, B + iter.ibeg, ldb, SeqH);
}
}
WAIT;
return B;
}
} // FFLAS
#endif // __FFLASFFPACK_fflas_pftrsm_INL
<commit_msg>explicit cast to int<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* fflas/fflas_pftrsm.inl
* Copyright (C) 2013 Ziad Sultan
*
* Written by Ziad Sultan < Ziad.Sultan@imag.fr >
* Time-stamp: <03 Dec 14 11:35:13 Jean-Guillaume.Dumas@imag.fr>
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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
* ========LICENCE========
*.
*/
#ifndef __FFLASFFPACK_fflas_pftrsm_INL
#define __FFLASFFPACK_fflas_pftrsm_INL
#define PTRSM_HYBRID_THRESHOLD 256
#ifdef __FFLASFFPACK_USE_OPENMP
#include <omp.h>
#endif
#ifdef __FFLASFFPACK_USE_KAAPI
#include <kaapi++>
#include "fflas-ffpack/fflas/kaapi_routines.inl"
#endif
#include "fflas-ffpack/fflas/parallel.h"
namespace FFLAS {
template<class Field>
inline typename Field::Element_ptr
ftrsm( const Field& F,
const FFLAS::FFLAS_SIDE Side,
const FFLAS::FFLAS_UPLO UpLo,
const FFLAS::FFLAS_TRANSPOSE TA,
const FFLAS::FFLAS_DIAG Diag,
const size_t m,
const size_t n,
const typename Field::Element alpha,
#ifdef __FFLAS__TRSM_READONLY
typename Field::ConstElement_ptr
#else
typename Field::Element_ptr
#endif
A, const size_t lda,
typename Field::Element_ptr B, const size_t ldb,
TRSMHelper <StructureHelper::Iterative, ParSeqHelper::Parallel> & H)
// const FFLAS::CuttingStrategy method,
// const size_t numThreads)
{
if(Side == FflasRight){
ForStrategy1D iter(m, H.parseq.method, (size_t)H.parseq.numthreads);
for (iter.begin(); ! iter.end(); ++iter) {
TRSMHelper<StructureHelper::Recursive, ParSeqHelper::Sequential> SeqH (H);
TASK(READ(F, A), NOWRITE(), READWRITE(B), ftrsm, F, Side, UpLo, TA, Diag, iter.iend-iter.ibeg, n, alpha, A, lda, B + iter.ibeg*ldb, ldb, SeqH);
}
} else {
ForStrategy1D iter(n, H.parseq.method, (size_t)H.parseq.numthreads);
for (iter.begin(); ! iter.end(); ++iter) {
TRSMHelper<StructureHelper::Recursive, ParSeqHelper::Sequential> SeqH (H);
TASK(READ(F, A), NOWRITE(), READWRITE(B), ftrsm, F, Side, UpLo, TA, Diag, m, iter.iend-iter.ibeg, alpha, A , lda, B + iter.ibeg, ldb, SeqH);
}
}
WAIT;
return B;
}
template<class Field>
inline typename Field::Element_ptr
ftrsm( const Field& F,
const FFLAS::FFLAS_SIDE Side,
const FFLAS::FFLAS_UPLO UpLo,
const FFLAS::FFLAS_TRANSPOSE TA,
const FFLAS::FFLAS_DIAG Diag,
const size_t m,
const size_t n,
const typename Field::Element alpha,
#ifdef __FFLAS__TRSM_READONLY
typename Field::ConstElement_ptr
#else
typename Field::Element_ptr
#endif
A, const size_t lda,
typename Field::Element_ptr B, const size_t ldb,
TRSMHelper <StructureHelper::Hybrid, ParSeqHelper::Parallel> & H)
// const FFLAS::CuttingStrategy method,
// const size_t numThreads)
{
if(Side == FflasRight){
int nt = H.parseq.numthreads;
int nt_it,nt_rec;
if ((int)m/PTRSM_HYBRID_THRESHOLD < nt){
nt_it = (int)ceil(double(m)/PTRSM_HYBRID_THRESHOLD);
nt_rec = (int)ceil(double(nt)/nt_it);
} else { nt_it = nt; nt_rec = 1;}
ForStrategy1D iter(m, H.parseq.method, (size_t)nt_it);
for (iter.begin(); ! iter.end(); ++iter) {
ParSeqHelper::Parallel psh(nt_rec,CuttingStrategy::TWO_D_ADAPT);
TRSMHelper<StructureHelper::Recursive, ParSeqHelper::Parallel> SeqH (psh);
std::cerr<<"trsm_rec nt = "<<nt_rec<<std::endl;
TASK(READ(F, A), NOWRITE(), READWRITE(B), ftrsm, F, Side, UpLo, TA, Diag, iter.iend-iter.ibeg, n, alpha, A, lda, B + iter.ibeg*ldb, ldb, SeqH);
}
} else {
int nt = H.parseq.numthreads;
int nt_it=nt;
int nt_rec=1;
while(nt_it*PTRSM_HYBRID_THRESHOLD >= (int)n){
nt_it>>=1;
nt_rec<<=1;
}
nt_it<<=1;
nt_rec>>=1;
// if ((int)n/PTRSM_HYBRID_THRESHOLD < nt){
// nt_it = std::min(nt,(int)ceil(double(n)/PTRSM_HYBRID_THRESHOLD));
// nt_rec = ceil(double(nt)/nt_it);
// } else { nt_it = nt; nt_rec = 1;}
ForStrategy1D iter(n, H.parseq.method, (size_t)nt_it);
for (iter.begin(); ! iter.end(); ++iter) {
ParSeqHelper::Parallel psh(nt_rec, CuttingStrategy::TWO_D_ADAPT);
TRSMHelper<StructureHelper::Recursive, ParSeqHelper::Parallel> SeqH (psh);
//std::cerr<<"trsm_rec nt = "<<nt_rec<<std::endl;
TASK(READ(F, A), NOWRITE(), READWRITE(B), ftrsm, F, Side, UpLo, TA, Diag, m, iter.iend-iter.ibeg, alpha, A , lda, B + iter.ibeg, ldb, SeqH);
}
}
WAIT;
return B;
}
} // FFLAS
#endif // __FFLASFFPACK_fflas_pftrsm_INL
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2021 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 "BackendTest.h"
#include <private/filament/EngineEnums.h>
#include <utils/Hash.h>
#include <utils/Log.h>
#include <fstream>
#ifndef IOS
#include <imageio/ImageEncoder.h>
#include <image/ColorTransform.h>
#endif
static uint32_t sPixelHashResult = 0;
static constexpr int kDstTexWidth = 384;
static constexpr int kDstTexHeight = 384;
static constexpr auto kDstTexFormat = filament::backend::TextureFormat::RGBA8;
static constexpr int kNumLevels = 3;
namespace test {
using namespace filament;
using namespace filament::backend;
using namespace filament::math;
using namespace utils;
struct MaterialParams {
float fbWidth;
float fbHeight;
float sourceLevel;
float unused;
};
static void uploadUniforms(DriverApi& dapi, Handle<HwUniformBuffer> ubh, MaterialParams params) {
MaterialParams* tmp = new MaterialParams(params);
auto cb = [](void* buffer, size_t size, void* user) {
MaterialParams* sp = (MaterialParams*) buffer;
delete sp;
};
BufferDescriptor bd(tmp, sizeof(MaterialParams), cb);
dapi.loadUniformBuffer(ubh, std::move(bd));
}
#ifdef IOS
static void dumpScreenshot(DriverApi& dapi, Handle<HwRenderTarget> rt, const char* filename) {}
#else
static void dumpScreenshot(DriverApi& dapi, Handle<HwRenderTarget> rt, const char* filename) {
using namespace image;
const size_t size = kDstTexWidth * kDstTexHeight * 4;
void* buffer = calloc(1, size);
auto cb = [](void* buffer, size_t size, void* user) {
const char* file = (char*) user;
int w = kDstTexWidth, h = kDstTexHeight;
const uint32_t* texels = (uint32_t*) buffer;
sPixelHashResult = utils::hash::murmur3(texels, size / 4, 0);
LinearImage image(w, h, 4);
image = toLinearWithAlpha<uint8_t>(w, h, w * 4, (uint8_t*) buffer);
std::ofstream pngstrm(file, std::ios::binary | std::ios::trunc);
ImageEncoder::encode(pngstrm, ImageEncoder::Format::PNG, image, "", file);
};
PixelBufferDescriptor pb(buffer, size, PixelDataFormat::RGBA, PixelDataType::UBYTE, cb,
(void*) filename);
dapi.readPixels(rt, 0, 0, kDstTexWidth, kDstTexHeight, std::move(pb));
}
#endif
static uint32_t toUintColor(float4 color) {
color = saturate(color);
uint32_t r = color.r * 255.0;
uint32_t g = color.g * 255.0;
uint32_t b = color.b * 255.0;
uint32_t a = color.a * 255.0;
return (r << 0) | (g << 8) | (b << 16) | (a << 24);
}
static void createBitmap(DriverApi& dapi, Handle<HwTexture> texture, int baseWidth, int baseHeight,
int level, float3 color) {
auto cb = [](void* buffer, size_t size, void* user) { free(buffer); };
const int width = baseWidth >> level;
const int height = baseHeight >> level;
const size_t size0 = height * width * 4;
uint8_t* buffer0 = (uint8_t*) calloc(size0, 1);
PixelBufferDescriptor pb(buffer0, size0, PixelDataFormat::RGBA, PixelDataType::UBYTE, cb);
const float3 foreground = color;
const float3 background = float3(1, 1, 0);
const float radius = 0.25f;
// Draw a circle on a yellow background.
uint32_t* texels = (uint32_t*) buffer0;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
float2 uv = { (col - width / 2.0f) / width, (row - height / 2.0f) / height };
const float d = distance(uv, float2(0));
const float t = d < radius ? 1.0 : 0.0;
const float3 color = mix(foreground, background, t);
texels[row * width + col] = toUintColor(float4(color, 1.0f));
}
}
// Upload to the GPU.
dapi.update2DImage(texture, level, 0, 0, width, height, std::move(pb));
}
TEST_F(BackendTest, ColorMagnify) {
auto& api = getDriverApi();
constexpr int kSrcTexWidth = 256;
constexpr int kSrcTexHeight = 256;
constexpr auto kSrcTexFormat = filament::backend::TextureFormat::RGBA8;
// Create a SwapChain and make it current. We don't really use it so the res doesn't matter.
auto swapChain = api.createSwapChainHeadless(256, 256, 0);
api.makeCurrent(swapChain, swapChain);
// Create a source texture.
Handle<HwTexture> srcTexture = api.createTexture(
SamplerType::SAMPLER_2D, kNumLevels, kSrcTexFormat, 1, kSrcTexWidth, kSrcTexHeight, 1,
TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE | TextureUsage::COLOR_ATTACHMENT);
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 0, float3(0.5, 0, 0));
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 1, float3(0, 0, 0.5));
// Create a destination texture.
Handle<HwTexture> dstTexture = api.createTexture(
SamplerType::SAMPLER_2D, kNumLevels, kDstTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
// Create a RenderTarget for each texture's miplevel.
Handle<HwRenderTarget> srcRenderTargets[kNumLevels];
Handle<HwRenderTarget> dstRenderTargets[kNumLevels];
for (uint8_t level = 0; level < kNumLevels; level++) {
srcRenderTargets[level] = api.createRenderTarget( TargetBufferFlags::COLOR,
kSrcTexWidth >> level, kSrcTexHeight >> level, 1, { srcTexture, level, 0 }, {}, {});
dstRenderTargets[level] = api.createRenderTarget( TargetBufferFlags::COLOR,
kDstTexWidth >> level, kDstTexHeight >> level, 1, { dstTexture, level, 0 }, {}, {});
}
// Do a "magnify" blit from level 1 of the source RT to the level 0 of the desination RT.
const int srcLevel = 1;
api.blit(TargetBufferFlags::COLOR0, dstRenderTargets[0],
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTargets[srcLevel],
{0, 0, kSrcTexWidth >> srcLevel, kSrcTexHeight >> srcLevel}, SamplerMagFilter::LINEAR);
// Push through an empty frame to allow the texture to upload and the blit to exectue.
getDriverApi().beginFrame(0, 0);
getDriverApi().commit(swapChain);
getDriverApi().endFrame(0);
// Grab a screenshot.
getDriverApi().beginFrame(0, 0);
dumpScreenshot(api, dstRenderTargets[0], "ColorMagnify.png");
getDriverApi().commit(swapChain);
getDriverApi().endFrame(0);
// Wait for the ReadPixels result to come back.
api.finish();
executeCommands();
getDriver().purge();
// Check if the image matches perfectly to our golden run.
const uint32_t expected = 0xb830a36a;
printf("Computed hash is 0x%8.8x, Expected 0x%8.8x\n", sPixelHashResult, expected);
EXPECT_TRUE(sPixelHashResult == expected);
// Cleanup.
api.destroyTexture(srcTexture);
api.destroyTexture(dstTexture);
api.destroySwapChain(swapChain);
for (auto rt : srcRenderTargets) api.destroyRenderTarget(rt);
for (auto rt : dstRenderTargets) api.destroyRenderTarget(rt);
}
TEST_F(BackendTest, ColorMinify) {
auto& api = getDriverApi();
constexpr int kSrcTexWidth = 1024;
constexpr int kSrcTexHeight = 1024;
constexpr auto kSrcTexFormat = filament::backend::TextureFormat::RGBA8;
// Create a SwapChain and make it current. We don't really use it so the res doesn't matter.
auto swapChain = api.createSwapChainHeadless(256, 256, 0);
api.makeCurrent(swapChain, swapChain);
// Create a source texture.
Handle<HwTexture> srcTexture = api.createTexture(
SamplerType::SAMPLER_2D, kNumLevels, kSrcTexFormat, 1, kSrcTexWidth, kSrcTexHeight, 1,
TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE | TextureUsage::COLOR_ATTACHMENT);
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 0, float3(0.5, 0, 0));
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 1, float3(0, 0, 0.5));
// Create a destination texture.
Handle<HwTexture> dstTexture = api.createTexture(
SamplerType::SAMPLER_2D, kNumLevels, kDstTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
// Create a RenderTarget for each texture's miplevel.
Handle<HwRenderTarget> srcRenderTargets[kNumLevels];
Handle<HwRenderTarget> dstRenderTargets[kNumLevels];
for (uint8_t level = 0; level < kNumLevels; level++) {
srcRenderTargets[level] = api.createRenderTarget( TargetBufferFlags::COLOR,
kSrcTexWidth >> level, kSrcTexHeight >> level, 1, { srcTexture, level, 0 }, {}, {});
dstRenderTargets[level] = api.createRenderTarget( TargetBufferFlags::COLOR,
kDstTexWidth >> level, kDstTexHeight >> level, 1, { dstTexture, level, 0 }, {}, {});
}
// Do a "magnify" blit from level 1 of the source RT to the level 0 of the desination RT.
const int srcLevel = 1;
api.blit(TargetBufferFlags::COLOR0, dstRenderTargets[0],
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTargets[srcLevel],
{0, 0, kSrcTexWidth >> srcLevel, kSrcTexHeight >> srcLevel}, SamplerMagFilter::LINEAR);
// Push through an empty frame to allow the texture to upload and the blit to exectue.
getDriverApi().beginFrame(0, 0);
getDriverApi().commit(swapChain);
getDriverApi().endFrame(0);
// Grab a screenshot.
getDriverApi().beginFrame(0, 0);
dumpScreenshot(api, dstRenderTargets[0], "ColorMinify.png");
getDriverApi().commit(swapChain);
getDriverApi().endFrame(0);
// Wait for the ReadPixels result to come back.
api.finish();
executeCommands();
getDriver().purge();
// Check if the image matches perfectly to our golden run.
const uint32_t expected = 0xe2353ca6;
printf("Computed hash is 0x%8.8x, Expected 0x%8.8x\n", sPixelHashResult, expected);
EXPECT_TRUE(sPixelHashResult == expected);
// Cleanup.
api.destroyTexture(srcTexture);
api.destroyTexture(dstTexture);
api.destroySwapChain(swapChain);
for (auto rt : srcRenderTargets) api.destroyRenderTarget(rt);
for (auto rt : dstRenderTargets) api.destroyRenderTarget(rt);
}
} // namespace test
<commit_msg>Code cleanup for test_Blit.<commit_after>/*
* Copyright (C) 2021 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 "BackendTest.h"
#include <private/filament/EngineEnums.h>
#include <utils/Hash.h>
#include <utils/Log.h>
#include <fstream>
#ifndef IOS
#include <imageio/ImageEncoder.h>
#include <image/ColorTransform.h>
#endif
namespace test {
using namespace filament;
using namespace filament::backend;
using namespace filament::math;
using namespace utils;
struct ScreenshotParams {
int width;
int height;
const char* filename;
uint32_t pixelHashResult;
};
#ifdef IOS
static void dumpScreenshot(DriverApi& dapi, Handle<HwRenderTarget> rt, ScreenshotParams* params) {}
#else
static void dumpScreenshot(DriverApi& dapi, Handle<HwRenderTarget> rt, ScreenshotParams* params) {
using namespace image;
const size_t size = params->width * params->height * 4;
void* buffer = calloc(1, size);
auto cb = [](void* buffer, size_t size, void* user) {
ScreenshotParams* params = (ScreenshotParams*) user;
int w = params->width, h = params->height;
const uint32_t* texels = (uint32_t*) buffer;
params->pixelHashResult = utils::hash::murmur3(texels, size / 4, 0);
LinearImage image(w, h, 4);
image = toLinearWithAlpha<uint8_t>(w, h, w * 4, (uint8_t*) buffer);
std::ofstream pngstrm(params->filename, std::ios::binary | std::ios::trunc);
ImageEncoder::encode(pngstrm, ImageEncoder::Format::PNG, image, "", params->filename);
};
PixelBufferDescriptor pb(buffer, size, PixelDataFormat::RGBA, PixelDataType::UBYTE, cb,
(void*) params);
dapi.readPixels(rt, 0, 0, params->width, params->height, std::move(pb));
}
#endif
static uint32_t toUintColor(float4 color) {
color = saturate(color);
uint32_t r = color.r * 255.0;
uint32_t g = color.g * 255.0;
uint32_t b = color.b * 255.0;
uint32_t a = color.a * 255.0;
return (r << 0) | (g << 8) | (b << 16) | (a << 24);
}
static void createBitmap(DriverApi& dapi, Handle<HwTexture> texture, int baseWidth, int baseHeight,
int level, float3 color) {
auto cb = [](void* buffer, size_t size, void* user) { free(buffer); };
const int width = baseWidth >> level;
const int height = baseHeight >> level;
const size_t size0 = height * width * 4;
uint8_t* buffer0 = (uint8_t*) calloc(size0, 1);
PixelBufferDescriptor pb(buffer0, size0, PixelDataFormat::RGBA, PixelDataType::UBYTE, cb);
const float3 foreground = color;
const float3 background = float3(1, 1, 0);
const float radius = 0.25f;
// Draw a circle on a yellow background.
uint32_t* texels = (uint32_t*) buffer0;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
float2 uv = { (col - width / 2.0f) / width, (row - height / 2.0f) / height };
const float d = distance(uv, float2(0));
const float t = d < radius ? 1.0 : 0.0;
const float3 color = mix(foreground, background, t);
texels[row * width + col] = toUintColor(float4(color, 1.0f));
}
}
// Upload to the GPU.
dapi.update2DImage(texture, level, 0, 0, width, height, std::move(pb));
}
TEST_F(BackendTest, ColorMagnify) {
auto& api = getDriverApi();
constexpr int kSrcTexWidth = 256;
constexpr int kSrcTexHeight = 256;
constexpr auto kSrcTexFormat = filament::backend::TextureFormat::RGBA8;
constexpr int kDstTexWidth = 384;
constexpr int kDstTexHeight = 384;
constexpr auto kDstTexFormat = filament::backend::TextureFormat::RGBA8;
constexpr int kNumLevels = 3;
// Create a SwapChain and make it current. We don't really use it so the res doesn't matter.
auto swapChain = api.createSwapChainHeadless(256, 256, 0);
api.makeCurrent(swapChain, swapChain);
// Create a source texture.
Handle<HwTexture> srcTexture = api.createTexture(
SamplerType::SAMPLER_2D, kNumLevels, kSrcTexFormat, 1, kSrcTexWidth, kSrcTexHeight, 1,
TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE | TextureUsage::COLOR_ATTACHMENT);
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 0, float3(0.5, 0, 0));
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 1, float3(0, 0, 0.5));
// Create a destination texture.
Handle<HwTexture> dstTexture = api.createTexture(
SamplerType::SAMPLER_2D, kNumLevels, kDstTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
// Create a RenderTarget for each texture's miplevel.
Handle<HwRenderTarget> srcRenderTargets[kNumLevels];
Handle<HwRenderTarget> dstRenderTargets[kNumLevels];
for (uint8_t level = 0; level < kNumLevels; level++) {
srcRenderTargets[level] = api.createRenderTarget( TargetBufferFlags::COLOR,
kSrcTexWidth >> level, kSrcTexHeight >> level, 1, { srcTexture, level, 0 }, {}, {});
dstRenderTargets[level] = api.createRenderTarget( TargetBufferFlags::COLOR,
kDstTexWidth >> level, kDstTexHeight >> level, 1, { dstTexture, level, 0 }, {}, {});
}
// Do a "magnify" blit from level 1 of the source RT to the level 0 of the destination RT.
const int srcLevel = 1;
api.blit(TargetBufferFlags::COLOR0, dstRenderTargets[0],
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTargets[srcLevel],
{0, 0, kSrcTexWidth >> srcLevel, kSrcTexHeight >> srcLevel}, SamplerMagFilter::LINEAR);
// Push through an empty frame to allow the texture to upload and the blit to execute.
getDriverApi().beginFrame(0, 0);
getDriverApi().commit(swapChain);
getDriverApi().endFrame(0);
// Grab a screenshot.
ScreenshotParams params { kDstTexWidth, kDstTexHeight, "ColorMagnify.png" };
getDriverApi().beginFrame(0, 0);
dumpScreenshot(api, dstRenderTargets[0], ¶ms);
getDriverApi().commit(swapChain);
getDriverApi().endFrame(0);
// Wait for the ReadPixels result to come back.
api.finish();
executeCommands();
getDriver().purge();
// Check if the image matches perfectly to our golden run.
const uint32_t expected = 0xb830a36a;
printf("Computed hash is 0x%8.8x, Expected 0x%8.8x\n", params.pixelHashResult, expected);
EXPECT_TRUE(params.pixelHashResult == expected);
// Cleanup.
api.destroyTexture(srcTexture);
api.destroyTexture(dstTexture);
api.destroySwapChain(swapChain);
for (auto rt : srcRenderTargets) api.destroyRenderTarget(rt);
for (auto rt : dstRenderTargets) api.destroyRenderTarget(rt);
}
TEST_F(BackendTest, ColorMinify) {
auto& api = getDriverApi();
constexpr int kSrcTexWidth = 1024;
constexpr int kSrcTexHeight = 1024;
constexpr auto kSrcTexFormat = filament::backend::TextureFormat::RGBA8;
constexpr int kDstTexWidth = 384;
constexpr int kDstTexHeight = 384;
constexpr auto kDstTexFormat = filament::backend::TextureFormat::RGBA8;
constexpr int kNumLevels = 3;
// Create a SwapChain and make it current. We don't really use it so the res doesn't matter.
auto swapChain = api.createSwapChainHeadless(256, 256, 0);
api.makeCurrent(swapChain, swapChain);
// Create a source texture.
Handle<HwTexture> srcTexture = api.createTexture(
SamplerType::SAMPLER_2D, kNumLevels, kSrcTexFormat, 1, kSrcTexWidth, kSrcTexHeight, 1,
TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE | TextureUsage::COLOR_ATTACHMENT);
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 0, float3(0.5, 0, 0));
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 1, float3(0, 0, 0.5));
// Create a destination texture.
Handle<HwTexture> dstTexture = api.createTexture(
SamplerType::SAMPLER_2D, kNumLevels, kDstTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
// Create a RenderTarget for each texture's miplevel.
Handle<HwRenderTarget> srcRenderTargets[kNumLevels];
Handle<HwRenderTarget> dstRenderTargets[kNumLevels];
for (uint8_t level = 0; level < kNumLevels; level++) {
srcRenderTargets[level] = api.createRenderTarget( TargetBufferFlags::COLOR,
kSrcTexWidth >> level, kSrcTexHeight >> level, 1, { srcTexture, level, 0 }, {}, {});
dstRenderTargets[level] = api.createRenderTarget( TargetBufferFlags::COLOR,
kDstTexWidth >> level, kDstTexHeight >> level, 1, { dstTexture, level, 0 }, {}, {});
}
// Do a "minify" blit from level 1 of the source RT to the level 0 of the destination RT.
const int srcLevel = 1;
api.blit(TargetBufferFlags::COLOR0, dstRenderTargets[0],
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTargets[srcLevel],
{0, 0, kSrcTexWidth >> srcLevel, kSrcTexHeight >> srcLevel}, SamplerMagFilter::LINEAR);
// Push through an empty frame to allow the texture to upload and the blit to execute.
getDriverApi().beginFrame(0, 0);
getDriverApi().commit(swapChain);
getDriverApi().endFrame(0);
// Grab a screenshot.
ScreenshotParams params { kDstTexWidth, kDstTexHeight, "ColorMinify.png" };
getDriverApi().beginFrame(0, 0);
dumpScreenshot(api, dstRenderTargets[0], ¶ms);
getDriverApi().commit(swapChain);
getDriverApi().endFrame(0);
// Wait for the ReadPixels result to come back.
api.finish();
executeCommands();
getDriver().purge();
// Check if the image matches perfectly to our golden run.
const uint32_t expected = 0xe2353ca6;
printf("Computed hash is 0x%8.8x, Expected 0x%8.8x\n", params.pixelHashResult, expected);
EXPECT_TRUE(params.pixelHashResult == expected);
// Cleanup.
api.destroyTexture(srcTexture);
api.destroyTexture(dstTexture);
api.destroySwapChain(swapChain);
for (auto rt : srcRenderTargets) api.destroyRenderTarget(rt);
for (auto rt : dstRenderTargets) api.destroyRenderTarget(rt);
}
} // namespace test
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_MATH_MATRIX
#define MJOLNIR_MATH_MATRIX
#include <mjolnir/util/is_all.hpp>
#include <array>
namespace mjolnir
{
template<typename realT, std::size_t Row, std::size_t Col>
class Matrix
{
public:
using real_type = realT;
using scalar_type = real_type;
constexpr static std::size_t dim_row = Row;
constexpr static std::size_t dim_col = Col;
constexpr static std::size_t number_of_element = Row * Col;
public:
Matrix() : values_{{}}{}
~Matrix() = default;
template<typename ... T_args, class = typename std::enable_if<
(sizeof...(T_args) == number_of_element) &&
is_all<std::is_convertible, realT, T_args...>::value>::type>
Matrix(T_args ... args) : values_{{args...}}{}
Matrix(const Matrix& mat) = default;
Matrix& operator=(const Matrix& mat) = default;
Matrix& operator+=(const Matrix& mat);
Matrix& operator-=(const Matrix& mat);
Matrix& operator*=(const scalar_type& scl);
Matrix& operator/=(const scalar_type& scl);
scalar_type at(const std::size_t i, const std::size_t j) const;
scalar_type& at(const std::size_t i, const std::size_t j);
scalar_type operator()(const std::size_t i, const std::size_t j) const;
scalar_type& operator()(const std::size_t i, const std::size_t j);
scalar_type at(const std::size_t i) const {return values_.at(i);}
scalar_type& at(const std::size_t i) {return values_.at(i);}
scalar_type operator[](const std::size_t i) const {return values_[i];}
scalar_type& operator[](const std::size_t i) {return values_[i];}
private:
std::array<real_type, number_of_element> values_;
};
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>&
Matrix<realT, R, C>::operator+=(const Matrix<realT, R, C>& mat)
{
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
(*this)(i, j) += mat(i, j);
return *this;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>&
Matrix<realT, R, C>::operator-=(const Matrix<realT, R, C>& mat)
{
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
(*this)(i, j) -= mat(i, j);
return *this;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>&
Matrix<realT, R, C>::operator*=(const scalar_type& s)
{
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
(*this)(i, j) *= s;
return *this;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>&
Matrix<realT, R, C>::operator/=(const scalar_type& s)
{
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
(*this)(i, j) /= s;
return *this;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator+(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = lhs(i, j) + rhs(i, j);
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator-(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = lhs(i, j) - rhs(i, j);
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator*(const Matrix<realT, R, C>& lhs, const realT rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = lhs(i, j) * rhs;
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator*(const realT lhs, const Matrix<realT, R, C>& rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = rhs(i, j) * lhs;
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator/(const Matrix<realT, R, C>& lhs, const realT rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = lhs(i, j) / rhs;
return retval;
}
template<typename realT, std::size_t L, std::size_t M, std::size_t N>
Matrix<realT, L, N>
operator*(const Matrix<realT, L, M>& lhs, const Matrix<realT, M, N>& rhs)
{
Matrix<realT, L, N> retval;
for(std::size_t i=0; i < L; ++i)
for(std::size_t j=0; j < N; ++j)
for(std::size_t k=0; k < M; ++k)
retval(i, j) += lhs(i, k) * rhs(k, j);
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
typename Matrix<realT, R, C>::scalar_type
Matrix<realT, R, C>::at(const std::size_t i, const std::size_t j) const
{
return this->values_.at(i * C + j);
}
template<typename realT, std::size_t R, std::size_t C>
typename Matrix<realT, R, C>::scalar_type&
Matrix<realT, R, C>::at(const std::size_t i, const std::size_t j)
{
return this->values_.at(i * C + j);
}
template<typename realT, std::size_t R, std::size_t C>
typename Matrix<realT, R, C>::scalar_type
Matrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j) const
{
return this->values_[i * C + j];
}
template<typename realT, std::size_t R, std::size_t C>
typename Matrix<realT, R, C>::scalar_type&
Matrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j)
{
return this->values_[i * C + j];
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, C, R> transpose(const Matrix<realT, R, C>& mat)
{
Matrix<realT, C, R> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(j, i) = mat(i, j);
return retval;
}
// for 3*3 only ...
template<typename realT>
inline realT determinant(const Matrix<realT, 3, 3>& mat)
{
return mat(0,0) * mat(1,1) * mat(2,2) +
mat(1,0) * mat(2,1) * mat(0,2) +
mat(2,0) * mat(0,1) * mat(1,2) -
mat(0,0) * mat(2,1) * mat(1,2) -
mat(2,0) * mat(1,1) * mat(0,2) -
mat(1,0) * mat(0,1) * mat(2,2);
}
template<typename realT>
Matrix<realT, 3, 3> inverse(const Matrix<realT, 3, 3>& mat)
{
const auto det_inv = 1e0 / determinant(mat);
Matrix<realT, 3, 3> inv;
inv(0,0) = det_inv * (mat(1,1) * mat(2,2) - mat(1,2) * mat(2,1));
inv(1,1) = det_inv * (mat(0,0) * mat(2,2) - mat(0,2) * mat(2,0));
inv(2,2) = det_inv * (mat(0,0) * mat(1,1) - mat(0,1) * mat(1,0));
inv(0,1) = det_inv * (mat(0,2) * mat(2,1) - mat(0,1) * mat(2,2));
inv(0,2) = det_inv * (mat(0,1) * mat(1,2) - mat(0,2) * mat(1,1));
inv(1,2) = det_inv * (mat(0,2) * mat(1,0) - mat(0,0) * mat(1,2));
inv(1,0) = det_inv * (mat(1,2) * mat(2,0) - mat(1,0) * mat(2,2));
inv(2,0) = det_inv * (mat(1,0) * mat(2,1) - mat(2,0) * mat(1,1));
inv(2,1) = det_inv * (mat(2,0) * mat(0,1) - mat(0,0) * mat(2,1));
return inv;
}
} // mjolnir
#endif /* MJOLNIR_MATH_MATRIX */
<commit_msg>add partial template specialization of scalar_type_of<matrix><commit_after>#ifndef MJOLNIR_MATH_MATRIX
#define MJOLNIR_MATH_MATRIX
#include <mjolnir/util/is_all.hpp>
#include <mjolnir/util/scalar_type_of.hpp>
#include <array>
namespace mjolnir
{
template<typename realT, std::size_t Row, std::size_t Col>
class Matrix
{
public:
using real_type = realT;
using scalar_type = real_type;
constexpr static std::size_t dim_row = Row;
constexpr static std::size_t dim_col = Col;
constexpr static std::size_t number_of_element = Row * Col;
public:
Matrix() : values_{{}}{}
~Matrix() = default;
template<typename ... T_args, class = typename std::enable_if<
(sizeof...(T_args) == number_of_element) &&
is_all<std::is_convertible, realT, T_args...>::value>::type>
Matrix(T_args ... args) : values_{{args...}}{}
Matrix(const Matrix& mat) = default;
Matrix& operator=(const Matrix& mat) = default;
Matrix& operator+=(const Matrix& mat);
Matrix& operator-=(const Matrix& mat);
Matrix& operator*=(const scalar_type& scl);
Matrix& operator/=(const scalar_type& scl);
scalar_type at(const std::size_t i, const std::size_t j) const;
scalar_type& at(const std::size_t i, const std::size_t j);
scalar_type operator()(const std::size_t i, const std::size_t j) const;
scalar_type& operator()(const std::size_t i, const std::size_t j);
scalar_type at(const std::size_t i) const {return values_.at(i);}
scalar_type& at(const std::size_t i) {return values_.at(i);}
scalar_type operator[](const std::size_t i) const {return values_[i];}
scalar_type& operator[](const std::size_t i) {return values_[i];}
private:
std::array<real_type, number_of_element> values_;
};
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>&
Matrix<realT, R, C>::operator+=(const Matrix<realT, R, C>& mat)
{
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
(*this)(i, j) += mat(i, j);
return *this;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>&
Matrix<realT, R, C>::operator-=(const Matrix<realT, R, C>& mat)
{
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
(*this)(i, j) -= mat(i, j);
return *this;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>&
Matrix<realT, R, C>::operator*=(const scalar_type& s)
{
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
(*this)(i, j) *= s;
return *this;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>&
Matrix<realT, R, C>::operator/=(const scalar_type& s)
{
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
(*this)(i, j) /= s;
return *this;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator+(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = lhs(i, j) + rhs(i, j);
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator-(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = lhs(i, j) - rhs(i, j);
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator*(const Matrix<realT, R, C>& lhs, const realT rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = lhs(i, j) * rhs;
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator*(const realT lhs, const Matrix<realT, R, C>& rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = rhs(i, j) * lhs;
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, R, C>
operator/(const Matrix<realT, R, C>& lhs, const realT rhs)
{
Matrix<realT, R, C> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(i, j) = lhs(i, j) / rhs;
return retval;
}
template<typename realT, std::size_t L, std::size_t M, std::size_t N>
Matrix<realT, L, N>
operator*(const Matrix<realT, L, M>& lhs, const Matrix<realT, M, N>& rhs)
{
Matrix<realT, L, N> retval;
for(std::size_t i=0; i < L; ++i)
for(std::size_t j=0; j < N; ++j)
for(std::size_t k=0; k < M; ++k)
retval(i, j) += lhs(i, k) * rhs(k, j);
return retval;
}
template<typename realT, std::size_t R, std::size_t C>
typename Matrix<realT, R, C>::scalar_type
Matrix<realT, R, C>::at(const std::size_t i, const std::size_t j) const
{
return this->values_.at(i * C + j);
}
template<typename realT, std::size_t R, std::size_t C>
typename Matrix<realT, R, C>::scalar_type&
Matrix<realT, R, C>::at(const std::size_t i, const std::size_t j)
{
return this->values_.at(i * C + j);
}
template<typename realT, std::size_t R, std::size_t C>
typename Matrix<realT, R, C>::scalar_type
Matrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j) const
{
return this->values_[i * C + j];
}
template<typename realT, std::size_t R, std::size_t C>
typename Matrix<realT, R, C>::scalar_type&
Matrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j)
{
return this->values_[i * C + j];
}
template<typename realT, std::size_t R, std::size_t C>
Matrix<realT, C, R> transpose(const Matrix<realT, R, C>& mat)
{
Matrix<realT, C, R> retval;
for(std::size_t i=0; i<R; ++i)
for(std::size_t j=0; j<C; ++j)
retval(j, i) = mat(i, j);
return retval;
}
// for 3*3 only ...
template<typename realT>
inline realT determinant(const Matrix<realT, 3, 3>& mat)
{
return mat(0,0) * mat(1,1) * mat(2,2) +
mat(1,0) * mat(2,1) * mat(0,2) +
mat(2,0) * mat(0,1) * mat(1,2) -
mat(0,0) * mat(2,1) * mat(1,2) -
mat(2,0) * mat(1,1) * mat(0,2) -
mat(1,0) * mat(0,1) * mat(2,2);
}
template<typename realT>
Matrix<realT, 3, 3> inverse(const Matrix<realT, 3, 3>& mat)
{
const auto det_inv = 1e0 / determinant(mat);
Matrix<realT, 3, 3> inv;
inv(0,0) = det_inv * (mat(1,1) * mat(2,2) - mat(1,2) * mat(2,1));
inv(1,1) = det_inv * (mat(0,0) * mat(2,2) - mat(0,2) * mat(2,0));
inv(2,2) = det_inv * (mat(0,0) * mat(1,1) - mat(0,1) * mat(1,0));
inv(0,1) = det_inv * (mat(0,2) * mat(2,1) - mat(0,1) * mat(2,2));
inv(0,2) = det_inv * (mat(0,1) * mat(1,2) - mat(0,2) * mat(1,1));
inv(1,2) = det_inv * (mat(0,2) * mat(1,0) - mat(0,0) * mat(1,2));
inv(1,0) = det_inv * (mat(1,2) * mat(2,0) - mat(1,0) * mat(2,2));
inv(2,0) = det_inv * (mat(1,0) * mat(2,1) - mat(2,0) * mat(1,1));
inv(2,1) = det_inv * (mat(2,0) * mat(0,1) - mat(0,0) * mat(2,1));
return inv;
}
template<typename T, std::size_t S1, std::size_t S2>
struct scalar_type_of<Matrix<T, S1, S2>>
{
typedef T type;
};
} // mjolnir
#endif /* MJOLNIR_MATH_MATRIX */
<|endoftext|> |
<commit_before>#include "vm.hpp"
#include "builtin/bytearray.hpp"
#include "builtin/string.hpp"
#include "primitives.hpp"
#include <cxxtest/TestSuite.h>
using namespace rubinius;
class TestByteArray : public CxxTest::TestSuite {
public:
VM * state;
void setUp() {
state = new VM();
}
void tearDown() {
delete state;
}
void test_create() {
size_t mag = sizeof(OBJECT);
ByteArray* b;
for(size_t i = 0; i <= mag; i++) {
b = ByteArray::create(state, i);
TS_ASSERT_EQUALS(b->size(state)->to_native(), mag);
}
for(size_t i = mag + 1; i <= 2 * mag; i++) {
b = ByteArray::create(state, i);
TS_ASSERT_EQUALS(b->size(state)->to_native(), 2 * mag);
}
for(size_t i = 5 * mag + 1; i <= 6 * mag; i++) {
b = ByteArray::create(state, i);
TS_ASSERT_EQUALS(b->size(state)->to_native(), 6 * mag);
}
}
void test_allocate() {
ByteArray* b = ByteArray::allocate(state, Fixnum::from(5));
TS_ASSERT_EQUALS(b->size(state)->to_native(), 8);
}
void test_size() {
ByteArray* b = ByteArray::create(state, 0);
TS_ASSERT_EQUALS(b->size(state), Fixnum::from(4));
}
void test_to_chars() {
String* s = String::create(state, "xy");
ByteArray* b = s->data;
char* chars = b->to_chars(state);
TS_ASSERT_SAME_DATA("xy", chars, 2);
}
void test_get_byte() {
ByteArray* b = String::create(state, "xyz")->data;
TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(0)), Fixnum::from('x'));
TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(2)), Fixnum::from('z'));
}
void test_get_byte_index_out_of_bounds() {
ByteArray* b = String::create(state, "xyz")->data;
native_int sz = b->size(state)->to_native();
TS_ASSERT_THROWS(b->get_byte(state, Fixnum::from(sz)), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->get_byte(state, Fixnum::from(sz+1)), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->get_byte(state, Fixnum::from(-1)), const PrimitiveFailed &);
}
void test_set_byte() {
ByteArray* b = String::create(state, "xyz")->data;
b->set_byte(state, Fixnum::from(0), Fixnum::from('1'));
TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(0)), Fixnum::from('1'));
b->set_byte(state, Fixnum::from(2), Fixnum::from('2'));
TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(2)), Fixnum::from('2'));
}
void test_set_byte_out_of_bounds() {
ByteArray* b = String::create(state, "xyz")->data;
native_int sz = b->size(state)->to_native();
TS_ASSERT_THROWS(b->set_byte(state, Fixnum::from(sz), Fixnum::from('0')), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->set_byte(state, Fixnum::from(sz+1), Fixnum::from('0')), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->set_byte(state, Fixnum::from(-1), Fixnum::from('0')), const PrimitiveFailed &);
}
void test_move_bytes() {
String* s = String::create(state, "xyzzy");
ByteArray* b = s->data;
b->move_bytes(state, Fixnum::from(0), Fixnum::from(2), Fixnum::from(3));
TS_ASSERT_SAME_DATA(b->bytes, "xyzxy", 5);
}
void test_move_bytes_out_of_bounds() {
ByteArray* b = String::create(state, "xyzzy")->data;
INTEGER neg = Fixnum::from(-1);
INTEGER one = Fixnum::from(1);
INTEGER zero = Fixnum::from(0);
INTEGER size = b->size(state);
INTEGER size1 = Fixnum::from(b->size(state)->to_native()+1);
TS_ASSERT_THROWS(b->move_bytes(state, neg, zero, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, zero, neg, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, zero, zero, neg), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, zero, size1, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, zero, size, one), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, one, size, zero), const PrimitiveFailed &);
}
void test_fetch_bytes() {
String* s = String::create(state, "xyzzy");
ByteArray* b = s->data;
ByteArray* ba = b->fetch_bytes(state, Fixnum::from(1), Fixnum::from(3));
TS_ASSERT_SAME_DATA(ba->bytes, "yzz", 3);
}
void test_fetch_bytes_out_of_bounds() {
ByteArray* b = String::create(state, "xyzzy")->data;
INTEGER neg = Fixnum::from(-1);
INTEGER zero = Fixnum::from(0);
INTEGER one = Fixnum::from(1);
INTEGER size = b->size(state);
INTEGER size1 = Fixnum::from(b->size(state)->to_native()+1);
TS_ASSERT_THROWS(b->fetch_bytes(state, neg, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->fetch_bytes(state, zero, neg), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->fetch_bytes(state, zero, size1), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->fetch_bytes(state, one, size), const PrimitiveFailed &);
}
void test_compare_bytes() {
ByteArray* a = String::create(state, "xyZzyx")->data;
ByteArray* b = String::create(state, "xyzzyx")->data;
INTEGER two = Fixnum::from(2);
INTEGER three = Fixnum::from(3);
INTEGER size = Fixnum::from(8);
INTEGER size1 = Fixnum::from(9);
TS_ASSERT_EQUALS(a->size(state)->to_native(), 8);
TS_ASSERT_EQUALS(b->size(state)->to_native(), 8);
TS_ASSERT_EQUALS(a->compare_bytes(state, b, two, two), Fixnum::from(0));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, two, three), Fixnum::from(-1));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, three, two), Fixnum::from(1));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, three, three), Fixnum::from(-1));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, size, size), Fixnum::from(-1));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, size1, size1), Fixnum::from(-1));
}
void test_compare_bytes_out_of_bounds() {
ByteArray* a = String::create(state, "xyZzy")->data;
ByteArray* b = String::create(state, "xyzzy")->data;
INTEGER zero = Fixnum::from(0);
INTEGER neg = Fixnum::from(-1);
TS_ASSERT_THROWS(a->compare_bytes(state, b, neg, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(a->compare_bytes(state, b, zero, neg), const PrimitiveFailed &);
}
void test_dup_into() {
ByteArray* a = String::create(state, "xyZzyx")->data;
ByteArray* b = ByteArray::create(state, 5);
TS_ASSERT_EQUALS(a->size(state)->to_native(), 8);
TS_ASSERT_EQUALS(b->size(state)->to_native(), 8);
a->dup_into(state, b);
TS_ASSERT_SAME_DATA(b->bytes, "xyZzyx", 7);
ByteArray* c = ByteArray::create(state, 0);
TS_ASSERT_EQUALS(c->size(state)->to_native(), 4);
a->dup_into(state, c);
TS_ASSERT_SAME_DATA(c->bytes, "xyZz", 4);
ByteArray* d = ByteArray::create(state, 12);
a->dup_into(state, d);
TS_ASSERT_SAME_DATA(d->bytes, "xyZzyx", 7);
}
};
<commit_msg>Cast comparison value to native_int to make stricter compilers happy.<commit_after>#include "vm.hpp"
#include "builtin/bytearray.hpp"
#include "builtin/string.hpp"
#include "primitives.hpp"
#include <cxxtest/TestSuite.h>
using namespace rubinius;
class TestByteArray : public CxxTest::TestSuite {
public:
VM * state;
void setUp() {
state = new VM();
}
void tearDown() {
delete state;
}
void test_create() {
size_t mag = sizeof(OBJECT);
ByteArray* b;
for(size_t i = 0; i <= mag; i++) {
b = ByteArray::create(state, i);
TS_ASSERT_EQUALS(b->size(state)->to_native(), (native_int)mag);
}
for(size_t i = mag + 1; i <= 2 * mag; i++) {
b = ByteArray::create(state, i);
TS_ASSERT_EQUALS(b->size(state)->to_native(), (native_int)(2 * mag));
}
for(size_t i = 5 * mag + 1; i <= 6 * mag; i++) {
b = ByteArray::create(state, i);
TS_ASSERT_EQUALS(b->size(state)->to_native(), (native_int)(6 * mag));
}
}
void test_allocate() {
ByteArray* b = ByteArray::allocate(state, Fixnum::from(5));
TS_ASSERT_EQUALS(b->size(state)->to_native(), 8);
}
void test_size() {
ByteArray* b = ByteArray::create(state, 0);
TS_ASSERT_EQUALS(b->size(state), Fixnum::from(4));
}
void test_to_chars() {
String* s = String::create(state, "xy");
ByteArray* b = s->data;
char* chars = b->to_chars(state);
TS_ASSERT_SAME_DATA("xy", chars, 2);
}
void test_get_byte() {
ByteArray* b = String::create(state, "xyz")->data;
TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(0)), Fixnum::from('x'));
TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(2)), Fixnum::from('z'));
}
void test_get_byte_index_out_of_bounds() {
ByteArray* b = String::create(state, "xyz")->data;
native_int sz = b->size(state)->to_native();
TS_ASSERT_THROWS(b->get_byte(state, Fixnum::from(sz)), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->get_byte(state, Fixnum::from(sz+1)), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->get_byte(state, Fixnum::from(-1)), const PrimitiveFailed &);
}
void test_set_byte() {
ByteArray* b = String::create(state, "xyz")->data;
b->set_byte(state, Fixnum::from(0), Fixnum::from('1'));
TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(0)), Fixnum::from('1'));
b->set_byte(state, Fixnum::from(2), Fixnum::from('2'));
TS_ASSERT_EQUALS(b->get_byte(state, Fixnum::from(2)), Fixnum::from('2'));
}
void test_set_byte_out_of_bounds() {
ByteArray* b = String::create(state, "xyz")->data;
native_int sz = b->size(state)->to_native();
TS_ASSERT_THROWS(b->set_byte(state, Fixnum::from(sz), Fixnum::from('0')), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->set_byte(state, Fixnum::from(sz+1), Fixnum::from('0')), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->set_byte(state, Fixnum::from(-1), Fixnum::from('0')), const PrimitiveFailed &);
}
void test_move_bytes() {
String* s = String::create(state, "xyzzy");
ByteArray* b = s->data;
b->move_bytes(state, Fixnum::from(0), Fixnum::from(2), Fixnum::from(3));
TS_ASSERT_SAME_DATA(b->bytes, "xyzxy", 5);
}
void test_move_bytes_out_of_bounds() {
ByteArray* b = String::create(state, "xyzzy")->data;
INTEGER neg = Fixnum::from(-1);
INTEGER one = Fixnum::from(1);
INTEGER zero = Fixnum::from(0);
INTEGER size = b->size(state);
INTEGER size1 = Fixnum::from(b->size(state)->to_native()+1);
TS_ASSERT_THROWS(b->move_bytes(state, neg, zero, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, zero, neg, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, zero, zero, neg), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, zero, size1, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, zero, size, one), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->move_bytes(state, one, size, zero), const PrimitiveFailed &);
}
void test_fetch_bytes() {
String* s = String::create(state, "xyzzy");
ByteArray* b = s->data;
ByteArray* ba = b->fetch_bytes(state, Fixnum::from(1), Fixnum::from(3));
TS_ASSERT_SAME_DATA(ba->bytes, "yzz", 3);
}
void test_fetch_bytes_out_of_bounds() {
ByteArray* b = String::create(state, "xyzzy")->data;
INTEGER neg = Fixnum::from(-1);
INTEGER zero = Fixnum::from(0);
INTEGER one = Fixnum::from(1);
INTEGER size = b->size(state);
INTEGER size1 = Fixnum::from(b->size(state)->to_native()+1);
TS_ASSERT_THROWS(b->fetch_bytes(state, neg, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->fetch_bytes(state, zero, neg), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->fetch_bytes(state, zero, size1), const PrimitiveFailed &);
TS_ASSERT_THROWS(b->fetch_bytes(state, one, size), const PrimitiveFailed &);
}
void test_compare_bytes() {
ByteArray* a = String::create(state, "xyZzyx")->data;
ByteArray* b = String::create(state, "xyzzyx")->data;
INTEGER two = Fixnum::from(2);
INTEGER three = Fixnum::from(3);
INTEGER size = Fixnum::from(8);
INTEGER size1 = Fixnum::from(9);
TS_ASSERT_EQUALS(a->size(state)->to_native(), 8);
TS_ASSERT_EQUALS(b->size(state)->to_native(), 8);
TS_ASSERT_EQUALS(a->compare_bytes(state, b, two, two), Fixnum::from(0));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, two, three), Fixnum::from(-1));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, three, two), Fixnum::from(1));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, three, three), Fixnum::from(-1));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, size, size), Fixnum::from(-1));
TS_ASSERT_EQUALS(a->compare_bytes(state, b, size1, size1), Fixnum::from(-1));
}
void test_compare_bytes_out_of_bounds() {
ByteArray* a = String::create(state, "xyZzy")->data;
ByteArray* b = String::create(state, "xyzzy")->data;
INTEGER zero = Fixnum::from(0);
INTEGER neg = Fixnum::from(-1);
TS_ASSERT_THROWS(a->compare_bytes(state, b, neg, zero), const PrimitiveFailed &);
TS_ASSERT_THROWS(a->compare_bytes(state, b, zero, neg), const PrimitiveFailed &);
}
void test_dup_into() {
ByteArray* a = String::create(state, "xyZzyx")->data;
ByteArray* b = ByteArray::create(state, 5);
TS_ASSERT_EQUALS(a->size(state)->to_native(), 8);
TS_ASSERT_EQUALS(b->size(state)->to_native(), 8);
a->dup_into(state, b);
TS_ASSERT_SAME_DATA(b->bytes, "xyZzyx", 7);
ByteArray* c = ByteArray::create(state, 0);
TS_ASSERT_EQUALS(c->size(state)->to_native(), 4);
a->dup_into(state, c);
TS_ASSERT_SAME_DATA(c->bytes, "xyZz", 4);
ByteArray* d = ByteArray::create(state, 12);
a->dup_into(state, d);
TS_ASSERT_SAME_DATA(d->bytes, "xyZzyx", 7);
}
};
<|endoftext|> |
<commit_before>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "corebuiltins.hh"
#include "coreinterfaces.hh"
#include <iostream>
#include "emulate.hh"
#include "exchelpers.hh"
namespace builtins {
BuiltinResult equals(VM vm, UnstableNode* args[]) {
Equatable x = *args[0];
return x.equals(vm, args[1], args[2]);
}
BuiltinResult notEquals(VM vm, UnstableNode* args[]) {
Equatable x = *args[0];
BuiltinResult result = x.equals(vm, args[1], args[2]);
if (result.isProceed()) {
RichNode richResult = *args[2];
assert(richResult.type() == Boolean::type());
bool equalsResult = richResult.as<Boolean>().value();
args[2]->make<Boolean>(vm, !equalsResult);
}
return result;
}
BuiltinResult add(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.add(vm, args[1], args[2]);
}
BuiltinResult subtract(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.subtract(vm, args[1], args[2]);
}
BuiltinResult multiply(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.multiply(vm, args[1], args[2]);
}
BuiltinResult divide(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.divide(vm, args[1], args[2]);
}
BuiltinResult div(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.div(vm, args[1], args[2]);
}
BuiltinResult mod(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.mod(vm, args[1], args[2]);
}
BuiltinResult width(VM vm, UnstableNode* args[]) {
RecordLike x = *args[0];
return x.width(vm, args[1]);
}
BuiltinResult dot(VM vm, UnstableNode* args[]) {
RecordLike x = *args[0];
return x.dot(vm, args[1], args[2]);
}
BuiltinResult createThread(VM vm, UnstableNode* args[]) {
int arity;
StableNode* body;
ProgramCounter start;
int Xcount;
StaticArray<StableNode> Gs;
StaticArray<StableNode> Ks;
RichNode target = *args[0];
Callable x = target;
BuiltinResult result = x.getCallInfo(vm, &arity, &body, &start,
&Xcount, &Gs, &Ks);
if (!result.isProceed())
return result;
if (arity != 0)
return raiseAtom(vm, u"illegalArity");
new (vm) Thread(vm, target.getStableRef(vm));
return BuiltinResult::proceed();
}
BuiltinResult show(VM vm, UnstableNode* args[]) {
RichNode arg = *args[0];
printReprToStream(vm, arg, std::cout);
std::cout << std::endl;
return BuiltinResult::proceed();
}
void printReprToStream(VM vm, RichNode arg,
std::ostream& out, int depth) {
if (depth <= 0) {
out << "...";
return;
}
if (arg.type() == SmallInt::type()) {
out << arg.as<SmallInt>().value();
} else if (arg.type() == Boolean::type()) {
out << (arg.as<Boolean>().value() ? "true" : "false");
} else if (arg.type() == Float::type()) {
out << arg.as<Float>().value();
} else if (arg.type() == Atom::type()) {
arg.as<Atom>().printReprToStream(vm, &out, depth);
} else if (arg.type() == Tuple::type()) {
arg.as<Tuple>().printReprToStream(vm, &out, depth);
} else if (arg.type()->isTransient()) {
out << "_";
} else {
out << "<" << arg.type()->getName() << ">";
}
}
}
<commit_msg>Fixed compiler warning.<commit_after>// Copyright © 2011, Université catholique de Louvain
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "corebuiltins.hh"
#include "coreinterfaces.hh"
#include <iostream>
#include "emulate.hh"
#include "exchelpers.hh"
namespace builtins {
BuiltinResult equals(VM vm, UnstableNode* args[]) {
Equatable x = *args[0];
return x.equals(vm, args[1], args[2]);
}
BuiltinResult notEquals(VM vm, UnstableNode* args[]) {
Equatable x = *args[0];
BuiltinResult result = x.equals(vm, args[1], args[2]);
if (result.isProceed()) {
RichNode richResult = *args[2];
assert(richResult.type() == Boolean::type());
bool equalsResult = richResult.as<Boolean>().value();
args[2]->make<Boolean>(vm, !equalsResult);
}
return result;
}
BuiltinResult add(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.add(vm, args[1], args[2]);
}
BuiltinResult subtract(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.subtract(vm, args[1], args[2]);
}
BuiltinResult multiply(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.multiply(vm, args[1], args[2]);
}
BuiltinResult divide(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.divide(vm, args[1], args[2]);
}
BuiltinResult div(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.div(vm, args[1], args[2]);
}
BuiltinResult mod(VM vm, UnstableNode* args[]) {
Numeric x = *args[0];
return x.mod(vm, args[1], args[2]);
}
BuiltinResult width(VM vm, UnstableNode* args[]) {
RecordLike x = *args[0];
return x.width(vm, args[1]);
}
BuiltinResult dot(VM vm, UnstableNode* args[]) {
RecordLike x = *args[0];
return x.dot(vm, args[1], args[2]);
}
BuiltinResult createThread(VM vm, UnstableNode* args[]) {
int arity = 0;
StableNode* body;
ProgramCounter start;
int Xcount;
StaticArray<StableNode> Gs;
StaticArray<StableNode> Ks;
RichNode target = *args[0];
Callable x = target;
BuiltinResult result = x.getCallInfo(vm, &arity, &body, &start,
&Xcount, &Gs, &Ks);
if (!result.isProceed())
return result;
if (arity != 0)
return raiseAtom(vm, u"illegalArity");
new (vm) Thread(vm, target.getStableRef(vm));
return BuiltinResult::proceed();
}
BuiltinResult show(VM vm, UnstableNode* args[]) {
RichNode arg = *args[0];
printReprToStream(vm, arg, std::cout);
std::cout << std::endl;
return BuiltinResult::proceed();
}
void printReprToStream(VM vm, RichNode arg,
std::ostream& out, int depth) {
if (depth <= 0) {
out << "...";
return;
}
if (arg.type() == SmallInt::type()) {
out << arg.as<SmallInt>().value();
} else if (arg.type() == Boolean::type()) {
out << (arg.as<Boolean>().value() ? "true" : "false");
} else if (arg.type() == Float::type()) {
out << arg.as<Float>().value();
} else if (arg.type() == Atom::type()) {
arg.as<Atom>().printReprToStream(vm, &out, depth);
} else if (arg.type() == Tuple::type()) {
arg.as<Tuple>().printReprToStream(vm, &out, depth);
} else if (arg.type()->isTransient()) {
out << "_";
} else {
out << "<" << arg.type()->getName() << ">";
}
}
}
<|endoftext|> |
<commit_before>const char* esd_geom_file_name = "http://root.cern.ch/files/alice_ESDgeometry.root";
void projection_test()
{
TFile::SetCacheFileDir(".");
TEveManager::Create();
// camera
TEveScene* s = gEve->SpawnNewScene("Projected Event");
gEve->GetDefViewer()->AddScene(s);
TGLViewer* v = (TGLViewer *)gEve->GetGLViewer();
v->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
TGLOrthoCamera* cam = (TGLOrthoCamera*) v->CurrentCamera();
cam->SetZoomMinMax(0.2, 20);
TGLCameraMarkupStyle* mup = v->GetCameraMarkup();
if(mup) mup->SetShow(kFALSE);
// projections
TEveProjectionManager* mng = new TEveProjectionManager();
gEve->AddElement(mng, s);
TEveProjectionAxes* axes = new TEveProjectionAxes(mng);
axes->SetText("TEveProjections demo");
axes->SetFontFile("comicbd");
axes->SetFontSize(20);
gEve->AddGlobalElement(axes);
gEve->AddToListTree(axes, kTRUE);
gEve->AddToListTree(mng, kTRUE);
// Simple geometry
TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD");
if (!geom)
return;
TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle");
TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse, 0);
geom->Close();
delete geom;
// gEve->AddToListTree(gsre);
mng->ImportElements(gsre);
TEveLine* line = new TEveLine;
line->SetMainColor(kGreen);
for (Int_t i=0; i<160; ++i)
line->SetNextPoint(120*sin(0.2*i), 120*cos(0.2*i), 80-i);
gEve->AddElement(line);
mng->ImportElements(line);
line->SetRnrSelf(kFALSE);
gEve->Redraw3D(kTRUE);
}
<commit_msg>Expose also 3d geometry.<commit_after>const char* esd_geom_file_name = "http://root.cern.ch/files/alice_ESDgeometry.root";
void projection_test()
{
TFile::SetCacheFileDir(".");
TEveManager::Create();
// camera
TEveScene* s = gEve->SpawnNewScene("Projected Event");
gEve->GetDefViewer()->AddScene(s);
TGLViewer* v = (TGLViewer *)gEve->GetGLViewer();
v->SetCurrentCamera(TGLViewer::kCameraOrthoXOY);
TGLOrthoCamera* cam = (TGLOrthoCamera*) v->CurrentCamera();
cam->SetZoomMinMax(0.2, 20);
TGLCameraMarkupStyle* mup = v->GetCameraMarkup();
if (mup) mup->SetShow(kFALSE);
// projections
TEveProjectionManager* mng = new TEveProjectionManager();
s->AddElement(mng);
TEveProjectionAxes* axes = new TEveProjectionAxes(mng);
axes->SetText("TEveProjections demo");
axes->SetFontFile("comicbd");
axes->SetFontSize(20);
s->AddElement(axes);
gEve->AddToListTree(axes, kTRUE);
gEve->AddToListTree(mng, kTRUE);
// Simple geometry
TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD");
if (!geom)
return;
TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle");
TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse, 0);
geom->Close();
delete geom;
gEve->AddGlobalElement(gsre);
gEve->GetGlobalScene()->SetRnrState(kFALSE);
mng->ImportElements(gsre);
TEveLine* line = new TEveLine;
line->SetMainColor(kGreen);
for (Int_t i=0; i<160; ++i)
line->SetNextPoint(120*sin(0.2*i), 120*cos(0.2*i), 80-i);
gEve->AddElement(line);
mng->ImportElements(line);
line->SetRnrSelf(kFALSE);
gEve->Redraw3D(kTRUE);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_gui_system.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2007-09-06 13:52:24 $
*
* 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 2006 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_desktop.hxx"
#include "dp_gui_system.hxx"
#ifdef WNT
#define WIN32_LEAN_AND_MEAN
#ifdef _MSC_VER
#pragma warning(push,1) /* disable warnings within system headers */
#endif
#include <windows.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
namespace dp_gui {
//We cannot distinguish Vista and 2008 Server
bool isVista()
{
#ifdef WNT
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
return osvi.dwMajorVersion >= 6;
#else
return false;
#endif
}
} //namespace dp_gui
<commit_msg>INTEGRATION: CWS changefileheader (1.3.146); FILE MERGED 2008/03/28 15:26:37 rt 1.3.146.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: dp_gui_system.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_gui_system.hxx"
#ifdef WNT
#define WIN32_LEAN_AND_MEAN
#ifdef _MSC_VER
#pragma warning(push,1) /* disable warnings within system headers */
#endif
#include <windows.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
namespace dp_gui {
//We cannot distinguish Vista and 2008 Server
bool isVista()
{
#ifdef WNT
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
return osvi.dwMajorVersion >= 6;
#else
return false;
#endif
}
} //namespace dp_gui
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <osquery/logger.h>
#include <osquery/tables.h>
#include "osquery/core/conversions.h"
#include "osquery/events/darwin/iokit_hid.h"
namespace osquery {
REGISTER_EVENTPUBLISHER(IOKitHIDEventPublisher);
size_t IOKitHIDEventPublisher::initial_device_count_ = 0;
size_t IOKitHIDEventPublisher::initial_device_evented_count_ = 0;
boost::mutex IOKitHIDEventPublisher::iokit_match_lock_;
std::string IOKitHIDEventPublisher::getProperty(const IOHIDDeviceRef &device,
const CFStringRef &property) {
CFTypeRef value = IOHIDDeviceGetProperty(device, property);
if (value == NULL) {
return "";
}
// Only support CFNumber and CFString types.
if (CFGetTypeID(value) == CFNumberGetTypeID()) {
return stringFromCFNumber((CFDataRef)value);
} else if (CFGetTypeID(value) == CFStringGetTypeID()) {
return stringFromCFString((CFStringRef)value);
}
return "";
}
void IOKitHIDEventPublisher::restart() {
if (run_loop_ == nullptr) {
// There is no run loop to restart.
return;
}
// Remove any existing stream.
stop();
if (manager_ == nullptr) {
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
}
// Match anything.
IOHIDManagerSetDeviceMatching(manager_, NULL);
auto status = IOHIDManagerOpen(manager_, kIOHIDOptionsTypeNone);
if (status != kIOReturnSuccess) {
LOG(ERROR) << "Cannot open IOKit HID Manager";
return;
}
// Enumerate initial set of devices matched before time=0.
CFSetRef devices = IOHIDManagerCopyDevices(manager_);
initial_device_count_ = devices == NULL ? 0 : CFSetGetCount(devices);
CFRelease(devices);
// Register callbacks.
IOHIDManagerRegisterDeviceMatchingCallback(
manager_, IOKitHIDEventPublisher::MatchingCallback, NULL);
IOHIDManagerRegisterDeviceRemovalCallback(
manager_, IOKitHIDEventPublisher::RemovalCallback, NULL);
IOHIDManagerScheduleWithRunLoop(manager_, run_loop_, kCFRunLoopDefaultMode);
manager_started_ = true;
}
void IOKitHIDEventPublisher::MatchingCallback(void *context,
IOReturn result,
void *sender,
IOHIDDeviceRef device) {
{
// Must not event on initial list of matches.
boost::lock_guard<boost::mutex> lock(iokit_match_lock_);
if (initial_device_count_ > initial_device_evented_count_) {
initial_device_evented_count_++;
return;
}
}
fire(device, "add");
}
void IOKitHIDEventPublisher::fire(const IOHIDDeviceRef &device,
const std::string &action) {
auto ec = createEventContext();
ec->device = device;
ec->action = action;
// Fill in more-useful fields.
ec->vendor_id = getProperty(device, CFSTR(kIOHIDVendorIDKey));
ec->model_id = getProperty(device, CFSTR(kIOHIDProductIDKey));
ec->vendor = getProperty(device, CFSTR(kIOHIDManufacturerKey));
ec->model = getProperty(device, CFSTR(kIOHIDProductKey));
ec->transport = getProperty(device, CFSTR(kIOHIDTransportKey));
ec->primary_usage = getProperty(device, CFSTR(kIOHIDPrimaryUsageKey));
ec->device_usage = getProperty(device, CFSTR(kIOHIDDeviceUsageKey));
// Fill in more esoteric properties.
ec->version = getProperty(device, CFSTR(kIOHIDVersionNumberKey));
ec->location = getProperty(device, CFSTR(kIOHIDLocationIDKey));
ec->serial = getProperty(device, CFSTR(kIOHIDSerialNumberKey));
ec->country_code = getProperty(device, CFSTR(kIOHIDCountryCodeKey));
EventFactory::fire<IOKitHIDEventPublisher>(ec);
}
void IOKitHIDEventPublisher::RemovalCallback(void *context,
IOReturn result,
void *sender,
IOHIDDeviceRef device) {
fire(device, "remove");
}
void IOKitHIDEventPublisher::InputValueCallback(void *context,
IOReturn result,
void *sender,
IOHIDValueRef value) {
// Nothing yet (do not allow value change subscriptions).
// Value changes contain potentially sensitive data.
}
bool IOKitHIDEventPublisher::shouldFire(
const IOKitHIDSubscriptionContextRef &sc,
const IOKitHIDEventContextRef &ec) {
if (sc->values) {
// See InputValueCallback
return false;
}
if (sc->transport != "" && sc->transport != ec->transport) {
return false;
} else if (sc->model_id != "" && sc->model_id != ec->model_id) {
return false;
} else if (sc->vendor_id != "" && sc->vendor_id != ec->vendor_id) {
return false;
} else if (sc->primary_usage != "" &&
sc->primary_usage != ec->primary_usage) {
return false;
} else if (sc->device_usage != "" && sc->device_usage != ec->device_usage) {
return false;
}
return true;
}
Status IOKitHIDEventPublisher::run() {
// The run entrypoint executes in a dedicated thread.
if (run_loop_ == nullptr) {
run_loop_ = CFRunLoopGetCurrent();
// Restart the stream creation.
restart();
}
// Start the run loop, it may be removed with a tearDown.
CFRunLoopRun();
// Add artificial latency to run loop.
::sleep(1);
return Status(0, "OK");
}
void IOKitHIDEventPublisher::stop() {
// Stop the manager.
if (manager_ != nullptr) {
IOHIDManagerUnscheduleFromRunLoop(
manager_, run_loop_, kCFRunLoopDefaultMode);
IOHIDManagerClose(manager_, kIOHIDOptionsTypeNone);
manager_started_ = false;
manager_ = nullptr;
}
// Stop the run loop.
if (run_loop_ != nullptr) {
CFRunLoopStop(run_loop_);
}
}
void IOKitHIDEventPublisher::tearDown() {
stop();
// Do not keep a reference to the run loop.
run_loop_ = nullptr;
}
}
<commit_msg>Treat IOKit HID failures as warnings<commit_after>/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <osquery/logger.h>
#include <osquery/tables.h>
#include "osquery/core/conversions.h"
#include "osquery/events/darwin/iokit_hid.h"
namespace osquery {
REGISTER_EVENTPUBLISHER(IOKitHIDEventPublisher);
size_t IOKitHIDEventPublisher::initial_device_count_ = 0;
size_t IOKitHIDEventPublisher::initial_device_evented_count_ = 0;
boost::mutex IOKitHIDEventPublisher::iokit_match_lock_;
std::string IOKitHIDEventPublisher::getProperty(const IOHIDDeviceRef &device,
const CFStringRef &property) {
CFTypeRef value = IOHIDDeviceGetProperty(device, property);
if (value == NULL) {
return "";
}
// Only support CFNumber and CFString types.
if (CFGetTypeID(value) == CFNumberGetTypeID()) {
return stringFromCFNumber((CFDataRef)value);
} else if (CFGetTypeID(value) == CFStringGetTypeID()) {
return stringFromCFString((CFStringRef)value);
}
return "";
}
void IOKitHIDEventPublisher::restart() {
if (run_loop_ == nullptr) {
// There is no run loop to restart.
return;
}
// Remove any existing stream.
stop();
if (manager_ == nullptr) {
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
}
// Match anything.
IOHIDManagerSetDeviceMatching(manager_, NULL);
auto status = IOHIDManagerOpen(manager_, kIOHIDOptionsTypeNone);
if (status != kIOReturnSuccess) {
LOG(WARNING) << "[Reference #617] Cannot open IOKit HID Manager";
return;
}
// Enumerate initial set of devices matched before time=0.
CFSetRef devices = IOHIDManagerCopyDevices(manager_);
initial_device_count_ = devices == NULL ? 0 : CFSetGetCount(devices);
CFRelease(devices);
// Register callbacks.
IOHIDManagerRegisterDeviceMatchingCallback(
manager_, IOKitHIDEventPublisher::MatchingCallback, NULL);
IOHIDManagerRegisterDeviceRemovalCallback(
manager_, IOKitHIDEventPublisher::RemovalCallback, NULL);
IOHIDManagerScheduleWithRunLoop(manager_, run_loop_, kCFRunLoopDefaultMode);
manager_started_ = true;
}
void IOKitHIDEventPublisher::MatchingCallback(void *context,
IOReturn result,
void *sender,
IOHIDDeviceRef device) {
{
// Must not event on initial list of matches.
boost::lock_guard<boost::mutex> lock(iokit_match_lock_);
if (initial_device_count_ > initial_device_evented_count_) {
initial_device_evented_count_++;
return;
}
}
fire(device, "add");
}
void IOKitHIDEventPublisher::fire(const IOHIDDeviceRef &device,
const std::string &action) {
auto ec = createEventContext();
ec->device = device;
ec->action = action;
// Fill in more-useful fields.
ec->vendor_id = getProperty(device, CFSTR(kIOHIDVendorIDKey));
ec->model_id = getProperty(device, CFSTR(kIOHIDProductIDKey));
ec->vendor = getProperty(device, CFSTR(kIOHIDManufacturerKey));
ec->model = getProperty(device, CFSTR(kIOHIDProductKey));
ec->transport = getProperty(device, CFSTR(kIOHIDTransportKey));
ec->primary_usage = getProperty(device, CFSTR(kIOHIDPrimaryUsageKey));
ec->device_usage = getProperty(device, CFSTR(kIOHIDDeviceUsageKey));
// Fill in more esoteric properties.
ec->version = getProperty(device, CFSTR(kIOHIDVersionNumberKey));
ec->location = getProperty(device, CFSTR(kIOHIDLocationIDKey));
ec->serial = getProperty(device, CFSTR(kIOHIDSerialNumberKey));
ec->country_code = getProperty(device, CFSTR(kIOHIDCountryCodeKey));
EventFactory::fire<IOKitHIDEventPublisher>(ec);
}
void IOKitHIDEventPublisher::RemovalCallback(void *context,
IOReturn result,
void *sender,
IOHIDDeviceRef device) {
fire(device, "remove");
}
void IOKitHIDEventPublisher::InputValueCallback(void *context,
IOReturn result,
void *sender,
IOHIDValueRef value) {
// Nothing yet (do not allow value change subscriptions).
// Value changes contain potentially sensitive data.
}
bool IOKitHIDEventPublisher::shouldFire(
const IOKitHIDSubscriptionContextRef &sc,
const IOKitHIDEventContextRef &ec) {
if (sc->values) {
// See InputValueCallback
return false;
}
if (sc->transport != "" && sc->transport != ec->transport) {
return false;
} else if (sc->model_id != "" && sc->model_id != ec->model_id) {
return false;
} else if (sc->vendor_id != "" && sc->vendor_id != ec->vendor_id) {
return false;
} else if (sc->primary_usage != "" &&
sc->primary_usage != ec->primary_usage) {
return false;
} else if (sc->device_usage != "" && sc->device_usage != ec->device_usage) {
return false;
}
return true;
}
Status IOKitHIDEventPublisher::run() {
// The run entrypoint executes in a dedicated thread.
if (run_loop_ == nullptr) {
run_loop_ = CFRunLoopGetCurrent();
// Restart the stream creation.
restart();
}
// Start the run loop, it may be removed with a tearDown.
CFRunLoopRun();
// Add artificial latency to run loop.
::sleep(1);
return Status(0, "OK");
}
void IOKitHIDEventPublisher::stop() {
// Stop the manager.
if (manager_ != nullptr) {
IOHIDManagerUnscheduleFromRunLoop(
manager_, run_loop_, kCFRunLoopDefaultMode);
IOHIDManagerClose(manager_, kIOHIDOptionsTypeNone);
manager_started_ = false;
manager_ = nullptr;
}
// Stop the run loop.
if (run_loop_ != nullptr) {
CFRunLoopStop(run_loop_);
}
}
void IOKitHIDEventPublisher::tearDown() {
stop();
// Do not keep a reference to the run loop.
run_loop_ = nullptr;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// 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 <stingraykit/Random.h>
#include <ctime>
namespace stingray
{
Random::Random()
: _seed(std::time(0))
{ }
Random::Random(u32 seed)
: _seed(seed)
{ }
u32 Random::Next(u32 maxValue)
{ return Next() % maxValue; }
u32 Random::Next()
{
_seed = _seed * 1664525U + 1013904223U;
return _seed;
}
}
<commit_msg>strip lower bits for small random numbers<commit_after>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// 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 <stingraykit/Random.h>
#include <ctime>
namespace stingray
{
Random::Random()
: _seed(std::time(0))
{ }
Random::Random(u32 seed)
: _seed(seed)
{ }
u32 Random::Next(u32 maxValue)
{
static const u32 MaxRandBits = 16;
static const u32 MaxRand = (1 << MaxRandBits);
u32 next = Next();
if (maxValue < MaxRand)
next >>= MaxRandBits;
return next % maxValue;
}
u32 Random::Next()
{
_seed = _seed * 1664525U + 1013904223U;
return _seed;
}
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. 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 <fnord-cstable/RecordMaterializer.h>
namespace fnord {
namespace cstable {
RecordMaterializer::RecordMaterializer(
msg::MessageSchema* schema,
CSTableReader* reader) {
for (const auto& f : schema->fields) {
createColumns("", 0, Vector<Tuple<uint64_t, bool, uint32_t>>{}, f, reader);
}
}
void RecordMaterializer::nextRecord(msg::MessageObject* record) {
for (auto& col : columns_) {
loadColumn(col.first, &col.second, record);
}
}
void RecordMaterializer::loadColumn(
const String& column_name,
ColumnState* column,
msg::MessageObject* record) {
Vector<size_t> indexes(column->reader->maxRepetitionLevel());
for (;;) {
column->fetchIfNotPending();
if (column->r > 0) {
++indexes[column->r - 1];
for (int x = column->r; x < indexes.size(); ++x) {
indexes[x] = 0;
}
}
if (column->defined) {
insertValue(column, column->parents, indexes, record);
} else {
insertNull(column, column->parents, indexes, record);
}
column->consume();
if (column->reader->eofReached()) {
break;
}
column->fetchIfNotPending();
if (column->r == 0) {
return;
}
}
}
void RecordMaterializer::createColumns(
const String& prefix,
uint32_t dmax,
Vector<Tuple<uint64_t, bool, uint32_t>> parents,
const msg::MessageSchemaField& field,
CSTableReader* reader) {
auto colname = prefix + field.name;
if (field.repeated || field.optional) {
++dmax;
}
switch (field.type) {
case msg::FieldType::OBJECT: {
parents.emplace_back(field.id, field.repeated, dmax);
for (const auto& f : field.fields) {
createColumns(colname + ".", dmax, parents, f, reader);
}
break;
}
default: {
ColumnState colstate(reader->getColumnReader(colname));
colstate.parents = parents;
colstate.field_id = field.id;
colstate.field_type = field.type;
columns_.emplace(colname, colstate);
break;
}
}
}
void RecordMaterializer::insertValue(
ColumnState* column,
Vector<Tuple<uint64_t, bool, uint32_t>> parents,
Vector<size_t> indexes,
msg::MessageObject* record) {
if (parents.size() > 0) {
auto parent = parents[0];
parents.erase(parents.begin());
// repeated...
if (std::get<1>(parent)) {
auto target_idx = indexes[0];
size_t this_index = 0;
indexes.erase(indexes.begin());
for (auto& cld : record->asObject()) {
if (cld.id == std::get<0>(parent)) {
if (this_index == target_idx) {
return insertValue(column, parents, indexes, &cld);
}
++this_index;
}
}
for (; this_index < target_idx; ++this_index) {
record->addChild(std::get<0>(parent));
}
auto& new_cld = record->addChild(std::get<0>(parent));
return insertValue(column, parents, indexes, &new_cld);
// non repeated
} else {
for (auto& cld : record->asObject()) {
if (cld.id == std::get<0>(parent)) {
return insertValue(column, parents, indexes, &cld);
}
}
auto& new_cld = record->addChild(std::get<0>(parent));
return insertValue(column, parents, indexes, &new_cld);
}
}
switch (column->field_type) {
case msg::FieldType::OBJECT:
break;
case msg::FieldType::STRING:
record->addChild(
column->field_id,
String((char*) column->data, column->size));
break;
}
}
void RecordMaterializer::insertNull(
ColumnState* column,
Vector<Tuple<uint64_t, bool, uint32_t>> parents,
Vector<size_t> indexes,
msg::MessageObject* record) {
if (parents.size() > 0) {
auto parent = parents[0];
parents.erase(parents.begin());
// definition level
if (std::get<2>(parent) > column->d) {
return;
}
// repeated...
if (std::get<1>(parent)) {
auto target_idx = indexes[0];
size_t this_index = 0;
indexes.erase(indexes.begin());
for (auto& cld : record->asObject()) {
if (cld.id == std::get<0>(parent)) {
if (this_index == target_idx) {
return insertNull(column, parents, indexes, &cld);
}
++this_index;
}
}
for (; this_index < target_idx; ++this_index) {
record->addChild(std::get<0>(parent));
}
auto& new_cld = record->addChild(std::get<0>(parent));
return insertNull(column, parents, indexes, &new_cld);
// non repeated
} else {
for (auto& cld : record->asObject()) {
if (cld.id == std::get<0>(parent)) {
return insertNull(column, parents, indexes, &cld);
}
}
auto& new_cld = record->addChild(std::get<0>(parent));
return insertNull(column, parents, indexes, &new_cld);
}
}
}
void RecordMaterializer::ColumnState::fetchIfNotPending() {
if (pending) {
return;
}
defined = reader->next(&r, &d, &data, &size);
pending = true;
}
void RecordMaterializer::ColumnState::consume() {
pending = false;
}
} // namespace cstable
} // namespace fnord
<commit_msg>impl BOOL, UINT32 in RecordMaterializer<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. 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 <fnord-cstable/RecordMaterializer.h>
namespace fnord {
namespace cstable {
RecordMaterializer::RecordMaterializer(
msg::MessageSchema* schema,
CSTableReader* reader) {
for (const auto& f : schema->fields) {
createColumns("", 0, Vector<Tuple<uint64_t, bool, uint32_t>>{}, f, reader);
}
}
void RecordMaterializer::nextRecord(msg::MessageObject* record) {
for (auto& col : columns_) {
loadColumn(col.first, &col.second, record);
}
}
void RecordMaterializer::loadColumn(
const String& column_name,
ColumnState* column,
msg::MessageObject* record) {
Vector<size_t> indexes(column->reader->maxRepetitionLevel());
for (;;) {
column->fetchIfNotPending();
if (column->r > 0) {
++indexes[column->r - 1];
for (int x = column->r; x < indexes.size(); ++x) {
indexes[x] = 0;
}
}
if (column->defined) {
insertValue(column, column->parents, indexes, record);
} else {
insertNull(column, column->parents, indexes, record);
}
column->consume();
if (column->reader->eofReached()) {
break;
}
column->fetchIfNotPending();
if (column->r == 0) {
return;
}
}
}
void RecordMaterializer::createColumns(
const String& prefix,
uint32_t dmax,
Vector<Tuple<uint64_t, bool, uint32_t>> parents,
const msg::MessageSchemaField& field,
CSTableReader* reader) {
auto colname = prefix + field.name;
if (field.repeated || field.optional) {
++dmax;
}
switch (field.type) {
case msg::FieldType::OBJECT: {
parents.emplace_back(field.id, field.repeated, dmax);
for (const auto& f : field.fields) {
createColumns(colname + ".", dmax, parents, f, reader);
}
break;
}
default: {
ColumnState colstate(reader->getColumnReader(colname));
colstate.parents = parents;
colstate.field_id = field.id;
colstate.field_type = field.type;
columns_.emplace(colname, colstate);
break;
}
}
}
void RecordMaterializer::insertValue(
ColumnState* column,
Vector<Tuple<uint64_t, bool, uint32_t>> parents,
Vector<size_t> indexes,
msg::MessageObject* record) {
if (parents.size() > 0) {
auto parent = parents[0];
parents.erase(parents.begin());
// repeated...
if (std::get<1>(parent)) {
auto target_idx = indexes[0];
size_t this_index = 0;
indexes.erase(indexes.begin());
for (auto& cld : record->asObject()) {
if (cld.id == std::get<0>(parent)) {
if (this_index == target_idx) {
return insertValue(column, parents, indexes, &cld);
}
++this_index;
}
}
for (; this_index < target_idx; ++this_index) {
record->addChild(std::get<0>(parent));
}
auto& new_cld = record->addChild(std::get<0>(parent));
return insertValue(column, parents, indexes, &new_cld);
// non repeated
} else {
for (auto& cld : record->asObject()) {
if (cld.id == std::get<0>(parent)) {
return insertValue(column, parents, indexes, &cld);
}
}
auto& new_cld = record->addChild(std::get<0>(parent));
return insertValue(column, parents, indexes, &new_cld);
}
}
switch (column->field_type) {
case msg::FieldType::OBJECT:
break;
case msg::FieldType::UINT32:
record->addChild(
column->field_id,
*((uint32_t*) column->data));
break;
case msg::FieldType::STRING:
record->addChild(
column->field_id,
String((char*) column->data, column->size));
break;
case msg::FieldType::BOOLEAN:
if (*((uint8_t*) column->data) == 1) {
record->addChild(column->field_id, msg::TRUE);
} else {
record->addChild(column->field_id, msg::FALSE);
}
break;
}
}
void RecordMaterializer::insertNull(
ColumnState* column,
Vector<Tuple<uint64_t, bool, uint32_t>> parents,
Vector<size_t> indexes,
msg::MessageObject* record) {
if (parents.size() > 0) {
auto parent = parents[0];
parents.erase(parents.begin());
// definition level
if (std::get<2>(parent) > column->d) {
return;
}
// repeated...
if (std::get<1>(parent)) {
auto target_idx = indexes[0];
size_t this_index = 0;
indexes.erase(indexes.begin());
for (auto& cld : record->asObject()) {
if (cld.id == std::get<0>(parent)) {
if (this_index == target_idx) {
return insertNull(column, parents, indexes, &cld);
}
++this_index;
}
}
for (; this_index < target_idx; ++this_index) {
record->addChild(std::get<0>(parent));
}
auto& new_cld = record->addChild(std::get<0>(parent));
return insertNull(column, parents, indexes, &new_cld);
// non repeated
} else {
for (auto& cld : record->asObject()) {
if (cld.id == std::get<0>(parent)) {
return insertNull(column, parents, indexes, &cld);
}
}
auto& new_cld = record->addChild(std::get<0>(parent));
return insertNull(column, parents, indexes, &new_cld);
}
}
}
void RecordMaterializer::ColumnState::fetchIfNotPending() {
if (pending) {
return;
}
defined = reader->next(&r, &d, &data, &size);
pending = true;
}
void RecordMaterializer::ColumnState::consume() {
pending = false;
}
} // namespace cstable
} // namespace fnord
<|endoftext|> |
<commit_before>
#include "EClass.hpp"
#include "EAnnotation.hpp"
#include "EcoreFactory.hpp"
#include "EcorePackage.hpp"
#include "EClassifier.hpp"
#include "impl/EcorePackageImpl.hpp"
#include "EStructuralFeature.hpp"
#include "EReference.hpp"
#include "EStringToStringMapEntry.hpp"
#include "impl/EcoreFactoryImpl.hpp"
#include <string>
#include <iostream>
#include <chrono>
using namespace ecore;
int main()
{
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
start = std::chrono::high_resolution_clock::now();
std::shared_ptr<EcorePackage> package=EcorePackage::eInstance();
std::shared_ptr<EcoreFactory> factory = EcoreFactory::eInstance();
end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() << std::endl;
for (int var2 = 0; var2 < 10; ++var2) {
system("PAUSE");
std::shared_ptr<EPackage> p = std::dynamic_pointer_cast<EPackage>(
factory->create("EPackage", std::shared_ptr<EPackage>()));
/* std::shared_ptr<EObject> c2 = factory->create("EClass", p);
if (c2 != nullptr) {
std::shared_ptr<EClass> c3 = std::dynamic_pointer_cast<EClass>(c2);
if (c3 != nullptr) {
std::cout << c3->eClass()->getName() << " for c3 created by typed class name" << std::endl;
}
}
// creation class instances using class name (manual given (usable for serialization or by using meta class)
std::shared_ptr<EClass> c_metaclass = c2->eClass();
std::cout << "class name " << c_metaclass->getName() << std::endl;
std::shared_ptr<EObject> c4 = factory->create(c_metaclass->getName(), p);
if (c4 != nullptr) {
std::shared_ptr<EClass> c5 = std::dynamic_pointer_cast<EClass>(c4);
if (c5 != nullptr) {
std::cout << c5->eClass()->getName() << " for c5 created by name given by meta class of EClass"
<< std::endl;
}
}
// Benchmark section
std::shared_ptr<ecore::EClass> c = std::shared_ptr<ecore::EClass>(factory->createEClass(p));
c->setName("Test");
*/
//invoke anony getter
start = std::chrono::high_resolution_clock::now();
for (int var = 0; var < 1000000; ++var) {
std::shared_ptr<ecore::EClass> c = std::shared_ptr<ecore::EClass>(factory->createEClass(p));
//std::string b = boost::any_cast<std::string>(c->eGet(package->getENamedElement_Name()));
// c->setName("Name"); //b
//p->getEClassifiers()->push_back(std::shared_ptr<ecore::EClass>(c));
}
end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << std::endl;
std::cout<< "-------------------------------------------------------------------\n";
}
//qDebug()<<b;
return 0;
}
<commit_msg>update memoryBenchmarkEcore - use container implementation<commit_after>
#include "EClass.hpp"
#include "EAnnotation.hpp"
#include "EcoreFactory.hpp"
#include "EcorePackage.hpp"
#include "EClassifier.hpp"
#include "impl/EcorePackageImpl.hpp"
#include "EStructuralFeature.hpp"
#include "EReference.hpp"
#include "EStringToStringMapEntry.hpp"
#include "impl/EcoreFactoryImpl.hpp"
#include <string>
#include <iostream>
#include <chrono>
using namespace ecore;
int main()
{
omp_set_num_threads(1);
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
start = std::chrono::high_resolution_clock::now();
std::shared_ptr<EcorePackage> package=EcorePackage::eInstance();
std::shared_ptr<EcoreFactory> factory = EcoreFactory::eInstance();
end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() << std::endl;
for (int var2 = 0; var2 < 10; ++var2) {
system("PAUSE");
std::shared_ptr<EPackage> p = std::dynamic_pointer_cast<EPackage>(
factory->create("EPackage", package));
/* std::shared_ptr<EObject> c2 = factory->create("EClass", p);
if (c2 != nullptr) {
std::shared_ptr<EClass> c3 = std::dynamic_pointer_cast<EClass>(c2);
if (c3 != nullptr) {
std::cout << c3->eClass()->getName() << " for c3 created by typed class name" << std::endl;
}
}
// creation class instances using class name (manual given (usable for serialization or by using meta class)
std::shared_ptr<EClass> c_metaclass = c2->eClass();
std::cout << "class name " << c_metaclass->getName() << std::endl;
std::shared_ptr<EObject> c4 = factory->create(c_metaclass->getName(), p);
if (c4 != nullptr) {
std::shared_ptr<EClass> c5 = std::dynamic_pointer_cast<EClass>(c4);
if (c5 != nullptr) {
std::cout << c5->eClass()->getName() << " for c5 created by name given by meta class of EClass"
<< std::endl;
}
}
// Benchmark section
std::shared_ptr<ecore::EClass> c = std::shared_ptr<ecore::EClass>(factory->createEClass(p));
c->setName("Test");
*/
//invoke anony getter
start = std::chrono::high_resolution_clock::now();
for (int var = 0; var < 1000000; ++var) {
std::shared_ptr<ecore::EClass> c = factory->createEClass_in_EPackage(p);
//std::string b = boost::any_cast<std::string>(c->eGet(package->getENamedElement_Name()));
// c->setName("Name"); //b
//p->getEClassifiers()->push_back(std::shared_ptr<ecore::EClass>(c));
}
end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << std::endl;
std::cout<< "-------------------------------------------------------------------\n";
}
//qDebug()<<b;
return 0;
}
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2020-2021 Project CHIP Authors
*
* 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.
*/
/**
* @file
* This file implements the ExchangeManager class.
*
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <cstring>
#include <inttypes.h>
#include <stddef.h>
#include <core/CHIPCore.h>
#include <core/CHIPEncoding.h>
#include <messaging/ExchangeContext.h>
#include <messaging/ExchangeMgr.h>
#include <protocols/Protocols.h>
#include <support/CHIPFaultInjection.h>
#include <support/CodeUtils.h>
#include <support/RandUtils.h>
#include <support/logging/CHIPLogging.h>
using namespace chip::Encoding;
using namespace chip::Inet;
using namespace chip::System;
namespace chip {
namespace Messaging {
/**
* Constructor for the ExchangeManager class.
* It sets the state to kState_NotInitialized.
*
* @note
* The class must be initialized via ExchangeManager::Init()
* prior to use.
*
*/
ExchangeManager::ExchangeManager() : mReliableMessageMgr(mContextPool)
{
mState = State::kState_NotInitialized;
}
CHIP_ERROR ExchangeManager::Init(NodeId localNodeId, TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrReturnError(mState == State::kState_NotInitialized, err = CHIP_ERROR_INCORRECT_STATE);
mLocalNodeId = localNodeId;
mTransportMgr = transportMgr;
mSessionMgr = sessionMgr;
mNextExchangeId = GetRandU16();
mNextKeyId = 0;
mContextsInUse = 0;
memset(UMHandlerPool, 0, sizeof(UMHandlerPool));
mTransportMgr->SetRendezvousSession(this);
sessionMgr->SetDelegate(this);
mReliableMessageMgr.Init(sessionMgr->SystemLayer(), sessionMgr);
err = mMessageCounterSyncMgr.Init(this);
ReturnErrorOnFailure(err);
mState = State::kState_Initialized;
return err;
}
CHIP_ERROR ExchangeManager::Shutdown()
{
mMessageCounterSyncMgr.Shutdown();
mReliableMessageMgr.Shutdown();
if (mSessionMgr != nullptr)
{
mSessionMgr->SetDelegate(nullptr);
mSessionMgr = nullptr;
}
mState = State::kState_NotInitialized;
return CHIP_NO_ERROR;
}
ExchangeContext * ExchangeManager::NewContext(SecureSessionHandle session, ExchangeDelegate * delegate)
{
return AllocContext(mNextExchangeId++, session, true, delegate);
}
CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegate * delegate)
{
return RegisterUMH(protocolId, kAnyMessageType, delegate);
}
CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType,
ExchangeDelegate * delegate)
{
return RegisterUMH(protocolId, static_cast<int16_t>(msgType), delegate);
}
CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId)
{
return UnregisterUMH(protocolId, kAnyMessageType);
}
CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType)
{
return UnregisterUMH(protocolId, static_cast<int16_t>(msgType));
}
void ExchangeManager::OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * msgLayer)
{
ChipLogError(ExchangeManager, "Accept FAILED, err = %s", ErrorStr(error));
}
ExchangeContext * ExchangeManager::AllocContext(uint16_t ExchangeId, SecureSessionHandle session, bool Initiator,
ExchangeDelegate * delegate)
{
CHIP_FAULT_INJECT(FaultInjection::kFault_AllocExchangeContext, return nullptr);
for (auto & ec : mContextPool)
{
if (ec.GetReferenceCount() == 0)
{
return ec.Alloc(this, ExchangeId, session, Initiator, delegate);
}
}
ChipLogError(ExchangeManager, "Alloc ctxt FAILED");
return nullptr;
}
CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate)
{
UnsolicitedMessageHandler * umh = UMHandlerPool;
UnsolicitedMessageHandler * selected = nullptr;
for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
{
if (umh->Delegate == nullptr)
{
if (selected == nullptr)
selected = umh;
}
else if (umh->ProtocolId == protocolId && umh->MessageType == msgType)
{
umh->Delegate = delegate;
return CHIP_NO_ERROR;
}
}
if (selected == nullptr)
return CHIP_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS;
selected->Delegate = delegate;
selected->ProtocolId = protocolId;
selected->MessageType = msgType;
SYSTEM_STATS_INCREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers);
return CHIP_NO_ERROR;
}
CHIP_ERROR ExchangeManager::UnregisterUMH(Protocols::Id protocolId, int16_t msgType)
{
UnsolicitedMessageHandler * umh = UMHandlerPool;
for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
{
if (umh->Delegate != nullptr && umh->ProtocolId == protocolId && umh->MessageType == msgType)
{
umh->Delegate = nullptr;
SYSTEM_STATS_DECREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers);
return CHIP_NO_ERROR;
}
}
return CHIP_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER;
}
bool ExchangeManager::IsMsgCounterSyncMessage(const PayloadHeader & payloadHeader)
{
if (payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncReq) ||
payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncRsp))
{
return true;
}
return false;
}
void ExchangeManager::HandleGroupMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader,
const SecureSessionHandle & session, System::PacketBufferHandle msgBuf)
{
OnMessageReceived(packetHeader, payloadHeader, session, std::move(msgBuf), nullptr);
}
void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader,
SecureSessionHandle session, System::PacketBufferHandle msgBuf, SecureSessionMgr * msgLayer)
{
CHIP_ERROR err = CHIP_NO_ERROR;
UnsolicitedMessageHandler * umh = nullptr;
UnsolicitedMessageHandler * matchingUMH = nullptr;
bool sendAckAndCloseExchange = false;
if (!IsMsgCounterSyncMessage(payloadHeader) && session.IsPeerGroupMsgIdNotSynchronized())
{
Transport::PeerConnectionState * state = mSessionMgr->GetPeerConnectionState(session);
VerifyOrReturn(state != nullptr);
// Queue the message as needed for sync with destination node.
err = mMessageCounterSyncMgr.AddToReceiveTable(packetHeader, payloadHeader, session, std::move(msgBuf));
VerifyOrReturn(err == CHIP_NO_ERROR);
// Initiate message counter synchronization if no message counter synchronization is in progress.
if (!state->IsMsgCounterSyncInProgress())
{
err = mMessageCounterSyncMgr.SendMsgCounterSyncReq(session);
}
if (err != CHIP_NO_ERROR)
{
ChipLogError(ExchangeManager,
"Message counter synchronization for received message, failed to send synchronization request, err = %d",
err);
}
// After the message that triggers message counter synchronization is stored, and a message counter
// synchronization exchange is initiated, we need to return immediately and re-process the original message
// when the synchronization is completed.
return;
}
// Search for an existing exchange that the message applies to. If a match is found...
for (auto & ec : mContextPool)
{
if (ec.GetReferenceCount() > 0 && ec.MatchExchange(session, packetHeader, payloadHeader))
{
// Found a matching exchange. Set flag for correct subsequent CRMP
// retransmission timeout selection.
if (!ec.mReliableMessageContext.HasRcvdMsgFromPeer())
{
ec.mReliableMessageContext.SetMsgRcvdFromPeer(true);
}
// Matched ExchangeContext; send to message handler.
ec.HandleMessage(packetHeader, payloadHeader, std::move(msgBuf));
ExitNow(err = CHIP_NO_ERROR);
}
}
// Search for an unsolicited message handler if it marked as being sent by an initiator. Since we didn't
// find an existing exchange that matches the message, it must be an unsolicited message. However all
// unsolicited messages must be marked as being from an initiator.
if (payloadHeader.IsInitiator())
{
// Search for an unsolicited message handler that can handle the message. Prefer handlers that can explicitly
// handle the message type over handlers that handle all messages for a profile.
umh = (UnsolicitedMessageHandler *) UMHandlerPool;
matchingUMH = nullptr;
for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
{
if (umh->Delegate != nullptr && payloadHeader.HasProtocol(umh->ProtocolId))
{
if (umh->MessageType == payloadHeader.GetMessageType())
{
matchingUMH = umh;
break;
}
if (umh->MessageType == kAnyMessageType)
matchingUMH = umh;
}
}
}
// Discard the message if it isn't marked as being sent by an initiator and the message does not need to send
// an ack to the peer.
else if (!payloadHeader.NeedsAck())
{
ExitNow(err = CHIP_ERROR_UNSOLICITED_MSG_NO_ORIGINATOR);
}
// If we didn't find an existing exchange that matches the message, and no unsolicited message handler registered
// to hand this message, we need to create a temporary exchange to send an ack for this message and then close this exchange.
sendAckAndCloseExchange = payloadHeader.NeedsAck() && (matchingUMH == nullptr);
// If we found a handler or we need to create a new exchange context (EC).
if (matchingUMH != nullptr || sendAckAndCloseExchange)
{
ExchangeContext * ec = nullptr;
if (sendAckAndCloseExchange)
{
// If rcvd msg is from initiator then this exchange is created as not Initiator.
// If rcvd msg is not from initiator then this exchange is created as Initiator.
ec = AllocContext(payloadHeader.GetExchangeID(), session, !payloadHeader.IsInitiator(), nullptr);
}
else
{
ec = AllocContext(payloadHeader.GetExchangeID(), session, false, matchingUMH->Delegate);
}
VerifyOrExit(ec != nullptr, err = CHIP_ERROR_NO_MEMORY);
ChipLogProgress(ExchangeManager, "ec pos: %d, id: %d, Delegate: 0x%x", ec - mContextPool.begin(), ec->GetExchangeId(),
ec->GetDelegate());
ec->HandleMessage(packetHeader, payloadHeader, std::move(msgBuf));
// Close exchange if it was created only to send ack for a duplicate message.
if (sendAckAndCloseExchange)
ec->Close();
}
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %d", err);
}
}
ChannelHandle ExchangeManager::EstablishChannel(const ChannelBuilder & builder, ChannelDelegate * delegate)
{
ChannelContext * channelContext = nullptr;
// Find an existing Channel matching the builder
mChannelContexts.ForEachActiveObject([&](ChannelContext * context) {
if (context->MatchesBuilder(builder))
{
channelContext = context;
return false;
}
return true;
});
if (channelContext == nullptr)
{
// create a new channel if not found
channelContext = mChannelContexts.CreateObject(this);
if (channelContext == nullptr)
return ChannelHandle{ nullptr };
channelContext->Start(builder);
}
else
{
channelContext->Retain();
}
ChannelContextHandleAssociation * association = mChannelHandles.CreateObject(channelContext, delegate);
channelContext->Release();
return ChannelHandle{ association };
}
void ExchangeManager::OnNewConnection(SecureSessionHandle session, SecureSessionMgr * mgr)
{
mChannelContexts.ForEachActiveObject([&](ChannelContext * context) {
if (context->MatchesSession(session, mgr))
{
context->OnNewConnection(session);
return false;
}
return true;
});
}
void ExchangeManager::OnConnectionExpired(SecureSessionHandle session, SecureSessionMgr * mgr)
{
for (auto & ec : mContextPool)
{
if (ec.GetReferenceCount() > 0 && ec.mSecureSession == session)
{
ec.Close();
// Continue iterate because there can be multiple contexts associated with the connection.
}
}
mChannelContexts.ForEachActiveObject([&](ChannelContext * context) {
if (context->MatchesSession(session, mgr))
{
context->OnConnectionExpired(session);
return false;
}
return true;
});
}
void ExchangeManager::OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source,
System::PacketBufferHandle msgBuf)
{
auto peer = header.GetSourceNodeId();
if (!peer.HasValue())
{
char addrBuffer[Transport::PeerAddress::kMaxToStringSize];
source.ToString(addrBuffer, sizeof(addrBuffer));
ChipLogError(ExchangeManager, "Unencrypted message from %s is dropped since no source node id in packet header.",
addrBuffer);
return;
}
auto node = peer.Value();
auto notFound = mChannelContexts.ForEachActiveObject([&](ChannelContext * context) {
if (context->IsCasePairing() && context->MatchNodeId(node))
{
CHIP_ERROR err = context->HandlePairingMessage(header, source, std::move(msgBuf));
if (err != CHIP_NO_ERROR)
ChipLogError(ExchangeManager, "HandlePairingMessage error %s from node %llu.", chip::ErrorStr(err), node);
return false;
}
return true;
});
if (notFound)
{
char addrBuffer[Transport::PeerAddress::kMaxToStringSize];
source.ToString(addrBuffer, sizeof(addrBuffer));
ChipLogError(ExchangeManager, "Unencrypted message from %s is dropped since no session found for node %llu.", addrBuffer,
node);
return;
}
}
void ExchangeManager::IncrementContextsInUse()
{
mContextsInUse++;
}
void ExchangeManager::DecrementContextsInUse()
{
if (mContextsInUse >= 1)
{
mContextsInUse--;
}
else
{
ChipLogError(ExchangeManager, "No context in use, decrement failed");
}
}
} // namespace Messaging
} // namespace chip
<commit_msg>Fix build on gcc >= 10 (#5566)<commit_after>/*
*
* Copyright (c) 2020-2021 Project CHIP Authors
*
* 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.
*/
/**
* @file
* This file implements the ExchangeManager class.
*
*/
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include <cstring>
#include <inttypes.h>
#include <stddef.h>
#include <core/CHIPCore.h>
#include <core/CHIPEncoding.h>
#include <messaging/ExchangeContext.h>
#include <messaging/ExchangeMgr.h>
#include <protocols/Protocols.h>
#include <support/CHIPFaultInjection.h>
#include <support/CodeUtils.h>
#include <support/RandUtils.h>
#include <support/logging/CHIPLogging.h>
using namespace chip::Encoding;
using namespace chip::Inet;
using namespace chip::System;
namespace chip {
namespace Messaging {
/**
* Constructor for the ExchangeManager class.
* It sets the state to kState_NotInitialized.
*
* @note
* The class must be initialized via ExchangeManager::Init()
* prior to use.
*
*/
ExchangeManager::ExchangeManager() : mReliableMessageMgr(mContextPool)
{
mState = State::kState_NotInitialized;
}
CHIP_ERROR ExchangeManager::Init(NodeId localNodeId, TransportMgrBase * transportMgr, SecureSessionMgr * sessionMgr)
{
CHIP_ERROR err = CHIP_NO_ERROR;
VerifyOrReturnError(mState == State::kState_NotInitialized, err = CHIP_ERROR_INCORRECT_STATE);
mLocalNodeId = localNodeId;
mTransportMgr = transportMgr;
mSessionMgr = sessionMgr;
mNextExchangeId = GetRandU16();
mNextKeyId = 0;
mContextsInUse = 0;
for (auto & handler : UMHandlerPool)
{
handler = {};
}
mTransportMgr->SetRendezvousSession(this);
sessionMgr->SetDelegate(this);
mReliableMessageMgr.Init(sessionMgr->SystemLayer(), sessionMgr);
err = mMessageCounterSyncMgr.Init(this);
ReturnErrorOnFailure(err);
mState = State::kState_Initialized;
return err;
}
CHIP_ERROR ExchangeManager::Shutdown()
{
mMessageCounterSyncMgr.Shutdown();
mReliableMessageMgr.Shutdown();
if (mSessionMgr != nullptr)
{
mSessionMgr->SetDelegate(nullptr);
mSessionMgr = nullptr;
}
mState = State::kState_NotInitialized;
return CHIP_NO_ERROR;
}
ExchangeContext * ExchangeManager::NewContext(SecureSessionHandle session, ExchangeDelegate * delegate)
{
return AllocContext(mNextExchangeId++, session, true, delegate);
}
CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId, ExchangeDelegate * delegate)
{
return RegisterUMH(protocolId, kAnyMessageType, delegate);
}
CHIP_ERROR ExchangeManager::RegisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType,
ExchangeDelegate * delegate)
{
return RegisterUMH(protocolId, static_cast<int16_t>(msgType), delegate);
}
CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForProtocol(Protocols::Id protocolId)
{
return UnregisterUMH(protocolId, kAnyMessageType);
}
CHIP_ERROR ExchangeManager::UnregisterUnsolicitedMessageHandlerForType(Protocols::Id protocolId, uint8_t msgType)
{
return UnregisterUMH(protocolId, static_cast<int16_t>(msgType));
}
void ExchangeManager::OnReceiveError(CHIP_ERROR error, const Transport::PeerAddress & source, SecureSessionMgr * msgLayer)
{
ChipLogError(ExchangeManager, "Accept FAILED, err = %s", ErrorStr(error));
}
ExchangeContext * ExchangeManager::AllocContext(uint16_t ExchangeId, SecureSessionHandle session, bool Initiator,
ExchangeDelegate * delegate)
{
CHIP_FAULT_INJECT(FaultInjection::kFault_AllocExchangeContext, return nullptr);
for (auto & ec : mContextPool)
{
if (ec.GetReferenceCount() == 0)
{
return ec.Alloc(this, ExchangeId, session, Initiator, delegate);
}
}
ChipLogError(ExchangeManager, "Alloc ctxt FAILED");
return nullptr;
}
CHIP_ERROR ExchangeManager::RegisterUMH(Protocols::Id protocolId, int16_t msgType, ExchangeDelegate * delegate)
{
UnsolicitedMessageHandler * umh = UMHandlerPool;
UnsolicitedMessageHandler * selected = nullptr;
for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
{
if (umh->Delegate == nullptr)
{
if (selected == nullptr)
selected = umh;
}
else if (umh->ProtocolId == protocolId && umh->MessageType == msgType)
{
umh->Delegate = delegate;
return CHIP_NO_ERROR;
}
}
if (selected == nullptr)
return CHIP_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS;
selected->Delegate = delegate;
selected->ProtocolId = protocolId;
selected->MessageType = msgType;
SYSTEM_STATS_INCREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers);
return CHIP_NO_ERROR;
}
CHIP_ERROR ExchangeManager::UnregisterUMH(Protocols::Id protocolId, int16_t msgType)
{
UnsolicitedMessageHandler * umh = UMHandlerPool;
for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
{
if (umh->Delegate != nullptr && umh->ProtocolId == protocolId && umh->MessageType == msgType)
{
umh->Delegate = nullptr;
SYSTEM_STATS_DECREMENT(chip::System::Stats::kExchangeMgr_NumUMHandlers);
return CHIP_NO_ERROR;
}
}
return CHIP_ERROR_NO_UNSOLICITED_MESSAGE_HANDLER;
}
bool ExchangeManager::IsMsgCounterSyncMessage(const PayloadHeader & payloadHeader)
{
if (payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncReq) ||
payloadHeader.HasMessageType(Protocols::SecureChannel::MsgType::MsgCounterSyncRsp))
{
return true;
}
return false;
}
void ExchangeManager::HandleGroupMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader,
const SecureSessionHandle & session, System::PacketBufferHandle msgBuf)
{
OnMessageReceived(packetHeader, payloadHeader, session, std::move(msgBuf), nullptr);
}
void ExchangeManager::OnMessageReceived(const PacketHeader & packetHeader, const PayloadHeader & payloadHeader,
SecureSessionHandle session, System::PacketBufferHandle msgBuf, SecureSessionMgr * msgLayer)
{
CHIP_ERROR err = CHIP_NO_ERROR;
UnsolicitedMessageHandler * umh = nullptr;
UnsolicitedMessageHandler * matchingUMH = nullptr;
bool sendAckAndCloseExchange = false;
if (!IsMsgCounterSyncMessage(payloadHeader) && session.IsPeerGroupMsgIdNotSynchronized())
{
Transport::PeerConnectionState * state = mSessionMgr->GetPeerConnectionState(session);
VerifyOrReturn(state != nullptr);
// Queue the message as needed for sync with destination node.
err = mMessageCounterSyncMgr.AddToReceiveTable(packetHeader, payloadHeader, session, std::move(msgBuf));
VerifyOrReturn(err == CHIP_NO_ERROR);
// Initiate message counter synchronization if no message counter synchronization is in progress.
if (!state->IsMsgCounterSyncInProgress())
{
err = mMessageCounterSyncMgr.SendMsgCounterSyncReq(session);
}
if (err != CHIP_NO_ERROR)
{
ChipLogError(ExchangeManager,
"Message counter synchronization for received message, failed to send synchronization request, err = %d",
err);
}
// After the message that triggers message counter synchronization is stored, and a message counter
// synchronization exchange is initiated, we need to return immediately and re-process the original message
// when the synchronization is completed.
return;
}
// Search for an existing exchange that the message applies to. If a match is found...
for (auto & ec : mContextPool)
{
if (ec.GetReferenceCount() > 0 && ec.MatchExchange(session, packetHeader, payloadHeader))
{
// Found a matching exchange. Set flag for correct subsequent CRMP
// retransmission timeout selection.
if (!ec.mReliableMessageContext.HasRcvdMsgFromPeer())
{
ec.mReliableMessageContext.SetMsgRcvdFromPeer(true);
}
// Matched ExchangeContext; send to message handler.
ec.HandleMessage(packetHeader, payloadHeader, std::move(msgBuf));
ExitNow(err = CHIP_NO_ERROR);
}
}
// Search for an unsolicited message handler if it marked as being sent by an initiator. Since we didn't
// find an existing exchange that matches the message, it must be an unsolicited message. However all
// unsolicited messages must be marked as being from an initiator.
if (payloadHeader.IsInitiator())
{
// Search for an unsolicited message handler that can handle the message. Prefer handlers that can explicitly
// handle the message type over handlers that handle all messages for a profile.
umh = (UnsolicitedMessageHandler *) UMHandlerPool;
matchingUMH = nullptr;
for (int i = 0; i < CHIP_CONFIG_MAX_UNSOLICITED_MESSAGE_HANDLERS; i++, umh++)
{
if (umh->Delegate != nullptr && payloadHeader.HasProtocol(umh->ProtocolId))
{
if (umh->MessageType == payloadHeader.GetMessageType())
{
matchingUMH = umh;
break;
}
if (umh->MessageType == kAnyMessageType)
matchingUMH = umh;
}
}
}
// Discard the message if it isn't marked as being sent by an initiator and the message does not need to send
// an ack to the peer.
else if (!payloadHeader.NeedsAck())
{
ExitNow(err = CHIP_ERROR_UNSOLICITED_MSG_NO_ORIGINATOR);
}
// If we didn't find an existing exchange that matches the message, and no unsolicited message handler registered
// to hand this message, we need to create a temporary exchange to send an ack for this message and then close this exchange.
sendAckAndCloseExchange = payloadHeader.NeedsAck() && (matchingUMH == nullptr);
// If we found a handler or we need to create a new exchange context (EC).
if (matchingUMH != nullptr || sendAckAndCloseExchange)
{
ExchangeContext * ec = nullptr;
if (sendAckAndCloseExchange)
{
// If rcvd msg is from initiator then this exchange is created as not Initiator.
// If rcvd msg is not from initiator then this exchange is created as Initiator.
ec = AllocContext(payloadHeader.GetExchangeID(), session, !payloadHeader.IsInitiator(), nullptr);
}
else
{
ec = AllocContext(payloadHeader.GetExchangeID(), session, false, matchingUMH->Delegate);
}
VerifyOrExit(ec != nullptr, err = CHIP_ERROR_NO_MEMORY);
ChipLogProgress(ExchangeManager, "ec pos: %d, id: %d, Delegate: 0x%x", ec - mContextPool.begin(), ec->GetExchangeId(),
ec->GetDelegate());
ec->HandleMessage(packetHeader, payloadHeader, std::move(msgBuf));
// Close exchange if it was created only to send ack for a duplicate message.
if (sendAckAndCloseExchange)
ec->Close();
}
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(ExchangeManager, "OnMessageReceived failed, err = %d", err);
}
}
ChannelHandle ExchangeManager::EstablishChannel(const ChannelBuilder & builder, ChannelDelegate * delegate)
{
ChannelContext * channelContext = nullptr;
// Find an existing Channel matching the builder
mChannelContexts.ForEachActiveObject([&](ChannelContext * context) {
if (context->MatchesBuilder(builder))
{
channelContext = context;
return false;
}
return true;
});
if (channelContext == nullptr)
{
// create a new channel if not found
channelContext = mChannelContexts.CreateObject(this);
if (channelContext == nullptr)
return ChannelHandle{ nullptr };
channelContext->Start(builder);
}
else
{
channelContext->Retain();
}
ChannelContextHandleAssociation * association = mChannelHandles.CreateObject(channelContext, delegate);
channelContext->Release();
return ChannelHandle{ association };
}
void ExchangeManager::OnNewConnection(SecureSessionHandle session, SecureSessionMgr * mgr)
{
mChannelContexts.ForEachActiveObject([&](ChannelContext * context) {
if (context->MatchesSession(session, mgr))
{
context->OnNewConnection(session);
return false;
}
return true;
});
}
void ExchangeManager::OnConnectionExpired(SecureSessionHandle session, SecureSessionMgr * mgr)
{
for (auto & ec : mContextPool)
{
if (ec.GetReferenceCount() > 0 && ec.mSecureSession == session)
{
ec.Close();
// Continue iterate because there can be multiple contexts associated with the connection.
}
}
mChannelContexts.ForEachActiveObject([&](ChannelContext * context) {
if (context->MatchesSession(session, mgr))
{
context->OnConnectionExpired(session);
return false;
}
return true;
});
}
void ExchangeManager::OnMessageReceived(const PacketHeader & header, const Transport::PeerAddress & source,
System::PacketBufferHandle msgBuf)
{
auto peer = header.GetSourceNodeId();
if (!peer.HasValue())
{
char addrBuffer[Transport::PeerAddress::kMaxToStringSize];
source.ToString(addrBuffer, sizeof(addrBuffer));
ChipLogError(ExchangeManager, "Unencrypted message from %s is dropped since no source node id in packet header.",
addrBuffer);
return;
}
auto node = peer.Value();
auto notFound = mChannelContexts.ForEachActiveObject([&](ChannelContext * context) {
if (context->IsCasePairing() && context->MatchNodeId(node))
{
CHIP_ERROR err = context->HandlePairingMessage(header, source, std::move(msgBuf));
if (err != CHIP_NO_ERROR)
ChipLogError(ExchangeManager, "HandlePairingMessage error %s from node %llu.", chip::ErrorStr(err), node);
return false;
}
return true;
});
if (notFound)
{
char addrBuffer[Transport::PeerAddress::kMaxToStringSize];
source.ToString(addrBuffer, sizeof(addrBuffer));
ChipLogError(ExchangeManager, "Unencrypted message from %s is dropped since no session found for node %llu.", addrBuffer,
node);
return;
}
}
void ExchangeManager::IncrementContextsInUse()
{
mContextsInUse++;
}
void ExchangeManager::DecrementContextsInUse()
{
if (mContextsInUse >= 1)
{
mContextsInUse--;
}
else
{
ChipLogError(ExchangeManager, "No context in use, decrement failed");
}
}
} // namespace Messaging
} // namespace chip
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS 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.
****************************************************************************/
/**
* @file
* @brief IronBee --- CLIPP View Consumer Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include "ironbee_config_auto.h"
#include "view.hpp"
#include <boost/foreach.hpp>
#include <boost/function.hpp>
#include <boost/format.hpp>
#ifdef HAVE_MODP
#include <modp_burl.h>
#endif
using namespace std;
namespace IronBee {
namespace CLIPP {
struct ViewConsumer::State
{
boost::function<void(const Input::input_p&)> viewer;
};
namespace {
bool is_not_printable(char c)
{
return (c < 32 || c > 126) && (c != 10) && (c != 13);
}
void output_with_escapes(const char* b, const char* e)
{
const char* i = b;
while (i < e) {
const char* j = find_if(i, e, &is_not_printable);
if (j == e) {
cout.write(i, e - i);
i = e;
}
else {
if (j > i) {
cout.write(i, j - i);
i = j;
}
// Workaround for boost::format bug.
int value = *i;
cout << (boost::format("[%02x]") % (value & 0xff));
++i;
}
}
}
using namespace Input;
struct ViewDelegate :
public Delegate
{
//! Output ConnectionEvent.
static
void connection_event(const ConnectionEvent& event)
{
cout << event.local_ip << ":" << event.local_port
<< " <--> "
<< event.remote_ip << ":" << event.remote_port
;
}
//! Output DataEvent.
static
void data_event(const DataEvent& event)
{
output_with_escapes(
event.data.data,
event.data.data + event.data.length
);
}
//! Output HeaderEven& eventt
static
void header_event(const HeaderEvent& event)
{
BOOST_FOREACH(const header_t& header, event.headers) {
cout << header.first << ": " << header.second << endl;
}
}
//! CONNECTION_OPENED
void connection_opened(const ConnectionEvent& event)
{
cout << "=== CONNECTION_OPENED: ";
connection_event(event);
cout << " ===" << endl;
}
//! CONNECTION_CLOSED
void connection_closed(const NullEvent& event)
{
cout << "=== CONNECTION_CLOSED ===" << endl;
}
//! CONNECTION_DATA_IN
void connection_data_in(const DataEvent& event)
{
cout << "=== CONNECTION_DATA_IN ===" << endl;
data_event(event);
cout << endl;
}
//! CONNECTION_DATA_OUT
void connection_data_out(const DataEvent& event)
{
cout << "=== CONNECTION_DATA_OUT ===" << endl;
data_event(event);
cout << endl;
}
//! REQUEST_STARTED
void request_started(const RequestEvent& event)
{
cout << "=== REQUEST_STARTED: "
<< event.method << " " << event.uri << " " << event.protocol
<< " ===" << endl;
if (event.raw.data) {
cout << "RAW: " << event.raw << endl;
}
urldecode("DECODED RAW: ", event.raw.data, event.raw.length);
urldecode("DECODED URI: ", event.uri.data, event.uri.length);
}
//! REQUEST_HEADER
void request_header(const HeaderEvent& event)
{
cout << "=== REQUEST_HEADER ===" << endl;
header_event(event);
}
//! REQUEST HEADER FINISHED
void request_header_finished(const NullEvent& event)
{
cout << "=== REQUEST_HEADER_FINISHED ===" << endl;
}
//! REQUEST_BODY
void request_body(const DataEvent& event)
{
cout << "=== REQUEST_BODY ===" << endl;
data_event(event);
cout << endl;
}
//! REQUEST_FINISHED
void request_finished(const NullEvent& event)
{
cout << "=== REQUEST_FINISHED ===" << endl;
}
//! RESPONSE_STARTED
void response_started(const ResponseEvent& event)
{
cout << "=== RESPONSE_STARTED "
<< event.protocol << " " << event.status << " " << event.message
<< " ===" << endl;
if (event.raw.data) {
cout << event.raw << endl;
}
}
//! RESPONSE_HEADER
void response_header(const HeaderEvent& event)
{
cout << "=== RESPONSE HEADER ===" << endl;
header_event(event);
}
//! RESPONSE HEADER FINISHED
void response_header_finished(const NullEvent& event)
{
cout << "=== RESPONSE_HEADER_FINISHED ===" << endl;
}
//! RESPONSE_BODY
void response_body(const DataEvent& event)
{
cout << "=== RESPONSE_BODY ===" << endl;
data_event(event);
cout << endl;
}
//! RESPONSE_FINISHED
void response_finished(const NullEvent& event)
{
cout << "=== RESPONSE_FINISHED ===" << endl;
}
private:
void urldecode(const char* prefix, const char* data, size_t length)
{
#ifdef HAVE_MODP
if (! data) {
return;
}
string decoded = modp::url_decode(data, length);
if (
decoded.length() != length ||
! equal(decoded.begin(), decoded.end(), data)
) {
cout << prefix << decoded << endl;
}
#endif
}
};
void view_full(const input_p& input)
{
if (input->id.empty()) {
cout << "---- No ID Provided ----" << endl;
}
else {
cout << "---- " << input->id << " ----" << endl;
}
ViewDelegate viewer;
input->connection.dispatch(viewer);
}
void view_id(const input_p& input)
{
if (input->id.empty()) {
cout << "---- No ID Provided ----" << endl;
}
else {
cout << "---- " << input->id << " ----" << endl;
}
}
void view_summary(const input_p& input)
{
string id("NO ID");
if (! input->id.empty()) {
id = input->id;
}
size_t num_txs = input->connection.transactions.size();
if (input->connection.pre_transaction_events.empty()) {
// no IP information.
cout << boost::format("%36s NO CONNECTION INFO %5d") % id % num_txs
<< endl;
}
const ConnectionEvent& connection_event =
dynamic_cast<ConnectionEvent&>(
*input->connection.pre_transaction_events.front()
);
cout << boost::format("%-40s %22s <-> %-22s %5d txs") % id %
(boost::format("%s:%d") %
connection_event.local_ip % connection_event.local_port
) %
(boost::format("%s:%d") %
connection_event.remote_ip % connection_event.remote_port
) %
num_txs
<< endl;
}
}
ViewConsumer::ViewConsumer(const std::string& arg) :
m_state(new State())
{
if (arg == "id") {
m_state->viewer = view_id;
}
else if (arg == "summary") {
m_state->viewer = view_summary;
}
else if (arg.empty()) {
m_state->viewer = view_full;
}
else {
throw runtime_error("Unknown View argument: " + arg);
}
}
bool ViewConsumer::operator()(const input_p& input)
{
if ( ! input ) {
return true;
}
m_state->viewer(input);
return true;
}
ViewModifier::ViewModifier(const std::string& arg) :
m_consumer(arg)
{
// nop
}
bool ViewModifier::operator()(input_p& input)
{
return m_consumer(input);
}
} // CLIPP
} // IronBee
<commit_msg>clipp: Clarify ip/port display for @view.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS 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.
****************************************************************************/
/**
* @file
* @brief IronBee --- CLIPP View Consumer Implementation
*
* @author Christopher Alfeld <calfeld@qualys.com>
*/
#include "ironbee_config_auto.h"
#include "view.hpp"
#include <boost/foreach.hpp>
#include <boost/function.hpp>
#include <boost/format.hpp>
#ifdef HAVE_MODP
#include <modp_burl.h>
#endif
using namespace std;
namespace IronBee {
namespace CLIPP {
struct ViewConsumer::State
{
boost::function<void(const Input::input_p&)> viewer;
};
namespace {
bool is_not_printable(char c)
{
return (c < 32 || c > 126) && (c != 10) && (c != 13);
}
void output_with_escapes(const char* b, const char* e)
{
const char* i = b;
while (i < e) {
const char* j = find_if(i, e, &is_not_printable);
if (j == e) {
cout.write(i, e - i);
i = e;
}
else {
if (j > i) {
cout.write(i, j - i);
i = j;
}
// Workaround for boost::format bug.
int value = *i;
cout << (boost::format("[%02x]") % (value & 0xff));
++i;
}
}
}
using namespace Input;
struct ViewDelegate :
public Delegate
{
//! Output ConnectionEvent.
static
void connection_event(const ConnectionEvent& event)
{
cout << "local: " << event.local_ip << ":" << event.local_port
<< " remote: " << event.remote_ip << ":" << event.remote_port
;
}
//! Output DataEvent.
static
void data_event(const DataEvent& event)
{
output_with_escapes(
event.data.data,
event.data.data + event.data.length
);
}
//! Output HeaderEven& eventt
static
void header_event(const HeaderEvent& event)
{
BOOST_FOREACH(const header_t& header, event.headers) {
cout << header.first << ": " << header.second << endl;
}
}
//! CONNECTION_OPENED
void connection_opened(const ConnectionEvent& event)
{
cout << "=== CONNECTION_OPENED: ";
connection_event(event);
cout << " ===" << endl;
}
//! CONNECTION_CLOSED
void connection_closed(const NullEvent& event)
{
cout << "=== CONNECTION_CLOSED ===" << endl;
}
//! CONNECTION_DATA_IN
void connection_data_in(const DataEvent& event)
{
cout << "=== CONNECTION_DATA_IN ===" << endl;
data_event(event);
cout << endl;
}
//! CONNECTION_DATA_OUT
void connection_data_out(const DataEvent& event)
{
cout << "=== CONNECTION_DATA_OUT ===" << endl;
data_event(event);
cout << endl;
}
//! REQUEST_STARTED
void request_started(const RequestEvent& event)
{
cout << "=== REQUEST_STARTED: "
<< event.method << " " << event.uri << " " << event.protocol
<< " ===" << endl;
if (event.raw.data) {
cout << "RAW: " << event.raw << endl;
}
urldecode("DECODED RAW: ", event.raw.data, event.raw.length);
urldecode("DECODED URI: ", event.uri.data, event.uri.length);
}
//! REQUEST_HEADER
void request_header(const HeaderEvent& event)
{
cout << "=== REQUEST_HEADER ===" << endl;
header_event(event);
}
//! REQUEST HEADER FINISHED
void request_header_finished(const NullEvent& event)
{
cout << "=== REQUEST_HEADER_FINISHED ===" << endl;
}
//! REQUEST_BODY
void request_body(const DataEvent& event)
{
cout << "=== REQUEST_BODY ===" << endl;
data_event(event);
cout << endl;
}
//! REQUEST_FINISHED
void request_finished(const NullEvent& event)
{
cout << "=== REQUEST_FINISHED ===" << endl;
}
//! RESPONSE_STARTED
void response_started(const ResponseEvent& event)
{
cout << "=== RESPONSE_STARTED "
<< event.protocol << " " << event.status << " " << event.message
<< " ===" << endl;
if (event.raw.data) {
cout << event.raw << endl;
}
}
//! RESPONSE_HEADER
void response_header(const HeaderEvent& event)
{
cout << "=== RESPONSE HEADER ===" << endl;
header_event(event);
}
//! RESPONSE HEADER FINISHED
void response_header_finished(const NullEvent& event)
{
cout << "=== RESPONSE_HEADER_FINISHED ===" << endl;
}
//! RESPONSE_BODY
void response_body(const DataEvent& event)
{
cout << "=== RESPONSE_BODY ===" << endl;
data_event(event);
cout << endl;
}
//! RESPONSE_FINISHED
void response_finished(const NullEvent& event)
{
cout << "=== RESPONSE_FINISHED ===" << endl;
}
private:
void urldecode(const char* prefix, const char* data, size_t length)
{
#ifdef HAVE_MODP
if (! data) {
return;
}
string decoded = modp::url_decode(data, length);
if (
decoded.length() != length ||
! equal(decoded.begin(), decoded.end(), data)
) {
cout << prefix << decoded << endl;
}
#endif
}
};
void view_full(const input_p& input)
{
if (input->id.empty()) {
cout << "---- No ID Provided ----" << endl;
}
else {
cout << "---- " << input->id << " ----" << endl;
}
ViewDelegate viewer;
input->connection.dispatch(viewer);
}
void view_id(const input_p& input)
{
if (input->id.empty()) {
cout << "---- No ID Provided ----" << endl;
}
else {
cout << "---- " << input->id << " ----" << endl;
}
}
void view_summary(const input_p& input)
{
string id("NO ID");
if (! input->id.empty()) {
id = input->id;
}
size_t num_txs = input->connection.transactions.size();
if (input->connection.pre_transaction_events.empty()) {
// no IP information.
cout << boost::format("%36s NO CONNECTION INFO %5d") % id % num_txs
<< endl;
}
const ConnectionEvent& connection_event =
dynamic_cast<ConnectionEvent&>(
*input->connection.pre_transaction_events.front()
);
cout << boost::format("%-40s %22s <-> %-22s %5d txs") % id %
(boost::format("%s:%d") %
connection_event.local_ip % connection_event.local_port
) %
(boost::format("%s:%d") %
connection_event.remote_ip % connection_event.remote_port
) %
num_txs
<< endl;
}
}
ViewConsumer::ViewConsumer(const std::string& arg) :
m_state(new State())
{
if (arg == "id") {
m_state->viewer = view_id;
}
else if (arg == "summary") {
m_state->viewer = view_summary;
}
else if (arg.empty()) {
m_state->viewer = view_full;
}
else {
throw runtime_error("Unknown View argument: " + arg);
}
}
bool ViewConsumer::operator()(const input_p& input)
{
if ( ! input ) {
return true;
}
m_state->viewer(input);
return true;
}
ViewModifier::ViewModifier(const std::string& arg) :
m_consumer(arg)
{
// nop
}
bool ViewModifier::operator()(input_p& input)
{
return m_consumer(input);
}
} // CLIPP
} // IronBee
<|endoftext|> |
<commit_before>// Silly program just to test the natvis file for Visual Studio
// ------------------------------------------------------------
#include <string>
#include "parallel_hashmap/phmap.h"
template<class Set, class F>
void test_set(F &f)
{
Set s;
typename Set::iterator it;
for (int i=0; i<100; ++i)
s.insert(f(i));
it = s.begin();
++it;
it = s.end();
it = s.begin();
while(it != s.end())
++it;
it = s.begin();
}
int main(int, char **)
{
using namespace std;
auto make_int = [](int i) { return i; };
auto make_string = [](int i) { return std::to_string(i); };
auto make_2int = [](int i) { return std::make_pair(i, i); };
auto make_2string = [](int i) { return std::make_pair(std::to_string(i), std::to_string(i)); };
test_set<phmap::flat_hash_set<int>>(make_int);
test_set<phmap::flat_hash_set<string>>(make_string);
test_set<phmap::node_hash_set<int>>(make_int);
test_set<phmap::node_hash_set<string>>(make_string);
test_set<phmap::flat_hash_map<int, int>>(make_2int);
test_set<phmap::flat_hash_map<string, string>>(make_2string);
test_set<phmap::node_hash_map<int, int>>(make_2int);
test_set<phmap::node_hash_map<string, string>>(make_2string);
test_set<phmap::parallel_flat_hash_set<int>>(make_int);
test_set<phmap::parallel_flat_hash_set<string>>(make_string);
test_set<phmap::parallel_node_hash_set<int>>(make_int);
test_set<phmap::parallel_node_hash_set<string>>(make_string);
test_set<phmap::parallel_flat_hash_map<int, int>>(make_2int);
test_set<phmap::parallel_flat_hash_map<string, string>>(make_2string);
test_set<phmap::parallel_node_hash_map<int, int>>(make_2int);
test_set<phmap::parallel_node_hash_map<string, string>>(make_2string);
}
<commit_msg>Add example with default parameters<commit_after>// Silly program just to test the natvis file for Visual Studio
// ------------------------------------------------------------
#include <string>
#include "parallel_hashmap/phmap.h"
template<class Set, class F>
void test_set(const F &f)
{
Set s;
typename Set::iterator it;
for (int i=0; i<100; ++i)
s.insert(f(i));
it = s.begin();
++it;
it = s.end();
it = s.begin();
while(it != s.end())
++it;
it = s.begin();
}
int main(int, char **)
{
using namespace std;
auto make_int = [](int i) { return i; };
auto make_string = [](int i) { return std::to_string(i); };
auto make_2int = [](int i) { return std::make_pair(i, i); };
auto make_2string = [](int i) { return std::make_pair(std::to_string(i), std::to_string(i)); };
test_set<phmap::flat_hash_set<int>>(make_int);
test_set<phmap::flat_hash_set<string>>(make_string);
test_set<phmap::node_hash_set<int>>(make_int);
test_set<phmap::node_hash_set<string>>(make_string);
test_set<phmap::flat_hash_map<int, int>>(make_2int);
test_set<phmap::flat_hash_map<string, string>>(make_2string);
test_set<phmap::node_hash_map<int, int>>(make_2int);
test_set<phmap::node_hash_map<string, string>>(make_2string);
test_set<phmap::parallel_flat_hash_set<int>>(make_int);
test_set<phmap::parallel_flat_hash_set<string>>(make_string);
test_set<phmap::parallel_node_hash_set<int>>(make_int);
test_set<phmap::parallel_node_hash_set<string>>(make_string);
test_set<phmap::parallel_flat_hash_map<int, int>>(make_2int);
test_set<phmap::parallel_flat_hash_map<string, string>>(make_2string);
test_set<phmap::parallel_node_hash_map<int, int>>(make_2int);
test_set<phmap::parallel_node_hash_map<string, string>>(make_2string);
// example of using default parameters in order to specify the mutex type
using Map = phmap::parallel_flat_hash_map<std::size_t, std::size_t,
phmap::priv::hash_default_hash<size_t>,
phmap::priv::hash_default_eq<size_t>,
std::allocator<std::pair<const size_t, size_t>>,
4,
std::mutex>;
auto make_2size_t = [](size_t i) { return std::make_pair(i, i); };
test_set<Map>(make_2size_t);
}
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_ELEMENT_HPP
#define VIENNAGRID_ELEMENT_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/forwards.h"
#include "viennagrid/detail/element_iterators.hpp"
#include "viennagrid/detail/boundary_ncell_layer.hpp"
#include "viennagrid/meta/typelist.hpp"
#include <vector>
/** @file element.hpp
@brief Provides the main n-cell type
*/
namespace viennagrid
{
////////////// Top Level configuration //////////
/** @brief The main n-cell class. Assembled by recursive inheritance
*
* @tparam ConfigType Configuration class
* @tparam ElementTag A tag denoting the particular topological shape of the n-cell
*/
template <typename ConfigType,
typename ElementTag>
class element_t :
public boundary_ncell_layer < ConfigType, ElementTag, ElementTag::dim - 1>,
public result_of::element_id_handler<ConfigType, ElementTag>::type
{
typedef typename ConfigType::numeric_type ScalarType;
typedef boundary_ncell_layer < ConfigType, ElementTag, ElementTag::dim - 1> Base;
typedef typename result_of::point<ConfigType>::type PointType;
//typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
typedef topology::bndcells<ElementTag, 0> VertexSpecs;
public:
typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
typedef typename viennameta::typelist::result_of::push_back< typename Base::required_types, element_t >::type required_types;
/** @brief Publish the configuration class */
typedef ConfigType config_type;
/** @brief Tag of the n-cell */
typedef ElementTag tag;
/** @brief Publish ID handling class for dispatches */
typedef typename result_of::element_id_handler<ConfigType, point_tag>::type::id_type id_type;
element_t ( ) {}; //construction of "template" for this type
element_t (const element_t & e2) : Base(e2)
{
//std::cout << "Copy constructor Element " << this << std::endl;
this->id(e2.id());
};
/** @brief Set the vertices defining the n-cell */
// void vertices(VertexType **vertices_, std::size_t num = VertexSpecs::num)
// {
// Base::set_vertices(vertices_, num);
// }
/** @brief Callback function used for filling the domain */
template<typename inserter_type>
void insert_callback( inserter_type & inserter, bool inserted )
{
if (inserted) Base::create_bnd_cells(inserter);
}
};
/** @brief Overload for the output streaming operator */
template <typename ConfigType, typename ElementTag>
std::ostream & operator<<(std::ostream & os, element_t<ConfigType, ElementTag> const & el)
{
typedef element_t<ConfigType, ElementTag> ElementType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexRange;
typedef typename viennagrid::result_of::iterator<VertexRange>::type VertexIterator;
os << "-- " << ElementTag::name() << ", ID: " << el.id() << " --";
VertexRange vertices = viennagrid::ncells<0>(el);
for (VertexIterator vit = vertices.begin();
vit != vertices.end();
++vit)
os << std::endl << " " << *vit;
return os;
}
//vertex-type needs separate treatment:
/** @brief Specialization of the main n-cell class for vertices. Does not need to do any recursive inheritance here. */
template <typename ConfigType>
class element_t <ConfigType, point_tag> :
public result_of::element_id_handler<ConfigType, point_tag>::type
{
typedef typename result_of::point<ConfigType>::type PointType;
typedef typename ConfigType::numeric_type CoordType;
typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
typedef typename ConfigType::cell_tag CellTag;
public:
typedef ConfigType config_type;
typedef point_tag tag;
typedef typename result_of::element_id_handler<ConfigType, point_tag>::type::id_type id_type;
element_t() { };
element_t(PointType const & p, long id = -1) : point_(p)
{
this->id(id);
};
element_t(const element_t & e2)
{
//std::cout << "Copy constructor Element (Vertex) " << this << std::endl;
point_ = e2.point_;
this->id(e2.id());
}
//clean up any data associated with the element if it is destroyed:
~element_t() { viennadata::erase<viennadata::all, viennadata::all>()(*this); }
template<typename inserter_type>
void insert_callback( inserter_type & inserter, bool inserted )
{}
element_t & operator=(const element_t & other)
{
point_ = other.point_;
this->id(other.id());
return *this;
}
/** @brief Provide access to the geometrical point object defining the location of the vertex in space */
PointType & point() { return point_; }
/** @brief Provide access to the geometrical point object defining the location of the vertex in space. const-version. */
PointType const & point() const { return point_; }
//convenience access to coordinates of the vertex:
/** @brief Convenience access to the coordinates of the point */
CoordType & operator[](std::size_t i) { return point_[i]; }
/** @brief Convenience access to the coordinates of the point. const-version*/
CoordType const & operator[](std::size_t i) const { return point_[i]; }
/** @brief Convenience forward for obtaining the geometrical dimension of the underlying Euclidian space. */
std::size_t size() const { return point_.size(); }
/** @brief Convenience less-than comparison function, forwarding to the point */
bool operator<(const element_t e2) const { return point_ < e2.point_; }
/** @brief Convenience greater-than comparison function, forwarding to the point */
bool operator>(const element_t e2) const { return point_ > e2.point_; }
private:
PointType point_;
};
/** @brief Overload for the output streaming operator for the vertex type */
template <typename ConfigType>
std::ostream & operator<<(std::ostream & os, element_t<ConfigType, point_tag> const & el)
{
os << "-- Vertex, ID: " << el.id() << "; Point: " << el.point();
return os;
}
}
#endif
<commit_msg>adapted to new insert callback<commit_after>#ifndef VIENNAGRID_ELEMENT_HPP
#define VIENNAGRID_ELEMENT_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/forwards.h"
#include "viennagrid/detail/element_iterators.hpp"
#include "viennagrid/detail/boundary_ncell_layer.hpp"
#include "viennagrid/meta/typelist.hpp"
#include <vector>
/** @file element.hpp
@brief Provides the main n-cell type
*/
namespace viennagrid
{
////////////// Top Level configuration //////////
/** @brief The main n-cell class. Assembled by recursive inheritance
*
* @tparam ConfigType Configuration class
* @tparam ElementTag A tag denoting the particular topological shape of the n-cell
*/
template <typename ConfigType,
typename ElementTag>
class element_t :
public boundary_ncell_layer < ConfigType, ElementTag, ElementTag::dim - 1>,
public result_of::element_id_handler<ConfigType, ElementTag>::type
{
typedef typename ConfigType::numeric_type ScalarType;
typedef boundary_ncell_layer < ConfigType, ElementTag, ElementTag::dim - 1> Base;
typedef typename result_of::point<ConfigType>::type PointType;
//typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
typedef topology::bndcells<ElementTag, 0> VertexSpecs;
public:
typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
typedef typename viennameta::typelist::result_of::push_back< typename Base::required_types, element_t >::type required_types;
/** @brief Publish the configuration class */
typedef ConfigType config_type;
/** @brief Tag of the n-cell */
typedef ElementTag tag;
/** @brief Publish ID handling class for dispatches */
typedef typename result_of::element_id_handler<ConfigType, point_tag>::type::id_type id_type;
element_t ( ) {}; //construction of "template" for this type
element_t (const element_t & e2) : Base(e2)
{
//std::cout << "Copy constructor Element " << this << std::endl;
this->id(e2.id());
};
/** @brief Set the vertices defining the n-cell */
// void vertices(VertexType **vertices_, std::size_t num = VertexSpecs::num)
// {
// Base::set_vertices(vertices_, num);
// }
/** @brief Callback function used for filling the domain */
template<typename inserter_type, typename container_collection_type>
void insert_callback( inserter_type & inserter, bool inserted, container_collection_type & container_collection )
{
if (inserted) Base::create_bnd_cells(inserter);
}
};
/** @brief Overload for the output streaming operator */
template <typename ConfigType, typename ElementTag>
std::ostream & operator<<(std::ostream & os, element_t<ConfigType, ElementTag> const & el)
{
typedef element_t<ConfigType, ElementTag> ElementType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexRange;
typedef typename viennagrid::result_of::iterator<VertexRange>::type VertexIterator;
os << "-- " << ElementTag::name() << ", ID: " << el.id() << " --";
VertexRange vertices = viennagrid::ncells<0>(el);
for (VertexIterator vit = vertices.begin();
vit != vertices.end();
++vit)
os << std::endl << " " << *vit;
return os;
}
//vertex-type needs separate treatment:
/** @brief Specialization of the main n-cell class for vertices. Does not need to do any recursive inheritance here. */
template <typename ConfigType>
class element_t <ConfigType, point_tag> :
public result_of::element_id_handler<ConfigType, point_tag>::type
{
typedef typename result_of::point<ConfigType>::type PointType;
typedef typename ConfigType::numeric_type CoordType;
typedef typename result_of::ncell<ConfigType, 0>::type VertexType;
typedef typename ConfigType::cell_tag CellTag;
public:
typedef ConfigType config_type;
typedef point_tag tag;
typedef typename result_of::element_id_handler<ConfigType, point_tag>::type::id_type id_type;
element_t() { };
element_t(PointType const & p, long id = -1) : point_(p)
{
this->id(id);
};
element_t(const element_t & e2)
{
//std::cout << "Copy constructor Element (Vertex) " << this << std::endl;
point_ = e2.point_;
this->id(e2.id());
}
//clean up any data associated with the element if it is destroyed:
~element_t() { viennadata::erase<viennadata::all, viennadata::all>()(*this); }
template<typename inserter_type, typename container_collection_type>
void insert_callback( inserter_type & inserter, bool inserted, container_collection_type & container_collection )
{}
element_t & operator=(const element_t & other)
{
point_ = other.point_;
this->id(other.id());
return *this;
}
/** @brief Provide access to the geometrical point object defining the location of the vertex in space */
PointType & point() { return point_; }
/** @brief Provide access to the geometrical point object defining the location of the vertex in space. const-version. */
PointType const & point() const { return point_; }
//convenience access to coordinates of the vertex:
/** @brief Convenience access to the coordinates of the point */
CoordType & operator[](std::size_t i) { return point_[i]; }
/** @brief Convenience access to the coordinates of the point. const-version*/
CoordType const & operator[](std::size_t i) const { return point_[i]; }
/** @brief Convenience forward for obtaining the geometrical dimension of the underlying Euclidian space. */
std::size_t size() const { return point_.size(); }
/** @brief Convenience less-than comparison function, forwarding to the point */
bool operator<(const element_t e2) const { return point_ < e2.point_; }
/** @brief Convenience greater-than comparison function, forwarding to the point */
bool operator>(const element_t e2) const { return point_ > e2.point_; }
private:
PointType point_;
};
/** @brief Overload for the output streaming operator for the vertex type */
template <typename ConfigType>
std::ostream & operator<<(std::ostream & os, element_t<ConfigType, point_tag> const & el)
{
os << "-- Vertex, ID: " << el.id() << "; Point: " << el.point();
return os;
}
}
#endif
<|endoftext|> |
<commit_before>
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdint.h>
#include <memory>
#include "bytes.hh"
#include "utils/allocation_strategy.hh"
#include <seastar/core/unaligned.hh>
#include <unordered_map>
#include <type_traits>
struct blob_storage {
using size_type = uint32_t;
using char_type = bytes_view::value_type;
blob_storage** backref;
size_type size;
size_type frag_size;
blob_storage* next;
char_type data[];
blob_storage(blob_storage** backref, size_type size, size_type frag_size) noexcept
: backref(backref)
, size(size)
, frag_size(frag_size)
, next(nullptr)
{
*unaligned_cast<blob_storage**>(backref) = this;
}
blob_storage(blob_storage&& o) noexcept
: backref(o.backref)
, size(o.size)
, frag_size(o.frag_size)
, next(o.next)
{
*unaligned_cast<blob_storage**>(backref) = this;
o.next = nullptr;
if (next) {
next->backref = &next;
}
memcpy(data, o.data, frag_size);
}
} __attribute__((packed));
// A managed version of "bytes" (can be used with LSA).
class managed_bytes {
struct linearization_context {
unsigned _nesting = 0;
// Map from first blob_storage address to linearized version
// We use the blob_storage address to be insentive to moving
// a managed_bytes object.
std::unordered_map<const blob_storage*, std::unique_ptr<bytes_view::value_type[]>> _state;
void enter() {
++_nesting;
}
void leave() {
if (!--_nesting) {
_state.clear();
}
}
void forget(const blob_storage* p) noexcept;
};
static thread_local linearization_context _linearization_context;
public:
struct linearization_context_guard {
linearization_context_guard() {
_linearization_context.enter();
}
~linearization_context_guard() {
_linearization_context.leave();
}
};
private:
static constexpr size_t max_inline_size = 15;
struct small_blob {
bytes_view::value_type data[max_inline_size];
int8_t size; // -1 -> use blob_storage
};
union {
blob_storage* ptr;
small_blob small;
} _u;
static_assert(sizeof(small_blob) > sizeof(blob_storage*), "inline size too small");
private:
bool external() const {
return _u.small.size < 0;
}
size_t max_seg(allocation_strategy& alctr) {
return alctr.preferred_max_contiguous_allocation() - sizeof(blob_storage);
}
void free_chain(blob_storage* p) noexcept {
if (p->next && _linearization_context._nesting) {
_linearization_context.forget(p);
}
auto& alctr = current_allocator();
while (p) {
auto n = p->next;
alctr.destroy(p);
p = n;
}
}
const bytes_view::value_type* read_linearize() const {
if (!external()) {
return _u.small.data;
} else if (!_u.ptr->next) {
return _u.ptr->data;
} else {
return do_linearize();
}
}
bytes_view::value_type& value_at_index(blob_storage::size_type index) {
if (!external()) {
return _u.small.data[index];
}
blob_storage* a = _u.ptr;
while (index >= a->frag_size) {
index -= a->frag_size;
a = a->next;
}
return a->data[index];
}
const bytes_view::value_type* do_linearize() const;
public:
using size_type = blob_storage::size_type;
struct initialized_later {};
managed_bytes() {
_u.small.size = 0;
}
managed_bytes(const blob_storage::char_type* ptr, size_type size)
: managed_bytes(bytes_view(ptr, size)) {}
managed_bytes(const bytes& b) : managed_bytes(static_cast<bytes_view>(b)) {}
managed_bytes(initialized_later, size_type size) {
if (size <= max_inline_size) {
_u.small.size = size;
} else {
_u.small.size = -1;
auto& alctr = current_allocator();
auto maxseg = max_seg(alctr);
auto now = std::min(size_t(size), maxseg);
void* p = alctr.alloc(&standard_migrator<blob_storage>::object,
sizeof(blob_storage) + now, alignof(blob_storage));
auto first = new (p) blob_storage(&_u.ptr, size, now);
auto last = first;
size -= now;
try {
while (size) {
auto now = std::min(size_t(size), maxseg);
void* p = alctr.alloc(&standard_migrator<blob_storage>::object,
sizeof(blob_storage) + now, alignof(blob_storage));
last = new (p) blob_storage(&last->next, 0, now);
size -= now;
}
} catch (...) {
free_chain(first);
throw;
}
}
}
managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {
if (!external()) {
std::copy(v.begin(), v.end(), _u.small.data);
return;
}
auto p = v.data();
auto s = v.size();
auto b = _u.ptr;
while (s) {
memcpy(b->data, p, b->frag_size);
p += b->frag_size;
s -= b->frag_size;
b = b->next;
}
assert(!b);
}
managed_bytes(std::initializer_list<bytes::value_type> b) : managed_bytes(b.begin(), b.size()) {}
~managed_bytes() noexcept {
if (external()) {
free_chain(_u.ptr);
}
}
managed_bytes(const managed_bytes& o) : managed_bytes(initialized_later(), o.size()) {
if (!external()) {
memcpy(data(), o.data(), size());
return;
}
auto s = size();
blob_storage* const* next_src = &o._u.ptr;
blob_storage* blob_src = nullptr;
size_type size_src = 0;
size_type offs_src = 0;
blob_storage** next_dst = &_u.ptr;
blob_storage* blob_dst = nullptr;
size_type size_dst = 0;
size_type offs_dst = 0;
while (s) {
if (!size_src) {
blob_src = *unaligned_cast<blob_storage**>(next_src);
next_src = &blob_src->next;
size_src = blob_src->frag_size;
offs_src = 0;
}
if (!size_dst) {
blob_dst = *unaligned_cast<blob_storage**>(next_dst);
next_dst = &blob_dst->next;
size_dst = blob_dst->frag_size;
offs_dst = 0;
}
auto now = std::min(size_src, size_dst);
memcpy(blob_dst->data + offs_dst, blob_src->data + offs_src, now);
s -= now;
offs_src += now; size_src -= now;
offs_dst += now; size_dst -= now;
}
assert(size_src == 0 && size_dst == 0);
}
managed_bytes(managed_bytes&& o) noexcept
: _u(o._u)
{
if (external()) {
if (_u.ptr) {
_u.ptr->backref = &_u.ptr;
}
}
o._u.small.size = 0;
}
managed_bytes& operator=(managed_bytes&& o) noexcept {
if (this != &o) {
this->~managed_bytes();
new (this) managed_bytes(std::move(o));
}
return *this;
}
managed_bytes& operator=(const managed_bytes& o) {
if (this != &o) {
managed_bytes tmp(o);
this->~managed_bytes();
new (this) managed_bytes(std::move(tmp));
}
return *this;
}
bool operator==(const managed_bytes& o) const {
if (size() != o.size()) {
return false;
}
if (!external()) {
return bytes_view(*this) == bytes_view(o);
} else {
auto a = _u.ptr;
auto a_data = a->data;
auto a_remain = a->frag_size;
a = a->next;
auto b = o._u.ptr;
auto b_data = b->data;
auto b_remain = b->frag_size;
b = b->next;
while (a_remain || b_remain) {
auto now = std::min(a_remain, b_remain);
if (bytes_view(a_data, now) != bytes_view(b_data, now)) {
return false;
}
a_data += now;
a_remain -= now;
if (!a_remain && a) {
a_data = a->data;
a_remain = a->frag_size;
a = a->next;
}
b_data += now;
b_remain -= now;
if (!b_remain && b) {
b_data = b->data;
b_remain = b->frag_size;
b = b->next;
}
}
return true;
}
}
bool operator!=(const managed_bytes& o) const {
return !(*this == o);
}
operator bytes_view() const {
return { data(), size() };
}
bytes_view::value_type& operator[](size_type index) {
return value_at_index(index);
}
const bytes_view::value_type& operator[](size_type index) const {
return const_cast<const bytes_view::value_type&>(
const_cast<managed_bytes*>(this)->value_at_index(index));
}
size_type size() const {
if (external()) {
return _u.ptr->size;
} else {
return _u.small.size;
}
}
const blob_storage::char_type* begin() const {
return data();
}
const blob_storage::char_type* end() const {
return data() + size();
}
blob_storage::char_type* begin() {
return data();
}
blob_storage::char_type* end() {
return data() + size();
}
bool empty() const {
return _u.small.size == 0;
}
blob_storage::char_type* data() {
if (external()) {
assert(!_u.ptr->next); // must be linearized
return _u.ptr->data;
} else {
return _u.small.data;
}
}
const blob_storage::char_type* data() const {
return read_linearize();
}
// Returns the amount of external memory used.
size_t external_memory_usage() const {
if (external()) {
size_t mem = 0;
blob_storage* blob = _u.ptr;
while (blob) {
mem += blob->frag_size + sizeof(blob_storage);
blob = blob->next;
}
return mem;
}
return 0;
}
template <typename Func>
friend std::result_of_t<Func()> with_linearized_managed_bytes(Func&& func);
};
// Run func() while ensuring that reads of managed_bytes objects are
// temporarlily linearized
template <typename Func>
inline
std::result_of_t<Func()>
with_linearized_managed_bytes(Func&& func) {
managed_bytes::linearization_context_guard g;
return func();
}
namespace std {
template <>
struct hash<managed_bytes> {
size_t operator()(const managed_bytes& v) const {
return hash<bytes_view>()(v);
}
};
}
<commit_msg>managed_bytes: add cast to mutable_view<commit_after>
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdint.h>
#include <memory>
#include "bytes.hh"
#include "utils/allocation_strategy.hh"
#include <seastar/core/unaligned.hh>
#include <unordered_map>
#include <type_traits>
struct blob_storage {
using size_type = uint32_t;
using char_type = bytes_view::value_type;
blob_storage** backref;
size_type size;
size_type frag_size;
blob_storage* next;
char_type data[];
blob_storage(blob_storage** backref, size_type size, size_type frag_size) noexcept
: backref(backref)
, size(size)
, frag_size(frag_size)
, next(nullptr)
{
*unaligned_cast<blob_storage**>(backref) = this;
}
blob_storage(blob_storage&& o) noexcept
: backref(o.backref)
, size(o.size)
, frag_size(o.frag_size)
, next(o.next)
{
*unaligned_cast<blob_storage**>(backref) = this;
o.next = nullptr;
if (next) {
next->backref = &next;
}
memcpy(data, o.data, frag_size);
}
} __attribute__((packed));
// A managed version of "bytes" (can be used with LSA).
class managed_bytes {
struct linearization_context {
unsigned _nesting = 0;
// Map from first blob_storage address to linearized version
// We use the blob_storage address to be insentive to moving
// a managed_bytes object.
std::unordered_map<const blob_storage*, std::unique_ptr<bytes_view::value_type[]>> _state;
void enter() {
++_nesting;
}
void leave() {
if (!--_nesting) {
_state.clear();
}
}
void forget(const blob_storage* p) noexcept;
};
static thread_local linearization_context _linearization_context;
public:
struct linearization_context_guard {
linearization_context_guard() {
_linearization_context.enter();
}
~linearization_context_guard() {
_linearization_context.leave();
}
};
private:
static constexpr size_t max_inline_size = 15;
struct small_blob {
bytes_view::value_type data[max_inline_size];
int8_t size; // -1 -> use blob_storage
};
union {
blob_storage* ptr;
small_blob small;
} _u;
static_assert(sizeof(small_blob) > sizeof(blob_storage*), "inline size too small");
private:
bool external() const {
return _u.small.size < 0;
}
size_t max_seg(allocation_strategy& alctr) {
return alctr.preferred_max_contiguous_allocation() - sizeof(blob_storage);
}
void free_chain(blob_storage* p) noexcept {
if (p->next && _linearization_context._nesting) {
_linearization_context.forget(p);
}
auto& alctr = current_allocator();
while (p) {
auto n = p->next;
alctr.destroy(p);
p = n;
}
}
const bytes_view::value_type* read_linearize() const {
if (!external()) {
return _u.small.data;
} else if (!_u.ptr->next) {
return _u.ptr->data;
} else {
return do_linearize();
}
}
bytes_view::value_type& value_at_index(blob_storage::size_type index) {
if (!external()) {
return _u.small.data[index];
}
blob_storage* a = _u.ptr;
while (index >= a->frag_size) {
index -= a->frag_size;
a = a->next;
}
return a->data[index];
}
const bytes_view::value_type* do_linearize() const;
public:
using size_type = blob_storage::size_type;
struct initialized_later {};
managed_bytes() {
_u.small.size = 0;
}
managed_bytes(const blob_storage::char_type* ptr, size_type size)
: managed_bytes(bytes_view(ptr, size)) {}
managed_bytes(const bytes& b) : managed_bytes(static_cast<bytes_view>(b)) {}
managed_bytes(initialized_later, size_type size) {
if (size <= max_inline_size) {
_u.small.size = size;
} else {
_u.small.size = -1;
auto& alctr = current_allocator();
auto maxseg = max_seg(alctr);
auto now = std::min(size_t(size), maxseg);
void* p = alctr.alloc(&standard_migrator<blob_storage>::object,
sizeof(blob_storage) + now, alignof(blob_storage));
auto first = new (p) blob_storage(&_u.ptr, size, now);
auto last = first;
size -= now;
try {
while (size) {
auto now = std::min(size_t(size), maxseg);
void* p = alctr.alloc(&standard_migrator<blob_storage>::object,
sizeof(blob_storage) + now, alignof(blob_storage));
last = new (p) blob_storage(&last->next, 0, now);
size -= now;
}
} catch (...) {
free_chain(first);
throw;
}
}
}
managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {
if (!external()) {
std::copy(v.begin(), v.end(), _u.small.data);
return;
}
auto p = v.data();
auto s = v.size();
auto b = _u.ptr;
while (s) {
memcpy(b->data, p, b->frag_size);
p += b->frag_size;
s -= b->frag_size;
b = b->next;
}
assert(!b);
}
managed_bytes(std::initializer_list<bytes::value_type> b) : managed_bytes(b.begin(), b.size()) {}
~managed_bytes() noexcept {
if (external()) {
free_chain(_u.ptr);
}
}
managed_bytes(const managed_bytes& o) : managed_bytes(initialized_later(), o.size()) {
if (!external()) {
memcpy(data(), o.data(), size());
return;
}
auto s = size();
blob_storage* const* next_src = &o._u.ptr;
blob_storage* blob_src = nullptr;
size_type size_src = 0;
size_type offs_src = 0;
blob_storage** next_dst = &_u.ptr;
blob_storage* blob_dst = nullptr;
size_type size_dst = 0;
size_type offs_dst = 0;
while (s) {
if (!size_src) {
blob_src = *unaligned_cast<blob_storage**>(next_src);
next_src = &blob_src->next;
size_src = blob_src->frag_size;
offs_src = 0;
}
if (!size_dst) {
blob_dst = *unaligned_cast<blob_storage**>(next_dst);
next_dst = &blob_dst->next;
size_dst = blob_dst->frag_size;
offs_dst = 0;
}
auto now = std::min(size_src, size_dst);
memcpy(blob_dst->data + offs_dst, blob_src->data + offs_src, now);
s -= now;
offs_src += now; size_src -= now;
offs_dst += now; size_dst -= now;
}
assert(size_src == 0 && size_dst == 0);
}
managed_bytes(managed_bytes&& o) noexcept
: _u(o._u)
{
if (external()) {
if (_u.ptr) {
_u.ptr->backref = &_u.ptr;
}
}
o._u.small.size = 0;
}
managed_bytes& operator=(managed_bytes&& o) noexcept {
if (this != &o) {
this->~managed_bytes();
new (this) managed_bytes(std::move(o));
}
return *this;
}
managed_bytes& operator=(const managed_bytes& o) {
if (this != &o) {
managed_bytes tmp(o);
this->~managed_bytes();
new (this) managed_bytes(std::move(tmp));
}
return *this;
}
bool operator==(const managed_bytes& o) const {
if (size() != o.size()) {
return false;
}
if (!external()) {
return bytes_view(*this) == bytes_view(o);
} else {
auto a = _u.ptr;
auto a_data = a->data;
auto a_remain = a->frag_size;
a = a->next;
auto b = o._u.ptr;
auto b_data = b->data;
auto b_remain = b->frag_size;
b = b->next;
while (a_remain || b_remain) {
auto now = std::min(a_remain, b_remain);
if (bytes_view(a_data, now) != bytes_view(b_data, now)) {
return false;
}
a_data += now;
a_remain -= now;
if (!a_remain && a) {
a_data = a->data;
a_remain = a->frag_size;
a = a->next;
}
b_data += now;
b_remain -= now;
if (!b_remain && b) {
b_data = b->data;
b_remain = b->frag_size;
b = b->next;
}
}
return true;
}
}
bool operator!=(const managed_bytes& o) const {
return !(*this == o);
}
operator bytes_view() const {
return { data(), size() };
}
bool is_fragmented() const {
return external() && _u.ptr->next;
}
operator bytes_mutable_view() {
assert(!is_fragmented());
return { data(), size() };
};
bytes_view::value_type& operator[](size_type index) {
return value_at_index(index);
}
const bytes_view::value_type& operator[](size_type index) const {
return const_cast<const bytes_view::value_type&>(
const_cast<managed_bytes*>(this)->value_at_index(index));
}
size_type size() const {
if (external()) {
return _u.ptr->size;
} else {
return _u.small.size;
}
}
const blob_storage::char_type* begin() const {
return data();
}
const blob_storage::char_type* end() const {
return data() + size();
}
blob_storage::char_type* begin() {
return data();
}
blob_storage::char_type* end() {
return data() + size();
}
bool empty() const {
return _u.small.size == 0;
}
blob_storage::char_type* data() {
if (external()) {
assert(!_u.ptr->next); // must be linearized
return _u.ptr->data;
} else {
return _u.small.data;
}
}
const blob_storage::char_type* data() const {
return read_linearize();
}
// Returns the amount of external memory used.
size_t external_memory_usage() const {
if (external()) {
size_t mem = 0;
blob_storage* blob = _u.ptr;
while (blob) {
mem += blob->frag_size + sizeof(blob_storage);
blob = blob->next;
}
return mem;
}
return 0;
}
template <typename Func>
friend std::result_of_t<Func()> with_linearized_managed_bytes(Func&& func);
};
// Run func() while ensuring that reads of managed_bytes objects are
// temporarlily linearized
template <typename Func>
inline
std::result_of_t<Func()>
with_linearized_managed_bytes(Func&& func) {
managed_bytes::linearization_context_guard g;
return func();
}
namespace std {
template <>
struct hash<managed_bytes> {
size_t operator()(const managed_bytes& v) const {
return hash<bytes_view>()(v);
}
};
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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 <dali/dali.h>
#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/devel-api/controls/bubble-effect/bubble-emitter.h>
#include "shared/view.h"
using namespace Dali;
namespace
{
const char * const TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
const char * const APPLICATION_TITLE( "Bubble Effect" );
const char * const CHANGE_BACKGROUND_ICON( DALI_IMAGE_DIR "icon-change.png" );
const char * const CHANGE_BUBBLE_SHAPE_ICON( DALI_IMAGE_DIR "icon-replace.png" );
const char* BACKGROUND_IMAGES[]=
{
DALI_IMAGE_DIR "background-1.jpg",
DALI_IMAGE_DIR "background-2.jpg",
DALI_IMAGE_DIR "background-3.jpg",
DALI_IMAGE_DIR "background-4.jpg",
DALI_IMAGE_DIR "background-5.jpg",
};
const unsigned int NUM_BACKGROUND_IMAGES( sizeof( BACKGROUND_IMAGES ) / sizeof( BACKGROUND_IMAGES[0] ) );
const char* BUBBLE_SHAPE_IMAGES[] =
{
DALI_IMAGE_DIR "bubble-ball.png",
DALI_IMAGE_DIR "icon-item-view-layout-spiral.png",
DALI_IMAGE_DIR "icon-replace.png",
DALI_IMAGE_DIR "icon-effect-cross.png"
};
const unsigned int NUM_BUBBLE_SHAPE_IMAGES( sizeof( BUBBLE_SHAPE_IMAGES ) / sizeof( BUBBLE_SHAPE_IMAGES[0] ) );
const Vector2 DEFAULT_BUBBLE_SIZE( 10.f, 30.f );
const unsigned int DEFAULT_NUMBER_OF_BUBBLES( 1000 );
/**
* @brief Load an image, scaled-down to no more than the stage dimensions.
*
* Uses image scaling mode FittingMode::SCALE_TO_FILL to resize the image at
* load time to cover the entire stage with pixels with no borders,
* and filter mode BOX_THEN_LINEAR to sample the image with
* maximum quality.
*/
ResourceImage LoadStageFillingImage( const char * const imagePath )
{
Size stageSize = Stage::GetCurrent().GetSize();
return ResourceImage::New( imagePath, Dali::ImageDimensions( stageSize.x, stageSize.y ), Dali::FittingMode::SCALE_TO_FILL, Dali::SamplingMode::BOX_THEN_LINEAR );
}
}// end LOCAL_STUFF
// This example shows the usage of BubbleEmitter which displays lots of moving bubbles on the stage.
class BubbleEffectExample : public ConnectionTracker
{
public:
BubbleEffectExample(Application &app)
: mApp(app),
mHSVDelta( Vector3( 0.f, 0.f, 0.5f ) ),
mNeedNewAnimation( true ),
mTimerInterval( 16 ),
mCurrentBackgroundImageId( 0 ),
mCurrentBubbleShapeImageId( 0 )
{
// Connect to the Application's Init signal
app.InitSignal().Connect(this, &BubbleEffectExample::Create);
}
~BubbleEffectExample()
{
}
private:
// The Init signal is received once (only) during the Application lifetime
void Create(Application& app)
{
Stage stage = Stage::GetCurrent();
Vector2 stageSize = stage.GetSize();
stage.KeyEventSignal().Connect(this, &BubbleEffectExample::OnKeyEvent);
// Creates a default view with a default tool bar.
// The view is added to the stage.
Toolkit::ToolBar toolBar;
Toolkit::Control view;
Layer content = DemoHelper::CreateView( app,
view,
toolBar,
"",
TOOLBAR_IMAGE,
APPLICATION_TITLE );
// Add a button to change background. (right of toolbar)
mChangeBackgroundButton = Toolkit::PushButton::New();
mChangeBackgroundButton.SetBackgroundImage( ResourceImage::New( CHANGE_BACKGROUND_ICON ) );
mChangeBackgroundButton.ClickedSignal().Connect( this, &BubbleEffectExample::OnChangeIconClicked );
toolBar.AddControl( mChangeBackgroundButton,
DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage,
Toolkit::Alignment::HorizontalRight,
DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
// Add a button to change bubble shape. ( left of bar )
mChangeBubbleShapeButton = Toolkit::PushButton::New();
mChangeBubbleShapeButton.SetBackgroundImage( ResourceImage::New( CHANGE_BUBBLE_SHAPE_ICON ) );
mChangeBubbleShapeButton.ClickedSignal().Connect( this, &BubbleEffectExample::OnChangeIconClicked );
toolBar.AddControl( mChangeBubbleShapeButton,
DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage,
Toolkit::Alignment::HorizontalLeft,
DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
// Create and initialize the BubbleEmitter object
mBubbleEmitter = Toolkit::BubbleEmitter::New( stageSize,
ResourceImage::New( BUBBLE_SHAPE_IMAGES[mCurrentBubbleShapeImageId] ),
DEFAULT_NUMBER_OF_BUBBLES,
DEFAULT_BUBBLE_SIZE);
mBackgroundImage = LoadStageFillingImage( BACKGROUND_IMAGES[mCurrentBackgroundImageId] );
mBubbleEmitter.SetBackground( mBackgroundImage, mHSVDelta );
// Get the root actor of all bubbles, and add it to stage.
Actor bubbleRoot = mBubbleEmitter.GetRootActor();
bubbleRoot.SetParentOrigin(ParentOrigin::CENTER);
bubbleRoot.SetZ(0.1f); // Make sure the bubbles displayed on top og the background.
content.Add( bubbleRoot );
// Add the background image actor to stage
view.SetBackgroundImage( mBackgroundImage );
mBackgroundActor = ImageActor::DownCast( view.GetBackgroundActor() );
// Set up the timer to emit bubble regularly when the finger is touched down but not moved
mTimerForBubbleEmission = Timer::New( mTimerInterval );
mTimerForBubbleEmission.TickSignal().Connect(this, &BubbleEffectExample::OnTimerTick);
// Connect the callback to the touch signal on the background
mBackgroundActor.TouchedSignal().Connect( this, &BubbleEffectExample::OnTouch );
}
/***********
* Emit bubbles
*****************/
// Set up the animation of emitting bubbles, to be efficient, every animation controls multiple bubbles ( 4 here )
void SetUpAnimation( Vector2 emitPosition, Vector2 direction )
{
if( mNeedNewAnimation )
{
float duration = Random::Range(1.f, 1.5f);
mEmitAnimation = Animation::New( duration );
mNeedNewAnimation = false;
mAnimateComponentCount = 0;
}
mBubbleEmitter.EmitBubble( mEmitAnimation, emitPosition, direction + Vector2(0.f, 30.f) /* upwards */, Vector2(300, 600) );
mAnimateComponentCount++;
if( mAnimateComponentCount % 4 ==0 )
{
mEmitAnimation.Play();
mNeedNewAnimation = true;
}
}
// Emit bubbles when the finger touches down but keep stationary.
// And stops emitting new bubble after being stationary for 2 seconds
bool OnTimerTick()
{
if(mEmitPosition == mCurrentTouchPosition) // finger is not moving
{
mNonMovementCount++;
if(mNonMovementCount < (1000 / mTimerInterval)) // 1 seconds
{
for(int i = 0; i < 4; i++) // emit 4 bubbles every timer tick
{
SetUpAnimation( mCurrentTouchPosition+Vector2(rand()%5, rand()%5), Vector2(rand()%60-30, rand()%100-50) );
}
}
}
else
{
mNonMovementCount = 0;
mEmitPosition = mCurrentTouchPosition;
}
return true;
}
// Callback function of the touch signal on the background
bool OnTouch(Dali::Actor actor, const Dali::TouchEvent& event)
{
const TouchPoint &point = event.GetPoint(0);
switch(point.state)
{
case TouchPoint::Down:
{
mCurrentTouchPosition = point.screen;
mEmitPosition = point.screen;
mTimerForBubbleEmission.Start();
mNonMovementCount = 0;
break;
}
case TouchPoint::Motion:
{
Vector2 displacement = point.screen - mCurrentTouchPosition;
mCurrentTouchPosition = point.screen;
//emit multiple bubbles along the moving direction when the finger moves quickly
float step = std::min(5.f, displacement.Length());
for( float i=0.25f; i<step; i=i+1.f)
{
SetUpAnimation( mCurrentTouchPosition+displacement*(i/step), displacement );
}
break;
}
case TouchPoint::Up:
case TouchPoint::Leave:
case TouchPoint::Interrupted:
{
mTimerForBubbleEmission.Stop();
break;
}
case TouchPoint::Stationary:
case TouchPoint::Last:
default:
{
break;
}
}
return true;
}
bool OnChangeIconClicked( Toolkit::Button button )
{
if(button == mChangeBackgroundButton)
{
mBackgroundImage = LoadStageFillingImage( BACKGROUND_IMAGES[ ++mCurrentBackgroundImageId % NUM_BACKGROUND_IMAGES ] );
mBubbleEmitter.SetBackground( mBackgroundImage, mHSVDelta );
mBackgroundActor.SetImage( mBackgroundImage );
}
else if( button == mChangeBubbleShapeButton )
{
mBubbleEmitter.SetShapeImage( ResourceImage::New( BUBBLE_SHAPE_IMAGES[ ++mCurrentBubbleShapeImageId % NUM_BUBBLE_SHAPE_IMAGES ] ) );
}
return true;
}
/**
* Main key event handler
*/
void OnKeyEvent(const KeyEvent& event)
{
if(event.state == KeyEvent::Down)
{
if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
{
mApp.Quit();
}
}
}
private:
Application& mApp;
Image mBackgroundImage;
ImageActor mBackgroundActor;
Toolkit::BubbleEmitter mBubbleEmitter;
Vector3 mHSVDelta;
Animation mEmitAnimation;
unsigned int mAnimateComponentCount;
bool mNeedNewAnimation;
Timer mTimerForBubbleEmission;
unsigned int mNonMovementCount;
unsigned int mTimerInterval;
Vector2 mCurrentTouchPosition;
Vector2 mEmitPosition;
Toolkit::PushButton mChangeBackgroundButton;
Toolkit::PushButton mChangeBubbleShapeButton;
unsigned int mCurrentBackgroundImageId;
unsigned int mCurrentBubbleShapeImageId;
};
/*****************************************************************************/
static void
RunTest(Application& app)
{
BubbleEffectExample theApp(app);
app.MainLoop();
}
/*****************************************************************************/
int
main(int argc, char **argv)
{
Application app = Application::New(&argc, &argv, DALI_DEMO_THEME_PATH);
RunTest(app);
return 0;
}
<commit_msg>Remove unnecessary use of ImageActor from bubble-demo<commit_after>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd.
*
* 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 <dali/dali.h>
#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/devel-api/controls/bubble-effect/bubble-emitter.h>
#include "shared/view.h"
using namespace Dali;
namespace
{
const char * const TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
const char * const APPLICATION_TITLE( "Bubble Effect" );
const char * const CHANGE_BACKGROUND_ICON( DALI_IMAGE_DIR "icon-change.png" );
const char * const CHANGE_BUBBLE_SHAPE_ICON( DALI_IMAGE_DIR "icon-replace.png" );
const char* BACKGROUND_IMAGES[]=
{
DALI_IMAGE_DIR "background-1.jpg",
DALI_IMAGE_DIR "background-2.jpg",
DALI_IMAGE_DIR "background-3.jpg",
DALI_IMAGE_DIR "background-4.jpg",
DALI_IMAGE_DIR "background-5.jpg",
};
const unsigned int NUM_BACKGROUND_IMAGES( sizeof( BACKGROUND_IMAGES ) / sizeof( BACKGROUND_IMAGES[0] ) );
const char* BUBBLE_SHAPE_IMAGES[] =
{
DALI_IMAGE_DIR "bubble-ball.png",
DALI_IMAGE_DIR "icon-item-view-layout-spiral.png",
DALI_IMAGE_DIR "icon-replace.png",
DALI_IMAGE_DIR "icon-effect-cross.png"
};
const unsigned int NUM_BUBBLE_SHAPE_IMAGES( sizeof( BUBBLE_SHAPE_IMAGES ) / sizeof( BUBBLE_SHAPE_IMAGES[0] ) );
const Vector2 DEFAULT_BUBBLE_SIZE( 10.f, 30.f );
const unsigned int DEFAULT_NUMBER_OF_BUBBLES( 1000 );
/**
* @brief Load an image, scaled-down to no more than the stage dimensions.
*
* Uses image scaling mode FittingMode::SCALE_TO_FILL to resize the image at
* load time to cover the entire stage with pixels with no borders,
* and filter mode BOX_THEN_LINEAR to sample the image with
* maximum quality.
*/
ResourceImage LoadStageFillingImage( const char * const imagePath )
{
Size stageSize = Stage::GetCurrent().GetSize();
return ResourceImage::New( imagePath, Dali::ImageDimensions( stageSize.x, stageSize.y ), Dali::FittingMode::SCALE_TO_FILL, Dali::SamplingMode::BOX_THEN_LINEAR );
}
}// end LOCAL_STUFF
// This example shows the usage of BubbleEmitter which displays lots of moving bubbles on the stage.
class BubbleEffectExample : public ConnectionTracker
{
public:
BubbleEffectExample(Application &app)
: mApp(app),
mHSVDelta( Vector3( 0.f, 0.f, 0.5f ) ),
mNeedNewAnimation( true ),
mTimerInterval( 16 ),
mCurrentBackgroundImageId( 0 ),
mCurrentBubbleShapeImageId( 0 )
{
// Connect to the Application's Init signal
app.InitSignal().Connect(this, &BubbleEffectExample::Create);
}
~BubbleEffectExample()
{
}
private:
// The Init signal is received once (only) during the Application lifetime
void Create(Application& app)
{
Stage stage = Stage::GetCurrent();
Vector2 stageSize = stage.GetSize();
stage.KeyEventSignal().Connect(this, &BubbleEffectExample::OnKeyEvent);
// Creates a default view with a default tool bar.
// The view is added to the stage.
Toolkit::ToolBar toolBar;
Layer content = DemoHelper::CreateView( app,
mBackground,
toolBar,
"",
TOOLBAR_IMAGE,
APPLICATION_TITLE );
// Add a button to change background. (right of toolbar)
mChangeBackgroundButton = Toolkit::PushButton::New();
mChangeBackgroundButton.SetBackgroundImage( ResourceImage::New( CHANGE_BACKGROUND_ICON ) );
mChangeBackgroundButton.ClickedSignal().Connect( this, &BubbleEffectExample::OnChangeIconClicked );
toolBar.AddControl( mChangeBackgroundButton,
DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage,
Toolkit::Alignment::HorizontalRight,
DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
// Add a button to change bubble shape. ( left of bar )
mChangeBubbleShapeButton = Toolkit::PushButton::New();
mChangeBubbleShapeButton.SetBackgroundImage( ResourceImage::New( CHANGE_BUBBLE_SHAPE_ICON ) );
mChangeBubbleShapeButton.ClickedSignal().Connect( this, &BubbleEffectExample::OnChangeIconClicked );
toolBar.AddControl( mChangeBubbleShapeButton,
DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage,
Toolkit::Alignment::HorizontalLeft,
DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
// Create and initialize the BubbleEmitter object
mBubbleEmitter = Toolkit::BubbleEmitter::New( stageSize,
ResourceImage::New( BUBBLE_SHAPE_IMAGES[mCurrentBubbleShapeImageId] ),
DEFAULT_NUMBER_OF_BUBBLES,
DEFAULT_BUBBLE_SIZE);
mBackgroundImage = LoadStageFillingImage( BACKGROUND_IMAGES[mCurrentBackgroundImageId] );
mBubbleEmitter.SetBackground( mBackgroundImage, mHSVDelta );
// Get the root actor of all bubbles, and add it to stage.
Actor bubbleRoot = mBubbleEmitter.GetRootActor();
bubbleRoot.SetParentOrigin(ParentOrigin::CENTER);
bubbleRoot.SetZ(0.1f); // Make sure the bubbles displayed on top og the background.
content.Add( bubbleRoot );
// Add the background image actor to stage
mBackground.SetBackgroundImage( mBackgroundImage );
// Set up the timer to emit bubble regularly when the finger is touched down but not moved
mTimerForBubbleEmission = Timer::New( mTimerInterval );
mTimerForBubbleEmission.TickSignal().Connect(this, &BubbleEffectExample::OnTimerTick);
// Connect the callback to the touch signal on the background
mBackground.TouchedSignal().Connect( this, &BubbleEffectExample::OnTouch );
}
/***********
* Emit bubbles
*****************/
// Set up the animation of emitting bubbles, to be efficient, every animation controls multiple bubbles ( 4 here )
void SetUpAnimation( Vector2 emitPosition, Vector2 direction )
{
if( mNeedNewAnimation )
{
float duration = Random::Range(1.f, 1.5f);
mEmitAnimation = Animation::New( duration );
mNeedNewAnimation = false;
mAnimateComponentCount = 0;
}
mBubbleEmitter.EmitBubble( mEmitAnimation, emitPosition, direction + Vector2(0.f, 30.f) /* upwards */, Vector2(300, 600) );
mAnimateComponentCount++;
if( mAnimateComponentCount % 4 ==0 )
{
mEmitAnimation.Play();
mNeedNewAnimation = true;
}
}
// Emit bubbles when the finger touches down but keep stationary.
// And stops emitting new bubble after being stationary for 2 seconds
bool OnTimerTick()
{
if(mEmitPosition == mCurrentTouchPosition) // finger is not moving
{
mNonMovementCount++;
if(mNonMovementCount < (1000 / mTimerInterval)) // 1 seconds
{
for(int i = 0; i < 4; i++) // emit 4 bubbles every timer tick
{
SetUpAnimation( mCurrentTouchPosition+Vector2(rand()%5, rand()%5), Vector2(rand()%60-30, rand()%100-50) );
}
}
}
else
{
mNonMovementCount = 0;
mEmitPosition = mCurrentTouchPosition;
}
return true;
}
// Callback function of the touch signal on the background
bool OnTouch(Dali::Actor actor, const Dali::TouchEvent& event)
{
const TouchPoint &point = event.GetPoint(0);
switch(point.state)
{
case TouchPoint::Down:
{
mCurrentTouchPosition = point.screen;
mEmitPosition = point.screen;
mTimerForBubbleEmission.Start();
mNonMovementCount = 0;
break;
}
case TouchPoint::Motion:
{
Vector2 displacement = point.screen - mCurrentTouchPosition;
mCurrentTouchPosition = point.screen;
//emit multiple bubbles along the moving direction when the finger moves quickly
float step = std::min(5.f, displacement.Length());
for( float i=0.25f; i<step; i=i+1.f)
{
SetUpAnimation( mCurrentTouchPosition+displacement*(i/step), displacement );
}
break;
}
case TouchPoint::Up:
case TouchPoint::Leave:
case TouchPoint::Interrupted:
{
mTimerForBubbleEmission.Stop();
break;
}
case TouchPoint::Stationary:
case TouchPoint::Last:
default:
{
break;
}
}
return true;
}
bool OnChangeIconClicked( Toolkit::Button button )
{
if(button == mChangeBackgroundButton)
{
mBackgroundImage = LoadStageFillingImage( BACKGROUND_IMAGES[ ++mCurrentBackgroundImageId % NUM_BACKGROUND_IMAGES ] );
mBubbleEmitter.SetBackground( mBackgroundImage, mHSVDelta );
mBackground.SetBackgroundImage( mBackgroundImage );
}
else if( button == mChangeBubbleShapeButton )
{
mBubbleEmitter.SetShapeImage( ResourceImage::New( BUBBLE_SHAPE_IMAGES[ ++mCurrentBubbleShapeImageId % NUM_BUBBLE_SHAPE_IMAGES ] ) );
}
return true;
}
/**
* Main key event handler
*/
void OnKeyEvent(const KeyEvent& event)
{
if(event.state == KeyEvent::Down)
{
if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
{
mApp.Quit();
}
}
}
private:
Application& mApp;
Image mBackgroundImage;
Dali::Toolkit::Control mBackground;
Toolkit::BubbleEmitter mBubbleEmitter;
Vector3 mHSVDelta;
Animation mEmitAnimation;
unsigned int mAnimateComponentCount;
bool mNeedNewAnimation;
Timer mTimerForBubbleEmission;
unsigned int mNonMovementCount;
unsigned int mTimerInterval;
Vector2 mCurrentTouchPosition;
Vector2 mEmitPosition;
Toolkit::PushButton mChangeBackgroundButton;
Toolkit::PushButton mChangeBubbleShapeButton;
unsigned int mCurrentBackgroundImageId;
unsigned int mCurrentBubbleShapeImageId;
};
/*****************************************************************************/
static void
RunTest(Application& app)
{
BubbleEffectExample theApp(app);
app.MainLoop();
}
/*****************************************************************************/
int
main(int argc, char **argv)
{
Application app = Application::New(&argc, &argv, DALI_DEMO_THEME_PATH);
RunTest(app);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/input/input.h"
#include "ash/root_window_controller.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/metrics/histogram.h"
#include "base/strings/string16.h"
#include "chrome/browser/extensions/extension_function_registry.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
#include "ui/events/event.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/keyboard/keyboard_switches.h"
#if defined(USE_ASH)
#include "ash/shell.h"
#include "ui/keyboard/keyboard_util.h"
#endif
namespace {
const char kNotYetImplementedError[] =
"API is not implemented on this platform.";
} // namespace
namespace extensions {
bool VirtualKeyboardPrivateInsertTextFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
string16 text;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &text));
return keyboard::InsertText(text, ash::Shell::GetPrimaryRootWindow());
#endif
error_ = kNotYetImplementedError;
return false;
}
bool VirtualKeyboardPrivateMoveCursorFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!CommandLine::ForCurrentProcess()->HasSwitch(
keyboard::switches::kEnableSwipeSelection)) {
return false;
}
int swipe_direction;
int modifier_flags;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &swipe_direction));
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(1, &modifier_flags));
return keyboard::MoveCursor(
swipe_direction,
modifier_flags,
ash::Shell::GetPrimaryRootWindow()->GetDispatcher());
#endif
error_ = kNotYetImplementedError;
return false;
}
bool VirtualKeyboardPrivateSendKeyEventFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
base::Value* options_value = NULL;
base::DictionaryValue* params = NULL;
std::string type;
int char_value;
int key_code;
int modifiers;
EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &options_value));
EXTENSION_FUNCTION_VALIDATE(options_value->GetAsDictionary(¶ms));
EXTENSION_FUNCTION_VALIDATE(params->GetString("type", &type));
EXTENSION_FUNCTION_VALIDATE(params->GetInteger("charValue", &char_value));
EXTENSION_FUNCTION_VALIDATE(params->GetInteger("keyCode", &key_code));
EXTENSION_FUNCTION_VALIDATE(params->GetInteger("modifiers", &modifiers));
return keyboard::SendKeyEvent(
type,
char_value,
key_code,
modifiers,
ash::Shell::GetPrimaryRootWindow()->GetDispatcher());
#endif
error_ = kNotYetImplementedError;
return false;
}
bool VirtualKeyboardPrivateHideKeyboardFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
UMA_HISTOGRAM_ENUMERATION(
"VirtualKeyboard.KeyboardControlEvent",
keyboard::KEYBOARD_CONTROL_HIDE_USER,
keyboard::KEYBOARD_CONTROL_MAX);
// Pass HIDE_REASON_MANUAL since calls to HideKeyboard as part of this API
// would be user generated.
ash::Shell::GetInstance()->keyboard_controller()->HideKeyboard(
keyboard::KeyboardController::HIDE_REASON_MANUAL);
return true;
#endif
error_ = kNotYetImplementedError;
return false;
}
bool VirtualKeyboardPrivateKeyboardLoadedFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
keyboard::MarkKeyboardLoadFinished();
content::UserMetricsAction("VirtualKeyboardLoaded");
return true;
#endif
error_ = kNotYetImplementedError;
return false;
}
InputAPI::InputAPI(Profile* profile) {
}
InputAPI::~InputAPI() {
}
static base::LazyInstance<ProfileKeyedAPIFactory<InputAPI> >
g_factory = LAZY_INSTANCE_INITIALIZER;
// static
ProfileKeyedAPIFactory<InputAPI>* InputAPI::GetFactoryInstance() {
return &g_factory.Get();
}
} // namespace extensions
<commit_msg>Another fix<commit_after>// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/input/input.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/metrics/histogram.h"
#include "base/strings/string16.h"
#include "chrome/browser/extensions/extension_function_registry.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
#include "ui/events/event.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/keyboard/keyboard_switches.h"
#if defined(USE_ASH)
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ui/keyboard/keyboard_util.h"
#endif
namespace {
const char kNotYetImplementedError[] =
"API is not implemented on this platform.";
} // namespace
namespace extensions {
bool VirtualKeyboardPrivateInsertTextFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
string16 text;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &text));
return keyboard::InsertText(text, ash::Shell::GetPrimaryRootWindow());
#endif
error_ = kNotYetImplementedError;
return false;
}
bool VirtualKeyboardPrivateMoveCursorFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!CommandLine::ForCurrentProcess()->HasSwitch(
keyboard::switches::kEnableSwipeSelection)) {
return false;
}
int swipe_direction;
int modifier_flags;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &swipe_direction));
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(1, &modifier_flags));
return keyboard::MoveCursor(
swipe_direction,
modifier_flags,
ash::Shell::GetPrimaryRootWindow()->GetDispatcher());
#endif
error_ = kNotYetImplementedError;
return false;
}
bool VirtualKeyboardPrivateSendKeyEventFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
base::Value* options_value = NULL;
base::DictionaryValue* params = NULL;
std::string type;
int char_value;
int key_code;
int modifiers;
EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &options_value));
EXTENSION_FUNCTION_VALIDATE(options_value->GetAsDictionary(¶ms));
EXTENSION_FUNCTION_VALIDATE(params->GetString("type", &type));
EXTENSION_FUNCTION_VALIDATE(params->GetInteger("charValue", &char_value));
EXTENSION_FUNCTION_VALIDATE(params->GetInteger("keyCode", &key_code));
EXTENSION_FUNCTION_VALIDATE(params->GetInteger("modifiers", &modifiers));
return keyboard::SendKeyEvent(
type,
char_value,
key_code,
modifiers,
ash::Shell::GetPrimaryRootWindow()->GetDispatcher());
#endif
error_ = kNotYetImplementedError;
return false;
}
bool VirtualKeyboardPrivateHideKeyboardFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
UMA_HISTOGRAM_ENUMERATION(
"VirtualKeyboard.KeyboardControlEvent",
keyboard::KEYBOARD_CONTROL_HIDE_USER,
keyboard::KEYBOARD_CONTROL_MAX);
// Pass HIDE_REASON_MANUAL since calls to HideKeyboard as part of this API
// would be user generated.
ash::Shell::GetInstance()->keyboard_controller()->HideKeyboard(
keyboard::KeyboardController::HIDE_REASON_MANUAL);
return true;
#endif
error_ = kNotYetImplementedError;
return false;
}
bool VirtualKeyboardPrivateKeyboardLoadedFunction::RunImpl() {
#if defined(USE_ASH)
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
keyboard::MarkKeyboardLoadFinished();
content::UserMetricsAction("VirtualKeyboardLoaded");
return true;
#endif
error_ = kNotYetImplementedError;
return false;
}
InputAPI::InputAPI(Profile* profile) {
}
InputAPI::~InputAPI() {
}
static base::LazyInstance<ProfileKeyedAPIFactory<InputAPI> >
g_factory = LAZY_INSTANCE_INITIALIZER;
// static
ProfileKeyedAPIFactory<InputAPI>* InputAPI::GetFactoryInstance() {
return &g_factory.Get();
}
} // namespace extensions
<|endoftext|> |
<commit_before><commit_msg>Remove erroneous assert, pointers to references cannot be null.<commit_after><|endoftext|> |
<commit_before># include <Siv3D.hpp> // OpenSiv3D v0.4.2
void Main()
{
Window::Resize(1280, 720);
Scene::SetBackground(ColorF(0.4, 0.5, 0.6));
constexpr Vec2 pos(0, 0);
const String text = U"OpenSiv3D\nあいうえお\nアイエウオ";
/////////////////////
//
// 生成後はコメントアウト
{
String s;
for (auto i : Range(32, 126))
{
s << char32(i);
}
s += text;
// SDF の作成には時間がかかるので、
// ASCII 文字と text をあらかじめ SDF 化して、フォント情報を保存しておく
SDFFont(60, Typeface::Light).preload(s).saveGlyphs(U"sdf-font/light_60.png", U"sdf-font/light_60.json");
SDFFont(60, Typeface::Heavy).preload(s).saveGlyphs(U"sdf-font/heavy_60.png", U"sdf-font/heavy_60.json");
SDFFont(50, U"example/font/LogoTypeGothic/LogoTypeGothic.otf").preload(s).saveGlyphs(U"sdf-font/logo_50.png", U"sdf-font/logo_50.json");
}
/////////////////////
// フォント情報から SDFFont を作成
const Array<SDFFont> sdfFonts =
{
SDFFont({ U"sdf-font/light_60.png", U"sdf-font/light_60.json" }, 60, Typeface::Light),
SDFFont({ U"sdf-font/heavy_60.png", U"sdf-font/heavy_60.json" }, 60, Typeface::Heavy),
SDFFont({ U"sdf-font/logo_50.png", U"sdf-font/logo_50.json" }, 50, U"example/font/LogoTypeGothic/LogoTypeGothic.otf"),
};
const Array<Font> fonts =
{
Font(60, Typeface::Light),
Font(60, Typeface::Heavy),
Font(50, U"example/font/LogoTypeGothic/LogoTypeGothic.otf"),
};
size_t fontIndex = 0, method = 0;
double fontSize = 80, outline1 = 0.0, outline2 = 0.0;
HSV innerColor = Palette::Black, outlineColor = Palette::White;
while (System::Update())
{
const auto& sdfFont = sdfFonts[fontIndex];
const auto& font = fonts[fontIndex];
const int32 baseSize = sdfFont.baseSize();
if (method == 0)
{
Graphics2D::SetSDFParameters(sdfFont.pixelRange(), outline2);
sdfFont(text).draw(fontSize, pos, innerColor);
Graphics2D::SetSDFParameters(sdfFont.pixelRange(), outline1);
sdfFont(text).draw(fontSize, pos, outlineColor);
Graphics2D::SetSDFParameters(sdfFont.pixelRange());
sdfFont(text).draw(fontSize, pos, innerColor);
}
else if (method == 1)
{
Transformer2D tr(Mat3x2::Scale(fontSize / baseSize));
font(text).draw(pos, innerColor);
}
SimpleGUI::RadioButtons(fontIndex, { U"Light 60", U"Heavy 60", U"Logo 50" }, Vec2(20, 360), 150);
SimpleGUI::RadioButtons(method, { U"SDFFont", U"Font" }, Vec2(20, 480), 150);
SimpleGUI::Slider(U"size: {:.0f}"_fmt(fontSize), fontSize, 15, 550, Vec2(20, 560), 150, 200);
SimpleGUI::Slider(U"outline1: {:.2f}"_fmt(outline1), outline1, 0.0, 0.49, Vec2(20, 600), 150, 200, (method == 0));
SimpleGUI::Slider(U"outline2: {:.2f}"_fmt(outline2), outline2, 0.0, 0.49, Vec2(20, 640), 150, 200, (method == 0));
SimpleGUI::ColorPicker(innerColor, Vec2(400, 560));
SimpleGUI::ColorPicker(outlineColor, Vec2(580, 560));
}
}
<commit_msg>Linux/App/Main.cpp<commit_after>
# include <Siv3D.hpp> // OpenSiv3D v0.4.2
void Main()
{
// 背景を水色にする
Scene::SetBackground(ColorF(0.8, 0.9, 1.0));
// 大きさ 60 のフォントを用意
const Font font(60);
// 猫のテクスチャを用意
const Texture cat(Emoji(U"🐈"));
// 猫の座標
Vec2 catPos(640, 450);
while (System::Update())
{
// テキストを画面の中心に描く
font(U"Hello, Siv3D!🐣").drawAt(Scene::Center(), Palette::Black);
// 大きさをアニメーションさせて猫を表示する
cat.resized(100 + Periodic::Sine0_1(1s) * 20).drawAt(catPos);
// マウスカーソルに追従する半透明の赤い円を描く
Circle(Cursor::Pos(), 40).draw(ColorF(1, 0, 0, 0.5));
// [A] キーが押されたら
if (KeyA.down())
{
// Hello とデバッグ表示する
Print << U"Hello!";
}
// ボタンが押されたら
if (SimpleGUI::Button(U"Move the cat", Vec2(600, 20)))
{
// 猫の座標を画面内のランダムな位置に移動する
catPos = RandomVec2(Scene::Rect());
}
}
}
//
// = アドバイス =
// Debug ビルドではプログラムの最適化がオフになります。
// 実行速度が遅いと感じた場合は Release ビルドを試しましょう。
// アプリをリリースするときにも、Release ビルドにするのを忘れないように!
//
// 思ったように動作しない場合は「デバッグの開始」でプログラムを実行すると、
// 出力ウィンドウに詳細なログが表示されるので、エラーの原因を見つけやすくなります。
//
// = お役立ちリンク =
//
// OpenSiv3D リファレンス
// https://siv3d.github.io/ja-jp/
//
// チュートリアル
// https://siv3d.github.io/ja-jp/tutorial/basic/
//
// よくある間違い
// https://siv3d.github.io/ja-jp/articles/mistakes/
//
// サポートについて
// https://siv3d.github.io/ja-jp/support/support/
//
// Siv3D Slack (ユーザコミュニティ) への参加
// https://siv3d.github.io/ja-jp/community/community/
//
// 新機能の提案やバグの報告
// https://github.com/Siv3D/OpenSiv3D/issues
//
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <Graphics/Widgets/ArrowWidget.h>
#include <Graphics/Widgets/ConeWidget.h>
#include <Graphics/Widgets/CylinderWidget.h>
#include <Graphics/Widgets/DiskWidget.h>
#include <Graphics/Widgets/SphereWidget.h>
#include <Graphics/Widgets/WidgetFactory.h>
#include <Graphics/Widgets/Tests/WidgetTestingUtility.h>
using namespace SCIRun::Graphics::Datatypes;
using namespace SCIRun::Core::Geometry;
TEST(ArrowWidgetTest, CanCreateSingleArrowReal)
{
StubGeometryIDGenerator idGen;
auto rgf = boost::make_shared<RealGlyphFactory>();
WidgetFactory::setGlyphFactory(rgf);
ArrowWidget arrow({{idGen, "testArrow1"}, rgf},
{
{10.0, "", {0,1,2}, {{0,0,0}, {1,1,1}}, 10},
{1,1,0}, {2,2,0}, true, 2, 4
});
EXPECT_EQ(Point(16,16,0), arrow.position());
EXPECT_EQ("<dummyGeomId>testArrow10widget[1 1 0][2 2 0]0", arrow.name());
}
TEST(ArrowWidgetTest, CanCreateSingleArrowStubbed)
{
StubGeometryIDGenerator idGen;
auto sgf = boost::make_shared<StubGlyphFactory>();
WidgetFactory::setGlyphFactory(sgf);
ArrowWidget arrow({{idGen, "testArrow1"}, sgf},
{
{10.0, "", {0,1,2}, {{0,0,0}, {1,1,1}}, 10},
{1,1,0}, {2,2,0}, true, 2, 4
});
EXPECT_EQ(Point(16,16,0), arrow.position());
//arrow does not get name from factory--generates it in constructor.
EXPECT_EQ("<dummyGeomId>testArrow10widget[1 1 0][2 2 0]0", arrow.name());
}
TEST(ArrowWidgetTest, ArrowComponentsObserveEachOther)
{
StubGeometryIDGenerator idGen;
Point origin(0,0,0);
CommonWidgetParameters common
{
1.0, "red", origin,
{origin, Point(origin + Point{1,1,1})},
10
};
ArrowParameters arrowParams
{
common,
origin, Vector{1,1,1}, true, 2, 4
};
auto arrow = WidgetFactory::createArrowWidget(
{idGen, "testArrow1"},
arrowParams
);
ASSERT_TRUE(arrow != nullptr);
auto compositeArrow = boost::dynamic_pointer_cast<CompositeWidget>(arrow);
ASSERT_TRUE(compositeArrow != nullptr);
WidgetList internals(compositeArrow->subwidgetBegin(), compositeArrow->subwidgetEnd());
ASSERT_EQ(internals.size(), 4);
auto sphere = boost::dynamic_pointer_cast<SphereWidget>(internals[0]);
ASSERT_TRUE(sphere != nullptr);
EXPECT_EQ("__sphere__4", sphere->name());
EXPECT_EQ("<dummyGeomId>SphereWidget::ArrowWidget(0)(2)(4)", sphere->uniqueID());
auto shaft = boost::dynamic_pointer_cast<CylinderWidget>(internals[1]);
ASSERT_TRUE(shaft != nullptr);
EXPECT_EQ("__cylinder__5", shaft->name());
EXPECT_EQ("<dummyGeomId>CylinderWidget::ArrowWidget(1)(2)(4)", shaft->uniqueID());
auto cone = boost::dynamic_pointer_cast<ConeWidget>(internals[2]);
ASSERT_TRUE(cone != nullptr);
EXPECT_EQ("__cone__6", cone->name());
EXPECT_EQ("<dummyGeomId>ConeWidget::ArrowWidget(2)(2)(4)", cone->uniqueID());
auto disk = boost::dynamic_pointer_cast<DiskWidget>(internals[3]);
ASSERT_TRUE(disk != nullptr);
EXPECT_EQ("__disk__7", disk->name());
EXPECT_EQ("<dummyGeomId>DiskWidget::ArrowWidget(3)(2)(4)", disk->uniqueID());
int eventCounter = 0;
auto eventFunc = [&eventCounter](const std::string& id) { std::cout << "Translating: " << id << std::endl; eventCounter++; };
SimpleWidgetEvent transEvent{WidgetMovement::TRANSLATE, eventFunc};
// sphere takes translate events
sphere->propagateEvent(transEvent);
EXPECT_EQ(eventCounter, internals.size());
eventCounter = 0;
// shaft takes translate events too
shaft->propagateEvent(transEvent);
EXPECT_EQ(eventCounter, internals.size());
eventCounter = 0;
// cone takes rotate events
cone->propagateEvent({WidgetMovement::ROTATE, [&eventCounter](const std::string& id) { std::cout << "Rotating: " << id << std::endl; eventCounter++; }});
EXPECT_EQ(eventCounter, internals.size());
eventCounter = 0;
// disk takes scale events
disk->propagateEvent({WidgetMovement::SCALE, [&eventCounter](const std::string& id) { std::cout << "Scaling: " << id << std::endl; eventCounter++; }});
EXPECT_EQ(eventCounter, internals.size());
}
<commit_msg>Fix test<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <gtest/gtest.h>
#include <Graphics/Widgets/ArrowWidget.h>
#include <Graphics/Widgets/ConeWidget.h>
#include <Graphics/Widgets/CylinderWidget.h>
#include <Graphics/Widgets/DiskWidget.h>
#include <Graphics/Widgets/SphereWidget.h>
#include <Graphics/Widgets/WidgetFactory.h>
#include <Graphics/Widgets/Tests/WidgetTestingUtility.h>
using namespace SCIRun::Graphics::Datatypes;
using namespace SCIRun::Core::Geometry;
TEST(ArrowWidgetTest, CanCreateSingleArrowReal)
{
StubGeometryIDGenerator idGen;
auto rgf = boost::make_shared<RealGlyphFactory>();
WidgetFactory::setGlyphFactory(rgf);
ArrowWidget arrow({{idGen, "testArrow1"}, rgf},
{
{10.0, "", {0,1,2}, {{0,0,0}, {1,1,1}}, 10},
{1,1,0}, {2,2,0}, true, 2, 4
});
EXPECT_EQ(Point(16,16,0), arrow.position());
EXPECT_EQ("<dummyGeomId>testArrow10widget[1 1 0][2 2 0]0", arrow.name());
}
TEST(ArrowWidgetTest, CanCreateSingleArrowStubbed)
{
StubGeometryIDGenerator idGen;
auto sgf = boost::make_shared<StubGlyphFactory>();
WidgetFactory::setGlyphFactory(sgf);
ArrowWidget arrow({{idGen, "testArrow1"}, sgf},
{
{10.0, "", {0,1,2}, {{0,0,0}, {1,1,1}}, 10},
{1,1,0}, {2,2,0}, true, 2, 4
});
EXPECT_EQ(Point(16,16,0), arrow.position());
//arrow does not get name from factory--generates it in constructor.
EXPECT_EQ("<dummyGeomId>testArrow10widget[1 1 0][2 2 0]0", arrow.name());
}
TEST(ArrowWidgetTest, ArrowComponentsObserveEachOther)
{
StubGeometryIDGenerator idGen;
Point origin(0,0,0);
CommonWidgetParameters common
{
1.0, "red", origin,
{origin, Point(origin + Point{1,1,1})},
10
};
ArrowParameters arrowParams
{
common,
origin, Vector{1,1,1}, true, 2, 4
};
auto arrow = WidgetFactory::createArrowWidget(
{idGen, "testArrow1"},
arrowParams
);
ASSERT_TRUE(arrow != nullptr);
auto compositeArrow = boost::dynamic_pointer_cast<CompositeWidget>(arrow);
ASSERT_TRUE(compositeArrow != nullptr);
WidgetList internals(compositeArrow->subwidgetBegin(), compositeArrow->subwidgetEnd());
ASSERT_EQ(internals.size(), 4);
auto sphere = boost::dynamic_pointer_cast<SphereWidget>(internals[0]);
ASSERT_TRUE(sphere != nullptr);
EXPECT_EQ("__sphere__4", sphere->name());
EXPECT_EQ("<dummyGeomId>SphereWidget::ArrowWidget(0)(2)(4)0", sphere->uniqueID());
auto shaft = boost::dynamic_pointer_cast<CylinderWidget>(internals[1]);
ASSERT_TRUE(shaft != nullptr);
EXPECT_EQ("__cylinder__5", shaft->name());
EXPECT_EQ("<dummyGeomId>CylinderWidget::ArrowWidget(1)(2)(4)0", shaft->uniqueID());
auto cone = boost::dynamic_pointer_cast<ConeWidget>(internals[2]);
ASSERT_TRUE(cone != nullptr);
EXPECT_EQ("__cone__6", cone->name());
EXPECT_EQ("<dummyGeomId>ConeWidget::ArrowWidget(2)(2)(4)0", cone->uniqueID());
auto disk = boost::dynamic_pointer_cast<DiskWidget>(internals[3]);
ASSERT_TRUE(disk != nullptr);
EXPECT_EQ("__disk__7", disk->name());
EXPECT_EQ("<dummyGeomId>DiskWidget::ArrowWidget(3)(2)(4)0", disk->uniqueID());
int eventCounter = 0;
auto eventFunc = [&eventCounter](const std::string& id) { std::cout << "Translating: " << id << std::endl; eventCounter++; };
SimpleWidgetEvent transEvent{WidgetMovement::TRANSLATE, eventFunc};
// sphere takes translate events
sphere->propagateEvent(transEvent);
EXPECT_EQ(eventCounter, internals.size());
eventCounter = 0;
// shaft takes translate events too
shaft->propagateEvent(transEvent);
EXPECT_EQ(eventCounter, internals.size());
eventCounter = 0;
// cone takes rotate events
cone->propagateEvent({WidgetMovement::ROTATE, [&eventCounter](const std::string& id) { std::cout << "Rotating: " << id << std::endl; eventCounter++; }});
EXPECT_EQ(eventCounter, internals.size());
eventCounter = 0;
// disk takes scale events
disk->propagateEvent({WidgetMovement::SCALE, [&eventCounter](const std::string& id) { std::cout << "Scaling: " << id << std::endl; eventCounter++; }});
EXPECT_EQ(eventCounter, internals.size());
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS dba23c (1.45.18); FILE MERGED 2007/07/20 21:02:54 fs 1.45.18.1: #i79731# remove ROW_HEIGHT, it is already present as ROWHEIGHT<commit_after><|endoftext|> |
<commit_before>#include "JsonConfigParser.h"
#include "Poco/RegularExpression.h"
bool JsonConfigParser::_parse(const ofJson &config, const string &name, bool& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content.is_boolean()){
val = content;
return true;
}else {
ofLogError("JsonConfigParser::parse") << "Could not parse " << config << " to boolean.";
}
}
return false;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, std::string& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content.is_string()){
val = content;
return true;
}else {
ofLogError("JsonConfigParser::parse") << "Could not parse " << config << " to string.";
}
}
return false;
}
//source: https://gist.github.com/olmokramer/82ccce673f86db7cda5e
//complete check: (#(?:[\\da-f]{3}){1,2}|rgb\\((?:\d{1,3},\\s*){2}\\d{1,3}\\)|rgba\\((?:\\d{1,3},\\s*){3}\\d*\\.?\\d+\\)|hsl\\(\\d{1,3}(?:,\\s*\\d{1,3}%){2}\\)|hsla\\(\\d{1,3}(?:,\\s*\\d{1,3}%){2},\\s*\\d*\\.?\\d+\\))
bool JsonConfigParser::_parse(const ofJson &config, const string &name, ofColor& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content.is_string()){
std::string s_value = content;
//look for colors in hex format
std::string hexval = s_value;
std::transform(hexval.begin(), hexval.end(), hexval.begin(), ::tolower);
vector<string> matches = JsonConfigParser::getMatchedStrings(hexval, "#(?:[\\da-f]{3}){1,2}");
if(matches.size() > 0){
int x;
ofStringReplace(matches[0],"#","");
std::stringstream ss;
ss << std::hex << matches[0];
ss >> x;
val.set(ofColor::fromHex(x,255));
return true;
}
//look for colors in rgba format
matches.clear();
matches = JsonConfigParser::getMatchedStrings(s_value, "rgba\\((?:\\d{1,3},\\s*){3}\\d*\\.?\\d+\\)");
if(matches.size() > 0){
vector<string> vals = ofSplitString(ofSplitString(ofSplitString(s_value, "rgba(")[1],")")[0],",");
ofColor res(ofToFloat(vals[0]), ofToFloat(vals[1]), ofToFloat(vals[2]), ofToFloat(vals[3])*255);
val.set(res);
return true;
}
//loook for colors in rgb format
matches.clear();
matches = JsonConfigParser::getMatchedStrings(s_value, "rgb\\((?:\\d{1,3},\\s*){2}\\d{1,3}\\)");
if(matches.size() > 0){
vector<string> vals = ofSplitString(ofSplitString(ofSplitString(s_value, "rgb(")[1],")")[0],",");
ofColor res(ofToFloat(vals[0]), ofToFloat(vals[1]), ofToFloat(vals[2]));
val.set(res);
return true;
}
}/*else {
// look for ofColor format
if(ofColor* color = dynamic_cast<ofColor>(&content)){
val.set(color);
return true;
}
}*/
}
return false;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, ofPoint& val){
if (config.find("left") != config.end()) {
ofJson left = config["left"];
if(left.is_number()){
val.x = left;
}
}
if (config.find("top") != config.end()) {
ofJson top = config["top"];
if(top.is_number()){
val.y = top;
}
}
return true;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, ofRectangle& val){
if (config.find("left") != config.end()) {
ofJson left = config["left"];
if(left.is_number()){
val.x = left;
}
}
if (config.find("top") != config.end()) {
ofJson top = config["top"];
if(top.is_number()){
val.y = top;
}
}
if (config.find("width") != config.end()) {
ofJson width = config["width"];
if(width.is_number()){
val.width = width;
}
}
if (config.find("height") != config.end()) {
ofJson height = config["height"];
if(height.is_number()){
val.height = height;
}
}
return true;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, DOM::LayoutFloat& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content == "none"){
val = DOM::LayoutFloat::NONE;
return true;
}
if(content == "left"){
val = DOM::LayoutFloat::LEFT;
return true;
}
if(content == "right"){
val = DOM::LayoutFloat::RIGHT;
return true;
}
}
return false;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, DOM::LayoutPosition& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content == "static"){
val = DOM::LayoutPosition::STATIC;
return true;
}
if(content == "absolute"){
val = DOM::LayoutPosition::ABSOLUTE;
return true;
}
}
return false;
}
bool JsonConfigParser::parse(const ofJson &config, DOM::Element* val){
if(!config.is_null()){
if (config.find("left") != config.end()) {
ofJson left = config["left"];
if(left.is_number()){
val->setPosition(left, val->getPosition().y);
}
}
if (config.find("top") != config.end()) {
ofJson top = config["top"];
if(top.is_number()){
val->setPosition(val->getPosition().x, top);
}
}
// if (config.find("width") != config.end()) {
// ofJson width = config["width"];
// if(width.is_number()){
// val->setWidth(width);
// val->setPercentalWidth(false);
// }else {
// if(ofSplitString(width, "%").size() > 0){
// vector<std::string> _val = JsonConfigParser::getMatchedStrings(width, "(?:\\b|-)([1-9]{1,2}[0]?|100)\\b");
// if(_val.size() > 0){
// float res = ofToFloat(_val[0])/100.;
// val->setPercentalWidth(true, res);
// }
// }
// }
// }
// if (config.find("height") != config.end()) {
// ofJson height = config["height"];
// if(height.is_number()){
// val->setHeight(height);
// val->setPercentalHeight(false);
// }else {
// if(ofSplitString(height, "%").size() > 0){
// vector<std::string> _val = JsonConfigParser::getMatchedStrings(height, "(?:\\b|-)([1-9]{1,2}[0]?|100)\\b");
// if(_val.size() > 0){
// float res = ofToFloat(_val[0])/100.;
// val->setPercentalHeight(true, res);
// }
// }
// }
// }
}
return true;
}
vector < string > JsonConfigParser::getMatchedStrings (string contents, string regex ){
vector < string > results;
Poco::RegularExpression regEx(regex);
Poco::RegularExpression::Match match;
while(regEx.match(contents, match) != 0) {
// we get the sub string from the content
// and then trim the content so that we
// can continue to search
string foundStr = contents.substr(match.offset, match.length);
contents = contents.substr(match.offset + match.length);
results.push_back(foundStr);
}
return results;
}
std::string JsonConfigParser::colorToString(const ofColor& color){
std::stringstream strstr;
strstr << "rgba(" << (int)color.r << "," << (int)color.g << "," << (int)color.b << "," << 255./(float)color.a << ")";
return strstr.str();
}
<commit_msg>fixes color slider initial color<commit_after>#include "JsonConfigParser.h"
#include "Poco/RegularExpression.h"
bool JsonConfigParser::_parse(const ofJson &config, const string &name, bool& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content.is_boolean()){
val = content;
return true;
}else {
ofLogError("JsonConfigParser::parse") << "Could not parse " << config << " to boolean.";
}
}
return false;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, std::string& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content.is_string()){
val = content;
return true;
}else {
ofLogError("JsonConfigParser::parse") << "Could not parse " << config << " to string.";
}
}
return false;
}
//source: https://gist.github.com/olmokramer/82ccce673f86db7cda5e
//complete check: (#(?:[\\da-f]{3}){1,2}|rgb\\((?:\d{1,3},\\s*){2}\\d{1,3}\\)|rgba\\((?:\\d{1,3},\\s*){3}\\d*\\.?\\d+\\)|hsl\\(\\d{1,3}(?:,\\s*\\d{1,3}%){2}\\)|hsla\\(\\d{1,3}(?:,\\s*\\d{1,3}%){2},\\s*\\d*\\.?\\d+\\))
bool JsonConfigParser::_parse(const ofJson &config, const string &name, ofColor& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content.is_string()){
std::string s_value = content;
//look for colors in hex format
std::string hexval = s_value;
std::transform(hexval.begin(), hexval.end(), hexval.begin(), ::tolower);
vector<string> matches = JsonConfigParser::getMatchedStrings(hexval, "#(?:[\\da-f]{3}){1,2}");
if(matches.size() > 0){
int x;
ofStringReplace(matches[0],"#","");
std::stringstream ss;
ss << std::hex << matches[0];
ss >> x;
val.set(ofColor::fromHex(x,255));
return true;
}
//look for colors in rgba format
matches.clear();
matches = JsonConfigParser::getMatchedStrings(s_value, "rgba\\((?:\\d{1,3},\\s*){3}\\d*\\.?\\d+\\)");
if(matches.size() > 0){
vector<string> vals = ofSplitString(ofSplitString(ofSplitString(s_value, "rgba(")[1],")")[0],",");
ofColor res(ofToFloat(vals[0]), ofToFloat(vals[1]), ofToFloat(vals[2]), ofToFloat(vals[3])*255);
val.set(res);
return true;
}
//loook for colors in rgb format
matches.clear();
matches = JsonConfigParser::getMatchedStrings(s_value, "rgb\\((?:\\d{1,3},\\s*){2}\\d{1,3}\\)");
if(matches.size() > 0){
vector<string> vals = ofSplitString(ofSplitString(ofSplitString(s_value, "rgb(")[1],")")[0],",");
ofColor res(ofToFloat(vals[0]), ofToFloat(vals[1]), ofToFloat(vals[2]));
val.set(res);
return true;
}
}/*else {
// look for ofColor format
if(ofColor* color = dynamic_cast<ofColor>(&content)){
val.set(color);
return true;
}
}*/
}
return false;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, ofPoint& val){
if (config.find("left") != config.end()) {
ofJson left = config["left"];
if(left.is_number()){
val.x = left;
}
}
if (config.find("top") != config.end()) {
ofJson top = config["top"];
if(top.is_number()){
val.y = top;
}
}
return true;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, ofRectangle& val){
if (config.find("left") != config.end()) {
ofJson left = config["left"];
if(left.is_number()){
val.x = left;
}
}
if (config.find("top") != config.end()) {
ofJson top = config["top"];
if(top.is_number()){
val.y = top;
}
}
if (config.find("width") != config.end()) {
ofJson width = config["width"];
if(width.is_number()){
val.width = width;
}
}
if (config.find("height") != config.end()) {
ofJson height = config["height"];
if(height.is_number()){
val.height = height;
}
}
return true;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, DOM::LayoutFloat& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content == "none"){
val = DOM::LayoutFloat::NONE;
return true;
}
if(content == "left"){
val = DOM::LayoutFloat::LEFT;
return true;
}
if(content == "right"){
val = DOM::LayoutFloat::RIGHT;
return true;
}
}
return false;
}
bool JsonConfigParser::_parse(const ofJson &config, const string &name, DOM::LayoutPosition& val){
if (config.find(name) != config.end()) {
ofJson content = config[name];
if(content == "static"){
val = DOM::LayoutPosition::STATIC;
return true;
}
if(content == "absolute"){
val = DOM::LayoutPosition::ABSOLUTE;
return true;
}
}
return false;
}
bool JsonConfigParser::parse(const ofJson &config, DOM::Element* val){
if(!config.is_null()){
if (config.find("left") != config.end()) {
ofJson left = config["left"];
if(left.is_number()){
val->setPosition(left, val->getPosition().y);
}
}
if (config.find("top") != config.end()) {
ofJson top = config["top"];
if(top.is_number()){
val->setPosition(val->getPosition().x, top);
}
}
// if (config.find("width") != config.end()) {
// ofJson width = config["width"];
// if(width.is_number()){
// val->setWidth(width);
// val->setPercentalWidth(false);
// }else {
// if(ofSplitString(width, "%").size() > 0){
// vector<std::string> _val = JsonConfigParser::getMatchedStrings(width, "(?:\\b|-)([1-9]{1,2}[0]?|100)\\b");
// if(_val.size() > 0){
// float res = ofToFloat(_val[0])/100.;
// val->setPercentalWidth(true, res);
// }
// }
// }
// }
// if (config.find("height") != config.end()) {
// ofJson height = config["height"];
// if(height.is_number()){
// val->setHeight(height);
// val->setPercentalHeight(false);
// }else {
// if(ofSplitString(height, "%").size() > 0){
// vector<std::string> _val = JsonConfigParser::getMatchedStrings(height, "(?:\\b|-)([1-9]{1,2}[0]?|100)\\b");
// if(_val.size() > 0){
// float res = ofToFloat(_val[0])/100.;
// val->setPercentalHeight(true, res);
// }
// }
// }
// }
}
return true;
}
vector < string > JsonConfigParser::getMatchedStrings (string contents, string regex ){
vector < string > results;
Poco::RegularExpression regEx(regex);
Poco::RegularExpression::Match match;
while(regEx.match(contents, match) != 0) {
// we get the sub string from the content
// and then trim the content so that we
// can continue to search
string foundStr = contents.substr(match.offset, match.length);
contents = contents.substr(match.offset + match.length);
results.push_back(foundStr);
}
return results;
}
std::string JsonConfigParser::colorToString(const ofColor& color){
std::stringstream strstr;
strstr << "rgba(" << (int)color.r << "," << (int)color.g << "," << (int)color.b << "," << ((float)color.a)/255. << ")";
return strstr.str();
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Implements C wrappers around the CUDA library for easy linking in ORC jit.
// Also adds some debugging helpers that are helpful when writing MLIR code to
// run on GPUs.
#include <cassert>
#include <numeric>
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/ExecutionEngine/CRunnerUtils.h" // from @llvm-project
#if GOOGLE_CUDA
#include "third_party/gpus/cuda/include/cuda.h"
#define CUDA_REPORT_IF_ERROR(expr) \
[](CUresult result) { \
if (!result) \
return; \
const char *name = nullptr; \
cuGetErrorName(result, &name); \
if (!name) \
name = "<unknown>"; \
llvm::errs() << "'" << #expr << "' failed with '" << name << "'\n"; \
}(expr)
extern "C" CUmodule mgpuModuleLoad(void *data) {
CUmodule module = nullptr;
CUDA_REPORT_IF_ERROR(cuModuleLoadData(&module, data));
return module;
}
extern "C" CUfunction mgpuModuleGetFunction(CUmodule module, const char *name) {
CUfunction function = nullptr;
CUDA_REPORT_IF_ERROR(cuModuleGetFunction(&function, module, name));
return function;
}
// The wrapper uses intptr_t instead of CUDA's unsigned int to match
// the type of MLIR's index type. This avoids the need for casts in the
// generated MLIR code.
extern "C" void mgpuLaunchKernel(CUfunction function, intptr_t gridX,
intptr_t gridY, intptr_t gridZ,
intptr_t blockX, intptr_t blockY,
intptr_t blockZ, int32_t smem, CUstream stream,
void **params, void **extra) {
CUDA_REPORT_IF_ERROR(cuLaunchKernel(function, gridX, gridY, gridZ, blockX,
blockY, blockZ, smem, stream, params,
extra));
}
extern "C" CUstream mgpuStreamCreate() {
CUstream stream = nullptr;
CUDA_REPORT_IF_ERROR(cuStreamCreate(&stream, CU_STREAM_NON_BLOCKING));
return stream;
}
extern "C" void mgpuStreamSynchronize(CUstream stream) {
CUDA_REPORT_IF_ERROR(cuStreamSynchronize(stream));
}
/// Helper functions for writing mlir example code
// Allows to register byte array with the CUDA runtime. Helpful until we have
// transfer functions implemented.
extern "C" void mgpuMemHostRegister(void *ptr, uint64_t sizeBytes) {
CUDA_REPORT_IF_ERROR(cuMemHostRegister(ptr, sizeBytes, /*flags=*/0));
}
// Allows to register a MemRef with the CUDA runtime. Helpful until we have
// transfer functions implemented.
extern "C" void
mgpuMemHostRegisterMemRef(int64_t rank, StridedMemRefType<char, 1> *descriptor,
int64_t elementSizeBytes) {
llvm::SmallVector<int64_t, 4> denseStrides(rank);
llvm::ArrayRef<int64_t> sizes(descriptor->sizes, rank);
llvm::ArrayRef<int64_t> strides(sizes.end(), rank);
std::partial_sum(sizes.rbegin(), sizes.rend(), denseStrides.rbegin(),
std::multiplies<int64_t>());
auto sizeBytes = denseStrides.front() * elementSizeBytes;
// Only densely packed tensors are currently supported.
std::rotate(denseStrides.begin(), denseStrides.begin() + 1,
denseStrides.end());
denseStrides.back() = 1;
assert(strides == llvm::makeArrayRef(denseStrides));
auto ptr = descriptor->data + descriptor->offset * elementSizeBytes;
mgpuMemHostRegister(ptr, sizeBytes);
}
#endif
<commit_msg>[KERNEL_GEN] Cache cuda stream to avoid OOM.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Implements C wrappers around the CUDA library for easy linking in ORC jit.
// Also adds some debugging helpers that are helpful when writing MLIR code to
// run on GPUs.
#include <cassert>
#include <numeric>
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/raw_ostream.h"
#include "mlir/ExecutionEngine/CRunnerUtils.h" // from @llvm-project
#if GOOGLE_CUDA
#include "third_party/gpus/cuda/include/cuda.h"
#define CUDA_REPORT_IF_ERROR(expr) \
[](CUresult result) { \
if (!result) \
return; \
const char *name = nullptr; \
cuGetErrorName(result, &name); \
if (!name) \
name = "<unknown>"; \
llvm::errs() << "'" << #expr << "' failed with '" << name << "'\n"; \
}(expr)
extern "C" CUmodule mgpuModuleLoad(void *data) {
CUmodule module = nullptr;
CUDA_REPORT_IF_ERROR(cuModuleLoadData(&module, data));
return module;
}
extern "C" CUfunction mgpuModuleGetFunction(CUmodule module, const char *name) {
CUfunction function = nullptr;
CUDA_REPORT_IF_ERROR(cuModuleGetFunction(&function, module, name));
return function;
}
// The wrapper uses intptr_t instead of CUDA's unsigned int to match
// the type of MLIR's index type. This avoids the need for casts in the
// generated MLIR code.
extern "C" void mgpuLaunchKernel(CUfunction function, intptr_t gridX,
intptr_t gridY, intptr_t gridZ,
intptr_t blockX, intptr_t blockY,
intptr_t blockZ, int32_t smem, CUstream stream,
void **params, void **extra) {
CUDA_REPORT_IF_ERROR(cuLaunchKernel(function, gridX, gridY, gridZ, blockX,
blockY, blockZ, smem, stream, params,
extra));
}
extern "C" CUstream mgpuStreamCreate() {
static CUstream stream = []() {
// TODO(b/170649852): This is neither thread-safe nor handles
// creation/descruction of one stream per context.
CUstream stream = nullptr;
CUDA_REPORT_IF_ERROR(cuStreamCreate(&stream, CU_STREAM_NON_BLOCKING));
return stream;
}();
return stream;
}
extern "C" void mgpuStreamSynchronize(CUstream stream) {
CUDA_REPORT_IF_ERROR(cuStreamSynchronize(stream));
}
/// Helper functions for writing mlir example code
// Allows to register byte array with the CUDA runtime. Helpful until we have
// transfer functions implemented.
extern "C" void mgpuMemHostRegister(void *ptr, uint64_t sizeBytes) {
CUDA_REPORT_IF_ERROR(cuMemHostRegister(ptr, sizeBytes, /*flags=*/0));
}
// Allows to register a MemRef with the CUDA runtime. Helpful until we have
// transfer functions implemented.
extern "C" void
mgpuMemHostRegisterMemRef(int64_t rank, StridedMemRefType<char, 1> *descriptor,
int64_t elementSizeBytes) {
llvm::SmallVector<int64_t, 4> denseStrides(rank);
llvm::ArrayRef<int64_t> sizes(descriptor->sizes, rank);
llvm::ArrayRef<int64_t> strides(sizes.end(), rank);
std::partial_sum(sizes.rbegin(), sizes.rend(), denseStrides.rbegin(),
std::multiplies<int64_t>());
auto sizeBytes = denseStrides.front() * elementSizeBytes;
// Only densely packed tensors are currently supported.
std::rotate(denseStrides.begin(), denseStrides.begin() + 1,
denseStrides.end());
denseStrides.back() = 1;
assert(strides == llvm::makeArrayRef(denseStrides));
auto ptr = descriptor->data + descriptor->offset * elementSizeBytes;
mgpuMemHostRegister(ptr, sizeBytes);
}
#endif
<|endoftext|> |
<commit_before><commit_msg>typedef for reducing code clutter and text alignment<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2017, CNRS-LAAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef PLANNING_CPP_VNS_INTERFACE_H
#define PLANNING_CPP_VNS_INTERFACE_H
#include <ctime>
#include "plan.hpp"
#include "../ext/json.hpp"
using json = nlohmann::json;
class LocalMove {
public:
/** Reference to the plan this move is created for. */
PlanPtr base_plan;
explicit LocalMove(PlanPtr base) : base_plan(base) {};
/** Cost that would result in applying the move. */
virtual double utility() = 0;
/** Total duration that would result in applying the move */
virtual double duration() = 0;
/** True if applying this move on the base plan results in a valid plan. */
virtual bool is_valid() = 0;
/** Applies the move on the inner plan */
void apply() {
apply_on(base_plan);
}
/** Creates a new Plan on which the move is applied */
PlanPtr apply_on_new() {
PlanPtr ret = make_shared<Plan>(*base_plan);
apply_on(ret);
return ret;
}
protected:
/** Internal method that applies the move on a given plan.
* This should not be used directly. Instead you should the apply/apply_on_new public methods. */
virtual void apply_on(PlanPtr target) = 0;
private:
/** NEVER ACCESS. This is only to make the plan visible in gdb which has problems with shared points. */
Plan* plan_raw = base_plan.get();
};
typedef shared_ptr<LocalMove> PLocalMove;
/** Interface for generating local move in local search.
*
* A neighborhood provides a single method get_move() that optionally generates a new move.
* It also contains several parameters, with defaults, that can be overriden by subclasses.*/
struct Neighborhood {
/** Generates a new move for the given plan.
* The optional might be empty if this neighborhood failed to generate a valid move.
*
* If the optional return is non-empty, local search will apply this move regardless of its cost.
* Hence subclasses should make sure the returned values contribute to the overall quality of the plan.
* */
virtual opt<PLocalMove> get_move(PlanPtr plan) = 0;
virtual std::string name() const = 0;
};
struct Shuffler {
public:
virtual void suffle(shared_ptr<Plan> plan) = 0;
};
struct SearchResult {
shared_ptr<Plan> init_plan;
shared_ptr<Plan> final_plan;
public:
vector<Plan> intermediate_plans;
SearchResult(Plan& init_plan)
: init_plan(shared_ptr<Plan>(new Plan(init_plan))),
final_plan(shared_ptr<Plan>())
{}
void set_final_plan(Plan& p) {
ASSERT(!final_plan)
final_plan.reset(new Plan(p));
metadata["plan"] = p.metadata();
}
Plan initial() const { return *init_plan; }
Plan final() const { return *final_plan; }
json metadata;
};
struct VariableNeighborhoodSearch {
/** Sequence of neighborhoods to be considered by VNS. */
vector<shared_ptr<Neighborhood>> neighborhoods;
shared_ptr<Shuffler> shuffler;
explicit VariableNeighborhoodSearch(vector<shared_ptr<Neighborhood>>& neighborhoods, shared_ptr<Shuffler> shuffler) :
neighborhoods(neighborhoods), shuffler(shuffler) {
ASSERT(neighborhoods.size() > 0);
}
/** Refines an initial plan with Variable Neighborhood Search.
*
* @param p: Initial plan.
* @param max_restarts: Number of allowed restarts (currently only 0 is supported).
* @param save_every: If >0, the Search result will contain snapshots of the search every N iterations.
* Warning: this is very heavy on memory usage.
* @param save_improvements: If set, the Search result will contain snapshots of every improvement in the plan.
* Warning: this is very heavy on memory usage.
* @return
*/
SearchResult search(Plan p, size_t max_restarts, size_t save_every=0, bool save_improvements=false) {
const clock_t search_start = clock();
auto seconds_since_start = [search_start]() { return (double (clock() - search_start)) / CLOCKS_PER_SEC; };
SearchResult result(p);
PlanPtr best_plan = make_shared<Plan>(p);
PlanPtr best_plan_for_restart = make_shared<Plan>(p);
// a list of tuples (t, u) where 't' is a time in seconds reliative to the start of search and 'u' is the value
// of the best utility found a 't'
std::vector<std::pair<double, double>> utility_history;
utility_history.push_back(std::pair<double, double>(seconds_since_start(), best_plan->utility()));
size_t current_iter = 0;
size_t num_restarts = 0;
vector<double> runtime_per_neighborhood(neighborhoods.size(), 0.0);
bool saved = false; /*True if an improvement was saved so save_every do not take an snapshot again*/
while(num_restarts <= max_restarts) {
// choose first neighborhood
size_t current_neighborhood = 0;
if(num_restarts > 0) {
std::cout << "Shuffling\n";
best_plan_for_restart = std::make_shared<Plan>(*best_plan);
shuffler->suffle(best_plan_for_restart);
if(save_improvements) {
// save plan even though its is probably not an improvement
result.intermediate_plans.push_back(*best_plan_for_restart);
}
}
while(current_neighborhood < neighborhoods.size()) {
// current neighborhood
shared_ptr<Neighborhood> neighborhood = neighborhoods[current_neighborhood];
// get move for current neighborhood
const clock_t start = clock();
const opt<PLocalMove> move = neighborhood->get_move(best_plan_for_restart);
const clock_t end = clock();
runtime_per_neighborhood[current_neighborhood] += double(end - start) / CLOCKS_PER_SEC;
if(move) {
// neighborhood generate a move, apply it
LocalMove& m = **move;
ASSERT(m.is_valid());
// apply the move on best_plan_for_restart
m.apply();
if(best_plan_for_restart->utility() < best_plan->utility()) {
best_plan = make_shared<Plan>(*best_plan_for_restart);
utility_history.emplace_back(std::pair<double, double>(seconds_since_start(), best_plan_for_restart->utility()));
}
printf("Improvement (lvl: %d): utility: %f -- duration: %f\n", (int)current_neighborhood,
best_plan_for_restart->utility(), best_plan_for_restart->duration());
if(save_improvements) {
result.intermediate_plans.push_back(*best_plan_for_restart);
saved = true;
}
// plan changed, go back to first neighborhood
current_neighborhood = 0;
} else {
// no move
current_neighborhood += 1;
}
if(!saved && save_every != 0 && (current_iter % save_every) == 0) {
result.intermediate_plans.push_back(*best_plan_for_restart);
}
saved = false;
current_iter += 1;
}
if(best_plan_for_restart->utility() < best_plan->utility()) {
best_plan = best_plan_for_restart;
}
// no neighborhood provides improvements, restart or exit.
num_restarts += 1;
}
result.set_final_plan(*best_plan);
// save neighborhoods metadata
result.metadata["neighborhoods"] = json::array();
for(size_t i=0; i<neighborhoods.size(); i++) {
json j;
auto& n = *neighborhoods[i];
j["name"] = std::to_string(i) + "-" + n.name();
j["runtime"] = runtime_per_neighborhood[i];
result.metadata["neighborhoods"].push_back(j);
}
result.metadata["utility_history"] = json::array();
for(auto time_utility : utility_history)
result.metadata["utility_history"].push_back(json::array({time_utility.first, time_utility.second}));
return result;
}
};
#endif //PLANNING_CPP_VNS_INTERFACE_H
<commit_msg>Log the number of shuffles done while planning<commit_after>/* Copyright (c) 2017, CNRS-LAAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef PLANNING_CPP_VNS_INTERFACE_H
#define PLANNING_CPP_VNS_INTERFACE_H
#include <ctime>
#include "plan.hpp"
#include "../ext/json.hpp"
using json = nlohmann::json;
class LocalMove {
public:
/** Reference to the plan this move is created for. */
PlanPtr base_plan;
explicit LocalMove(PlanPtr base) : base_plan(base) {};
/** Cost that would result in applying the move. */
virtual double utility() = 0;
/** Total duration that would result in applying the move */
virtual double duration() = 0;
/** True if applying this move on the base plan results in a valid plan. */
virtual bool is_valid() = 0;
/** Applies the move on the inner plan */
void apply() {
apply_on(base_plan);
}
/** Creates a new Plan on which the move is applied */
PlanPtr apply_on_new() {
PlanPtr ret = make_shared<Plan>(*base_plan);
apply_on(ret);
return ret;
}
protected:
/** Internal method that applies the move on a given plan.
* This should not be used directly. Instead you should the apply/apply_on_new public methods. */
virtual void apply_on(PlanPtr target) = 0;
private:
/** NEVER ACCESS. This is only to make the plan visible in gdb which has problems with shared points. */
Plan* plan_raw = base_plan.get();
};
typedef shared_ptr<LocalMove> PLocalMove;
/** Interface for generating local move in local search.
*
* A neighborhood provides a single method get_move() that optionally generates a new move.
* It also contains several parameters, with defaults, that can be overriden by subclasses.*/
struct Neighborhood {
/** Generates a new move for the given plan.
* The optional might be empty if this neighborhood failed to generate a valid move.
*
* If the optional return is non-empty, local search will apply this move regardless of its cost.
* Hence subclasses should make sure the returned values contribute to the overall quality of the plan.
* */
virtual opt<PLocalMove> get_move(PlanPtr plan) = 0;
virtual std::string name() const = 0;
};
struct Shuffler {
public:
virtual void suffle(shared_ptr<Plan> plan) = 0;
};
struct SearchResult {
shared_ptr<Plan> init_plan;
shared_ptr<Plan> final_plan;
public:
vector<Plan> intermediate_plans;
SearchResult(Plan& init_plan)
: init_plan(shared_ptr<Plan>(new Plan(init_plan))),
final_plan(shared_ptr<Plan>())
{}
void set_final_plan(Plan& p) {
ASSERT(!final_plan)
final_plan.reset(new Plan(p));
metadata["plan"] = p.metadata();
}
Plan initial() const { return *init_plan; }
Plan final() const { return *final_plan; }
json metadata;
};
struct VariableNeighborhoodSearch {
/** Sequence of neighborhoods to be considered by VNS. */
vector<shared_ptr<Neighborhood>> neighborhoods;
shared_ptr<Shuffler> shuffler;
explicit VariableNeighborhoodSearch(vector<shared_ptr<Neighborhood>>& neighborhoods, shared_ptr<Shuffler> shuffler) :
neighborhoods(neighborhoods), shuffler(shuffler) {
ASSERT(neighborhoods.size() > 0);
}
/** Refines an initial plan with Variable Neighborhood Search.
*
* @param p: Initial plan.
* @param max_restarts: Number of allowed restarts (currently only 0 is supported).
* @param save_every: If >0, the Search result will contain snapshots of the search every N iterations.
* Warning: this is very heavy on memory usage.
* @param save_improvements: If set, the Search result will contain snapshots of every improvement in the plan.
* Warning: this is very heavy on memory usage.
* @return
*/
SearchResult search(Plan p, size_t max_restarts, size_t save_every=0, bool save_improvements=false) {
const clock_t search_start = clock();
auto seconds_since_start = [search_start]() { return (double (clock() - search_start)) / CLOCKS_PER_SEC; };
SearchResult result(p);
PlanPtr best_plan = make_shared<Plan>(p);
PlanPtr best_plan_for_restart = make_shared<Plan>(p);
// a list of tuples (t, u) where 't' is a time in seconds reliative to the start of search and 'u' is the value
// of the best utility found a 't'
std::vector<std::pair<double, double>> utility_history;
utility_history.push_back(std::pair<double, double>(seconds_since_start(), best_plan->utility()));
size_t current_iter = 0;
size_t num_restarts = 0;
vector<double> runtime_per_neighborhood(neighborhoods.size(), 0.0);
bool saved = false; /*True if an improvement was saved so save_every do not take an snapshot again*/
while(num_restarts <= max_restarts) {
// choose first neighborhood
size_t current_neighborhood = 0;
if(num_restarts > 0) {
std::cout << "Shuffling " << num_restarts << " of " << max_restarts << std::endl;
best_plan_for_restart = std::make_shared<Plan>(*best_plan);
shuffler->suffle(best_plan_for_restart);
if(save_improvements) {
// save plan even though its is probably not an improvement
result.intermediate_plans.push_back(*best_plan_for_restart);
}
}
while(current_neighborhood < neighborhoods.size()) {
// current neighborhood
shared_ptr<Neighborhood> neighborhood = neighborhoods[current_neighborhood];
// get move for current neighborhood
const clock_t start = clock();
const opt<PLocalMove> move = neighborhood->get_move(best_plan_for_restart);
const clock_t end = clock();
runtime_per_neighborhood[current_neighborhood] += double(end - start) / CLOCKS_PER_SEC;
if(move) {
// neighborhood generate a move, apply it
LocalMove& m = **move;
ASSERT(m.is_valid());
// apply the move on best_plan_for_restart
m.apply();
if(best_plan_for_restart->utility() < best_plan->utility()) {
best_plan = make_shared<Plan>(*best_plan_for_restart);
utility_history.emplace_back(std::pair<double, double>(seconds_since_start(), best_plan_for_restart->utility()));
}
printf("Improvement (lvl: %d): utility: %f -- duration: %f\n", (int)current_neighborhood,
best_plan_for_restart->utility(), best_plan_for_restart->duration());
if(save_improvements) {
result.intermediate_plans.push_back(*best_plan_for_restart);
saved = true;
}
// plan changed, go back to first neighborhood
current_neighborhood = 0;
} else {
// no move
current_neighborhood += 1;
}
if(!saved && save_every != 0 && (current_iter % save_every) == 0) {
result.intermediate_plans.push_back(*best_plan_for_restart);
}
saved = false;
current_iter += 1;
}
if(best_plan_for_restart->utility() < best_plan->utility()) {
best_plan = best_plan_for_restart;
}
// no neighborhood provides improvements, restart or exit.
num_restarts += 1;
}
result.set_final_plan(*best_plan);
// save neighborhoods metadata
result.metadata["neighborhoods"] = json::array();
for(size_t i=0; i<neighborhoods.size(); i++) {
json j;
auto& n = *neighborhoods[i];
j["name"] = std::to_string(i) + "-" + n.name();
j["runtime"] = runtime_per_neighborhood[i];
result.metadata["neighborhoods"].push_back(j);
}
result.metadata["utility_history"] = json::array();
for(auto time_utility : utility_history)
result.metadata["utility_history"].push_back(json::array({time_utility.first, time_utility.second}));
return result;
}
};
#endif //PLANNING_CPP_VNS_INTERFACE_H
<|endoftext|> |
<commit_before>#include "coverageobject.h"
#include <QTest>
#include <QMetaObject>
#include <QDir>
#include <QString>
#include <QDebug>
#include <QtDebug>
#include <QLibrary>
#include <QtCore/QBuffer>
#include <Cutelyst/context.h>
#include "cutelyst_paths.h"
using namespace Cutelyst;
void CoverageObject::init()
{
initTest();
}
QString CoverageObject::generateTestName() const
{
QString test_name;
test_name+=QString::fromLatin1(metaObject()->className());
test_name+=QString::fromLatin1("/");
test_name+=QString::fromLatin1(QTest::currentTestFunction());
if (QTest::currentDataTag())
{
test_name+=QString::fromLatin1("/");
test_name+=QString::fromLatin1(QTest::currentDataTag());
}
return test_name;
}
void CoverageObject::saveCoverageData()
{
#ifdef __COVERAGESCANNER__
QString test_name;
test_name += generateTestName();
__coveragescanner_testname(test_name.toStdString().c_str());
if (QTest::currentTestFailed())
__coveragescanner_teststate("FAILED");
else
__coveragescanner_teststate("PASSED") ;
__coveragescanner_save();
__coveragescanner_testname("");
__coveragescanner_clear();
#endif
}
void CoverageObject::cleanup()
{
cleanupTest();
saveCoverageData();
}
TestEngine::TestEngine(const QVariantMap &opts, QObject *parent) : Engine(opts, parent)
{
}
int TestEngine::workerId() const
{
return 0;
}
int TestEngine::workerCore() const
{
return 0;
}
QByteArray TestEngine::createRequest(const QString &method, const QString &path, const QByteArray &query, const Headers &headers, QByteArray *body)
{
QBuffer buf(body);
buf.open(QBuffer::ReadOnly);
m_responseData = QByteArray();
processRequest(method,
path,
query,
QStringLiteral("HTTP/1.1"),
false,
QStringLiteral("192.168.0.5"),
QStringLiteral("192.168.0.10"),
3203,
QString(), // RemoteUser
headers,
QDateTime::currentMSecsSinceEpoch(),
&buf,
0);
return m_responseData;
}
qint64 TestEngine::doWrite(Context *c, const char *data, qint64 len, void *engineData)
{
Q_UNUSED(c)
Q_UNUSED(engineData)
m_responseData.append(data, len);
}
bool TestEngine::init()
{
return true;
}
<commit_msg>Fix build of tests<commit_after>#include "coverageobject.h"
#include <QTest>
#include <QMetaObject>
#include <QDir>
#include <QString>
#include <QDebug>
#include <QtDebug>
#include <QLibrary>
#include <QtCore/QBuffer>
#include <Cutelyst/context.h>
#include "cutelyst_paths.h"
using namespace Cutelyst;
void CoverageObject::init()
{
initTest();
}
QString CoverageObject::generateTestName() const
{
QString test_name;
test_name+=QString::fromLatin1(metaObject()->className());
test_name+=QString::fromLatin1("/");
test_name+=QString::fromLatin1(QTest::currentTestFunction());
if (QTest::currentDataTag())
{
test_name+=QString::fromLatin1("/");
test_name+=QString::fromLatin1(QTest::currentDataTag());
}
return test_name;
}
void CoverageObject::saveCoverageData()
{
#ifdef __COVERAGESCANNER__
QString test_name;
test_name += generateTestName();
__coveragescanner_testname(test_name.toStdString().c_str());
if (QTest::currentTestFailed())
__coveragescanner_teststate("FAILED");
else
__coveragescanner_teststate("PASSED") ;
__coveragescanner_save();
__coveragescanner_testname("");
__coveragescanner_clear();
#endif
}
void CoverageObject::cleanup()
{
cleanupTest();
saveCoverageData();
}
TestEngine::TestEngine(const QVariantMap &opts, QObject *parent) : Engine(opts, parent)
{
}
int TestEngine::workerId() const
{
return 0;
}
int TestEngine::workerCore() const
{
return 0;
}
QByteArray TestEngine::createRequest(const QString &method, const QString &path, const QByteArray &query, const Headers &headers, QByteArray *body)
{
QBuffer buf(body);
buf.open(QBuffer::ReadOnly);
m_responseData = QByteArray();
processRequest(method,
path,
query,
QStringLiteral("HTTP/1.1"),
false,
QStringLiteral("192.168.0.5"),
QStringLiteral("192.168.0.10"),
3203,
QString(), // RemoteUser
headers,
QDateTime::currentMSecsSinceEpoch(),
&buf,
0);
return m_responseData;
}
qint64 TestEngine::doWrite(Context *c, const char *data, qint64 len, void *engineData)
{
Q_UNUSED(c)
Q_UNUSED(engineData)
m_responseData.append(data, len);
return len;
}
bool TestEngine::init()
{
return true;
}
<|endoftext|> |
<commit_before>
#include "PipelineManager.h"
#include "tis_logging.h"
#include <ctime>
#include <cstring>
#include <algorithm>
#include <tis_utils.h>
using namespace tis_imaging;
PipelineManager::PipelineManager ()
: status(PIPELINE_UNDEFINED), filter_loader(), frame_count(0)
{
filter_loader.index_possible_filter();
filter_loader.open_possible_filter();
available_filter = filter_loader.get_all_filter();
}
PipelineManager::~PipelineManager ()
{
if (status == PIPELINE_PLAYING)
{
stop_playing();
}
available_filter.clear();
filter_pipeline.clear();
filter_properties.clear();
filter_loader.drop_all_filter();
}
std::vector<std::shared_ptr<Property>> PipelineManager::getFilterProperties ()
{
return filter_properties;
}
std::vector<VideoFormatDescription> PipelineManager::getAvailableVideoFormats () const
{
return available_output_formats;
}
bool PipelineManager::setVideoFormat(const VideoFormat& f)
{
this->format = f;
}
bool PipelineManager::setStatus (const PIPELINE_STATUS& s)
{
if (status == s)
return true;
this->status = s;
if (status == PIPELINE_PLAYING)
{
frame_count = 0;
second_count = time(0);
if (create_pipeline())
{
start_playing();
tis_log(TIS_LOG_INFO, "All pipeline elements set to PLAYING.");
}
else
{
status = PIPELINE_ERROR;
// TODO: error
return false;
}
}
else if (status == PIPELINE_STOPPED)
{
}
return true;
}
PIPELINE_STATUS PipelineManager::getStatus () const
{
return status;
}
bool PipelineManager::destroyPipeline ()
{
setStatus(PIPELINE_STOPPED);
source = nullptr;
sink = nullptr;
return true;
}
void PipelineManager::index_output_formats ()
{
if (available_input_formats.empty() || available_filter.empty())
{
return ;
}
uint32_t fourcc = 0;
auto dev_formats = [&fourcc] (const VideoFormatDescription& vfd)
{
tis_log(TIS_LOG_DEBUG,
"Testing %s against %s",
fourcc2description(fourcc),
fourcc2description(vfd.getFormatDescription().fourcc));
return vfd.getFormatDescription().fourcc == fourcc;
};
for (auto f : available_filter)
{
if (f->getDescription().type == FILTER_TYPE_CONVERSION)
{
auto output = f->getDescription().output_fourcc;
auto input = f->getDescription().input_fourcc;
bool match = false;
for (const uint32_t& fi : input)
{
fourcc = fi;
auto format_match = std::find_if (available_input_formats.begin(),
available_input_formats.end(),
dev_formats);
if (format_match != available_input_formats.end())
{
for (uint32_t fcc : output)
{
auto desc = format_match->getFormatDescription();
auto rf = format_match-> getResolutionsFramesrates();
desc.fourcc = fcc;
memcpy(desc.description, fourcc2description(fcc), sizeof(desc.description));
VideoFormatDescription v (desc, rf);
available_output_formats.push_back (v);
}
}
}
if (match == false) // does not allow for input format
{
continue;
}
}
}
// to finalize iterate input formats and select those that shall be passed through
std::vector<uint32_t> pass_through = {FOURCC_Y800, FOURCC_Y16};
for (auto f : pass_through)
{
fourcc = f;
auto match = std::find_if(available_input_formats.begin(), available_input_formats.end(), dev_formats);
if (match != available_input_formats.end())
{
tis_log(TIS_LOG_ERROR, "Passing format through %s", fourcc2description(f));
available_output_formats.push_back(*match);
}
else
{
tis_log(TIS_LOG_DEBUG, "Device format '%s' will not be passed to user.", fourcc2description(f));
}
}
}
bool PipelineManager::setSource (std::shared_ptr<DeviceInterface> device)
{
if (status == PIPELINE_PLAYING || status == PIPELINE_PAUSED)
{
return false;
}
properties = device->getProperties();
available_input_formats = device->getAvailableVideoFormats();
distributeProperties();
this->source = std::make_shared<ImageSource>();
source->setSink(shared_from_this());
source->setDevice(device);
for (const auto& f : available_filter)
{
auto p = f->getFilterProperties();
if (!p.empty())
{
filter_properties.insert(filter_properties.end(), p.begin(), p.end());
}
}
index_output_formats();
return true;
}
std::shared_ptr<ImageSource> PipelineManager::getSource ()
{
return source;
}
bool PipelineManager::setSink (std::shared_ptr<SinkInterface> s)
{
if (status == PIPELINE_PLAYING || status == PIPELINE_PAUSED)
{
return false;
}
this->sink = s;
return true;
}
std::shared_ptr<SinkInterface> PipelineManager::getSink ()
{
return sink;
}
void PipelineManager::distributeProperties ()
{
for (auto& f : available_filter)
{
f->setDeviceProperties(properties);
}
}
bool isFilterApplicable (const uint32_t& fourcc,
const std::vector<uint32_t>& vec)
{
if (std::find(vec.begin(), vec.end(), fourcc) == vec.end())
{
return false;
}
return true;
}
void PipelineManager::create_input_format (const uint32_t& fourcc)
{
input_format = format;
input_format.setFourcc(fourcc);
}
std::vector<uint32_t> PipelineManager::getDeviceFourcc ()
{
// for easy usage we create a vector<fourcc> for avail. inputs
std::vector<uint32_t> device_fourcc;
for (const auto& v : available_input_formats)
{
tis_log(TIS_LOG_DEBUG,
"Found device fourcc '%s' - %d",
fourcc2description(v.getFormatDescription().fourcc),
v.getFormatDescription().fourcc);
device_fourcc.push_back(v.getFormatDescription().fourcc);
}
return device_fourcc;
}
bool PipelineManager::validate_pipeline ()
{
// check if pipeline is valid
if (source.get() == nullptr || sink.get() == nullptr)
{
// TODO: error
return false;
}
// check source format
auto in_format = source->getVideoFormat();
if (in_format != this->input_format)
{
tis_log(TIS_LOG_DEBUG,
"Video format in source does not match pipeline: '%s' != '%s'",
in_format.toString().c_str(),
input_format.toString().c_str());
return false;
}
VideoFormat in;
VideoFormat out;
for (auto f : filter_pipeline)
{
f->getVideoFormat(in, out);
if (in != in_format)
{
tis_log(TIS_LOG_ERROR,
"Ingoing video format for filter %s is not compatible with previous element. '%s' != '%s'",
f->getDescription().name.c_str(),
in_format.toString().c_str(),
in.toString().c_str());
// TODO: error
return false;
}
else
{
tis_log(TIS_LOG_DEBUG, "Filter %s connected to pipeline -- %s",
f->getDescription().name.c_str(),
out.toString().c_str());
// save output for next comparison
in_format = out;
}
}
if (in_format != this->format)
{
tis_log(TIS_LOG_ERROR, "Video format in sink does not match pipeline '%s' != '%s'",
in_format.toString().c_str(),
format.toString().c_str());
return false;
}
return true;
}
bool PipelineManager::create_conversion_pipeline ()
{
if (source.get() == nullptr || sink.get() == nullptr)
{
// TODO: error
return false;
}
auto device_fourcc = getDeviceFourcc();
for (auto f : available_filter)
{
std::string s = f->getDescription().name;
if (f->getDescription().type == FILTER_TYPE_CONVERSION)
{
if (isFilterApplicable(format.getFourcc(), f->getDescription().output_fourcc))
{
bool filter_valid = false;
uint32_t fourcc_to_use = 0;
for (const auto& cc : device_fourcc)
{
if (isFilterApplicable(cc, f->getDescription().input_fourcc))
{
filter_valid = true;
fourcc_to_use = cc;
break;
}
}
// set device format to use correct fourcc
create_input_format(fourcc_to_use);
if (filter_valid)
{
if (f->setVideoFormat(input_format, format))
{
tis_log(TIS_LOG_DEBUG,
"Added filter \"%s\" to pipeline",
s.c_str());
filter_pipeline.push_back(f);
}
else
{
tis_log(TIS_LOG_DEBUG,
"Filter %s did not accept format settings",
s.c_str());
}
}
else
{
tis_log(TIS_LOG_DEBUG, "Filter %s does not use the device output formats.", s.c_str());
}
}
else
{
tis_log(TIS_LOG_DEBUG, "Filter %s is not applicable", s.c_str());
}
}
}
return true;
}
bool PipelineManager::add_interpretation_filter ()
{
// if a valid pipeline can be created insert additional filter (e.g. autoexposure)
// interpretations should be done as early as possible in the pipeline
for (auto& f : available_filter)
{
if (f->getDescription().type == FILTER_TYPE_INTERPRET)
{
std::string s = f->getDescription().name;
// applicable to sink
bool all_formats = false;
if (f->getDescription().input_fourcc.size() == 1)
{
if (f->getDescription().input_fourcc.at(0) == 0)
{
all_formats = true;
}
}
if (all_formats ||isFilterApplicable(input_format.getFourcc(), f->getDescription().input_fourcc))
{
tis_log(TIS_LOG_DEBUG, "Adding filter '%s' after source", s.c_str());
f->setVideoFormat(input_format, input_format);
filter_pipeline.insert(filter_pipeline.begin(), f);
continue;
}
else
{
tis_log(TIS_LOG_DEBUG, "Filter '%s' not usable after source", s.c_str());
}
for (auto& filter : filter_pipeline)
{
if (f->setVideoFormat(input_format, input_format))
{
continue;
}
}
}
}
return true;
}
bool PipelineManager::allocate_conversion_buffer ()
{
for (int i = 0; i < 5; ++i)
{
image_buffer b = {};
b.pitch = format.getSize().width * img::getBitsPerPixel(format.getFourcc()) / 8;
b.length = b.pitch * format.getSize().height;
b.pData = (unsigned char*)malloc(b.length);
b.format.fourcc = format.getFourcc();
b.format.width = format.getSize().width;
b.format.height = format.getSize().height;
b.format.binning = format.getBinning();
b.format.framerate = format.getFramerate();
this->pipeline_buffer.push_back(std::make_shared<MemoryBuffer>(b));
}
return true;
}
bool PipelineManager::create_pipeline ()
{
if (source.get() == nullptr || sink.get() == nullptr)
{
// TODO: error
return false;
}
// assure everything is in a defined state
filter_pipeline.clear();
format.setFramerate(10.0);
format.setBinning(0);
if (!create_conversion_pipeline())
{
return false;
}
if (source->setVideoFormat(input_format))
{
tis_log(TIS_LOG_ERROR, "Unable to set video format in source.");
//return false;
}
if (!add_interpretation_filter())
{
return false;
}
if (!allocate_conversion_buffer())
{
return false;
}
if (!validate_pipeline())
{
return false;
}
tis_log(TIS_LOG_INFO, "Pipeline creation successful.");
std::string ppl = "source -> ";
for (const auto& f : filter_pipeline)
{
ppl += f->getDescription().name;
ppl += " -> ";
}
ppl += " sink";
tis_log(TIS_LOG_INFO, "%s" , ppl.c_str());
return true;
}
bool PipelineManager::start_playing ()
{
if (!sink->setStatus(PIPELINE_PLAYING))
{
tis_log(TIS_LOG_ERROR, "Sink refused to change to state PLAYING");
goto error;
}
for (auto& f : filter_pipeline)
{
if (!f->setStatus(PIPELINE_PLAYING))
{
tis_log(TIS_LOG_ERROR,
"Filter %s refused to change to state PLAYING",
f->getDescription().name.c_str());
goto error;
}
}
if (!source->setStatus(PIPELINE_PLAYING))
{
tis_log(TIS_LOG_ERROR, "Source refused to change to state PLAYING");
goto error;
}
status = PIPELINE_PLAYING;
return true;
error:
stop_playing();
return false;
}
bool PipelineManager::stop_playing ()
{
status = PIPELINE_STOPPED;
if (!source->setStatus(PIPELINE_STOPPED))
{
tis_log(TIS_LOG_ERROR, "Source refused to change to state STOP");
return false;
}
for (auto& f : filter_pipeline)
{
if (!f->setStatus(PIPELINE_STOPPED))
{
tis_log(TIS_LOG_ERROR,
"Filter %s refused to change to state STOP",
f->getDescription().name.c_str());
return false;
}
}
if (!sink->setStatus(PIPELINE_STOPPED))
{
tis_log(TIS_LOG_ERROR, "Sink refused to change to state STOP");
return false;
}
return true;
}
void PipelineManager::pushImage (std::shared_ptr<MemoryBuffer> buffer)
{
if (status == PIPELINE_STOPPED)
{
return;
}
frame_count++;
buffer->lock();
auto current_buffer = buffer;
for (auto& f : filter_pipeline)
{
if (f->getDescription().type == FILTER_TYPE_INTERPRET)
{
f->apply(current_buffer);
}
else if (f->getDescription().type == FILTER_TYPE_CONVERSION)
{
auto next_buffer = pipeline_buffer.at(0);
f->transform(*current_buffer, *next_buffer);
current_buffer = next_buffer;
}
}
if (sink != nullptr)
{
sink->pushImage(current_buffer);
}
else
{
tis_log(TIS_LOG_ERROR, "Sink is NULL");
}
buffer->unlock();
}
<commit_msg>Added FOURCC_UYVY to list of pass through formats<commit_after>
#include "PipelineManager.h"
#include "tis_logging.h"
#include <ctime>
#include <cstring>
#include <algorithm>
#include <tis_utils.h>
using namespace tis_imaging;
PipelineManager::PipelineManager ()
: status(PIPELINE_UNDEFINED), filter_loader(), frame_count(0)
{
filter_loader.index_possible_filter();
filter_loader.open_possible_filter();
available_filter = filter_loader.get_all_filter();
}
PipelineManager::~PipelineManager ()
{
if (status == PIPELINE_PLAYING)
{
stop_playing();
}
available_filter.clear();
filter_pipeline.clear();
filter_properties.clear();
filter_loader.drop_all_filter();
}
std::vector<std::shared_ptr<Property>> PipelineManager::getFilterProperties ()
{
return filter_properties;
}
std::vector<VideoFormatDescription> PipelineManager::getAvailableVideoFormats () const
{
return available_output_formats;
}
bool PipelineManager::setVideoFormat(const VideoFormat& f)
{
this->format = f;
}
bool PipelineManager::setStatus (const PIPELINE_STATUS& s)
{
if (status == s)
return true;
this->status = s;
if (status == PIPELINE_PLAYING)
{
frame_count = 0;
second_count = time(0);
if (create_pipeline())
{
start_playing();
tis_log(TIS_LOG_INFO, "All pipeline elements set to PLAYING.");
}
else
{
status = PIPELINE_ERROR;
// TODO: error
return false;
}
}
else if (status == PIPELINE_STOPPED)
{
}
return true;
}
PIPELINE_STATUS PipelineManager::getStatus () const
{
return status;
}
bool PipelineManager::destroyPipeline ()
{
setStatus(PIPELINE_STOPPED);
source = nullptr;
sink = nullptr;
return true;
}
void PipelineManager::index_output_formats ()
{
if (available_input_formats.empty() || available_filter.empty())
{
return ;
}
uint32_t fourcc = 0;
auto dev_formats = [&fourcc] (const VideoFormatDescription& vfd)
{
tis_log(TIS_LOG_DEBUG,
"Testing %s against %s",
fourcc2description(fourcc),
fourcc2description(vfd.getFormatDescription().fourcc));
return vfd.getFormatDescription().fourcc == fourcc;
};
for (auto f : available_filter)
{
if (f->getDescription().type == FILTER_TYPE_CONVERSION)
{
auto output = f->getDescription().output_fourcc;
auto input = f->getDescription().input_fourcc;
bool match = false;
for (const uint32_t& fi : input)
{
fourcc = fi;
auto format_match = std::find_if (available_input_formats.begin(),
available_input_formats.end(),
dev_formats);
if (format_match != available_input_formats.end())
{
for (uint32_t fcc : output)
{
auto desc = format_match->getFormatDescription();
auto rf = format_match-> getResolutionsFramesrates();
desc.fourcc = fcc;
memcpy(desc.description, fourcc2description(fcc), sizeof(desc.description));
VideoFormatDescription v (desc, rf);
available_output_formats.push_back (v);
}
}
}
if (match == false) // does not allow for input format
{
continue;
}
}
}
// to finalize iterate input formats and select those that shall be passed through
std::vector<uint32_t> pass_through = {FOURCC_Y800, FOURCC_Y16, FOURCC_UYVY};
for (auto f : pass_through)
{
fourcc = f;
auto match = std::find_if(available_input_formats.begin(), available_input_formats.end(), dev_formats);
if (match != available_input_formats.end())
{
tis_log(TIS_LOG_ERROR, "Passing format through %s", fourcc2description(f));
available_output_formats.push_back(*match);
}
else
{
tis_log(TIS_LOG_DEBUG, "Device format '%s' will not be passed to user.", fourcc2description(f));
}
}
}
bool PipelineManager::setSource (std::shared_ptr<DeviceInterface> device)
{
if (status == PIPELINE_PLAYING || status == PIPELINE_PAUSED)
{
return false;
}
properties = device->getProperties();
available_input_formats = device->getAvailableVideoFormats();
distributeProperties();
this->source = std::make_shared<ImageSource>();
source->setSink(shared_from_this());
source->setDevice(device);
for (const auto& f : available_filter)
{
auto p = f->getFilterProperties();
if (!p.empty())
{
filter_properties.insert(filter_properties.end(), p.begin(), p.end());
}
}
index_output_formats();
return true;
}
std::shared_ptr<ImageSource> PipelineManager::getSource ()
{
return source;
}
bool PipelineManager::setSink (std::shared_ptr<SinkInterface> s)
{
if (status == PIPELINE_PLAYING || status == PIPELINE_PAUSED)
{
return false;
}
this->sink = s;
return true;
}
std::shared_ptr<SinkInterface> PipelineManager::getSink ()
{
return sink;
}
void PipelineManager::distributeProperties ()
{
for (auto& f : available_filter)
{
f->setDeviceProperties(properties);
}
}
bool isFilterApplicable (const uint32_t& fourcc,
const std::vector<uint32_t>& vec)
{
if (std::find(vec.begin(), vec.end(), fourcc) == vec.end())
{
return false;
}
return true;
}
void PipelineManager::create_input_format (const uint32_t& fourcc)
{
input_format = format;
input_format.setFourcc(fourcc);
}
std::vector<uint32_t> PipelineManager::getDeviceFourcc ()
{
// for easy usage we create a vector<fourcc> for avail. inputs
std::vector<uint32_t> device_fourcc;
for (const auto& v : available_input_formats)
{
tis_log(TIS_LOG_DEBUG,
"Found device fourcc '%s' - %d",
fourcc2description(v.getFormatDescription().fourcc),
v.getFormatDescription().fourcc);
device_fourcc.push_back(v.getFormatDescription().fourcc);
}
return device_fourcc;
}
bool PipelineManager::validate_pipeline ()
{
// check if pipeline is valid
if (source.get() == nullptr || sink.get() == nullptr)
{
// TODO: error
return false;
}
// check source format
auto in_format = source->getVideoFormat();
if (in_format != this->input_format)
{
tis_log(TIS_LOG_DEBUG,
"Video format in source does not match pipeline: '%s' != '%s'",
in_format.toString().c_str(),
input_format.toString().c_str());
return false;
}
VideoFormat in;
VideoFormat out;
for (auto f : filter_pipeline)
{
f->getVideoFormat(in, out);
if (in != in_format)
{
tis_log(TIS_LOG_ERROR,
"Ingoing video format for filter %s is not compatible with previous element. '%s' != '%s'",
f->getDescription().name.c_str(),
in_format.toString().c_str(),
in.toString().c_str());
// TODO: error
return false;
}
else
{
tis_log(TIS_LOG_DEBUG, "Filter %s connected to pipeline -- %s",
f->getDescription().name.c_str(),
out.toString().c_str());
// save output for next comparison
in_format = out;
}
}
if (in_format != this->format)
{
tis_log(TIS_LOG_ERROR, "Video format in sink does not match pipeline '%s' != '%s'",
in_format.toString().c_str(),
format.toString().c_str());
return false;
}
return true;
}
bool PipelineManager::create_conversion_pipeline ()
{
if (source.get() == nullptr || sink.get() == nullptr)
{
// TODO: error
return false;
}
auto device_fourcc = getDeviceFourcc();
for (auto f : available_filter)
{
std::string s = f->getDescription().name;
if (f->getDescription().type == FILTER_TYPE_CONVERSION)
{
if (isFilterApplicable(format.getFourcc(), f->getDescription().output_fourcc))
{
bool filter_valid = false;
uint32_t fourcc_to_use = 0;
for (const auto& cc : device_fourcc)
{
if (isFilterApplicable(cc, f->getDescription().input_fourcc))
{
filter_valid = true;
fourcc_to_use = cc;
break;
}
}
// set device format to use correct fourcc
create_input_format(fourcc_to_use);
if (filter_valid)
{
if (f->setVideoFormat(input_format, format))
{
tis_log(TIS_LOG_DEBUG,
"Added filter \"%s\" to pipeline",
s.c_str());
filter_pipeline.push_back(f);
}
else
{
tis_log(TIS_LOG_DEBUG,
"Filter %s did not accept format settings",
s.c_str());
}
}
else
{
tis_log(TIS_LOG_DEBUG, "Filter %s does not use the device output formats.", s.c_str());
}
}
else
{
tis_log(TIS_LOG_DEBUG, "Filter %s is not applicable", s.c_str());
}
}
}
return true;
}
bool PipelineManager::add_interpretation_filter ()
{
// if a valid pipeline can be created insert additional filter (e.g. autoexposure)
// interpretations should be done as early as possible in the pipeline
for (auto& f : available_filter)
{
if (f->getDescription().type == FILTER_TYPE_INTERPRET)
{
std::string s = f->getDescription().name;
// applicable to sink
bool all_formats = false;
if (f->getDescription().input_fourcc.size() == 1)
{
if (f->getDescription().input_fourcc.at(0) == 0)
{
all_formats = true;
}
}
if (all_formats ||isFilterApplicable(input_format.getFourcc(), f->getDescription().input_fourcc))
{
tis_log(TIS_LOG_DEBUG, "Adding filter '%s' after source", s.c_str());
f->setVideoFormat(input_format, input_format);
filter_pipeline.insert(filter_pipeline.begin(), f);
continue;
}
else
{
tis_log(TIS_LOG_DEBUG, "Filter '%s' not usable after source", s.c_str());
}
for (auto& filter : filter_pipeline)
{
if (f->setVideoFormat(input_format, input_format))
{
continue;
}
}
}
}
return true;
}
bool PipelineManager::allocate_conversion_buffer ()
{
for (int i = 0; i < 5; ++i)
{
image_buffer b = {};
b.pitch = format.getSize().width * img::getBitsPerPixel(format.getFourcc()) / 8;
b.length = b.pitch * format.getSize().height;
b.pData = (unsigned char*)malloc(b.length);
b.format.fourcc = format.getFourcc();
b.format.width = format.getSize().width;
b.format.height = format.getSize().height;
b.format.binning = format.getBinning();
b.format.framerate = format.getFramerate();
this->pipeline_buffer.push_back(std::make_shared<MemoryBuffer>(b));
}
return true;
}
bool PipelineManager::create_pipeline ()
{
if (source.get() == nullptr || sink.get() == nullptr)
{
// TODO: error
return false;
}
// assure everything is in a defined state
filter_pipeline.clear();
format.setFramerate(10.0);
format.setBinning(0);
if (!create_conversion_pipeline())
{
return false;
}
if (source->setVideoFormat(input_format))
{
tis_log(TIS_LOG_ERROR, "Unable to set video format in source.");
//return false;
}
if (!add_interpretation_filter())
{
return false;
}
if (!allocate_conversion_buffer())
{
return false;
}
if (!validate_pipeline())
{
return false;
}
tis_log(TIS_LOG_INFO, "Pipeline creation successful.");
std::string ppl = "source -> ";
for (const auto& f : filter_pipeline)
{
ppl += f->getDescription().name;
ppl += " -> ";
}
ppl += " sink";
tis_log(TIS_LOG_INFO, "%s" , ppl.c_str());
return true;
}
bool PipelineManager::start_playing ()
{
if (!sink->setStatus(PIPELINE_PLAYING))
{
tis_log(TIS_LOG_ERROR, "Sink refused to change to state PLAYING");
goto error;
}
for (auto& f : filter_pipeline)
{
if (!f->setStatus(PIPELINE_PLAYING))
{
tis_log(TIS_LOG_ERROR,
"Filter %s refused to change to state PLAYING",
f->getDescription().name.c_str());
goto error;
}
}
if (!source->setStatus(PIPELINE_PLAYING))
{
tis_log(TIS_LOG_ERROR, "Source refused to change to state PLAYING");
goto error;
}
status = PIPELINE_PLAYING;
return true;
error:
stop_playing();
return false;
}
bool PipelineManager::stop_playing ()
{
status = PIPELINE_STOPPED;
if (!source->setStatus(PIPELINE_STOPPED))
{
tis_log(TIS_LOG_ERROR, "Source refused to change to state STOP");
return false;
}
for (auto& f : filter_pipeline)
{
if (!f->setStatus(PIPELINE_STOPPED))
{
tis_log(TIS_LOG_ERROR,
"Filter %s refused to change to state STOP",
f->getDescription().name.c_str());
return false;
}
}
if (!sink->setStatus(PIPELINE_STOPPED))
{
tis_log(TIS_LOG_ERROR, "Sink refused to change to state STOP");
return false;
}
return true;
}
void PipelineManager::pushImage (std::shared_ptr<MemoryBuffer> buffer)
{
if (status == PIPELINE_STOPPED)
{
return;
}
frame_count++;
buffer->lock();
auto current_buffer = buffer;
for (auto& f : filter_pipeline)
{
if (f->getDescription().type == FILTER_TYPE_INTERPRET)
{
f->apply(current_buffer);
}
else if (f->getDescription().type == FILTER_TYPE_CONVERSION)
{
auto next_buffer = pipeline_buffer.at(0);
f->transform(*current_buffer, *next_buffer);
current_buffer = next_buffer;
}
}
if (sink != nullptr)
{
sink->pushImage(current_buffer);
}
else
{
tis_log(TIS_LOG_ERROR, "Sink is NULL");
}
buffer->unlock();
}
<|endoftext|> |
<commit_before>#include "BacktraceTest.h"
#include "TestSuite.h"
REGISTER_TEST_CLASS(BacktraceTest)
#include "BackTrace.h"
#include "StackAddressLoader.h"
#include "DebugSymbolLoader.h"
#include <iostream>
using namespace std;
static const int STACK_DEPTH = 20;
#ifdef __GNUC__
// O asm é bom para esse teste porque impede o inline e a reodenacao
#define GET_CURRENT_ADDR(var) __asm__ volatile ("1: mov $1b, %0" : "=r" (var));
#else
#define GET_CURRENT_ADDR(var) var = (void*)~0;
#endif
void level5(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
*eff = Backtrace::getPlatformStackLoader().getStack(STACK_DEPTH, stack);
GET_CURRENT_ADDR(vstack[0]);
}
void level4(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
level5(eff, stack, vstack);
GET_CURRENT_ADDR(vstack[1]);
}
void level3(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
level4(eff, stack, vstack);
GET_CURRENT_ADDR(vstack[2]);
}
void level2(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
level3(eff, stack, vstack);
GET_CURRENT_ADDR(vstack[3]);
}
void level1(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
level2(eff, stack, vstack);
GET_CURRENT_ADDR(vstack[4]);
}
BacktraceTest::BacktraceTest() :
QObject(NULL)
{
Backtrace::initializeExecutablePath(qApp->applicationFilePath().toAscii().data());
}
void BacktraceTest::testBacktrace()
{
void* start[5];
Backtrace::StackFrame middle[STACK_DEPTH];
void* end[5];
int eff = 0;
start[0] = (void*)level5;
start[1] = (void*)level4;
start[2] = (void*)level3;
start[3] = (void*)level2;
start[4] = (void*)level1;
const char* names[] = {
"level5(int*, Backtrace::StackFrame*, void**)",
"level4(int*, Backtrace::StackFrame*, void**)",
"level3(int*, Backtrace::StackFrame*, void**)",
"level2(int*, Backtrace::StackFrame*, void**)",
"level1(int*, Backtrace::StackFrame*, void**)"
};
level1(&eff, middle, end);
for (int i = 0; i < eff; ++i) {
QVERIFY(middle[i].imageFile.empty() || QFile::exists(QString::fromStdString(middle[i].imageFile)));
}
eff = std::min(eff, 5) ;
for (int i = 0; i < eff; ++i) {
QVERIFY( start[i] <= middle[i].addr );
QVERIFY( middle[i].addr <= end[i] );
if (!middle[i].function.empty()) {
QCOMPARE(middle[i].function, names[i]);
}
}
}
void BacktraceTest::testBacktraceDebugInfo()
{
Backtrace::StackFrame middle[STACK_DEPTH];
void* end[5];
const char* names[] = {
"level5(int*, Backtrace::StackFrame*, void**)",
"level4(int*, Backtrace::StackFrame*, void**)",
"level3(int*, Backtrace::StackFrame*, void**)",
"level2(int*, Backtrace::StackFrame*, void**)",
"level1(int*, Backtrace::StackFrame*, void**)"
};
int lines[][2] = {
{20,24},
{26,30},
{32,36},
{39,42},
{44,48}
};
int eff = 0;
level1(&eff, middle, end);
eff = std::min(eff, 5);
Backtrace::getPlatformDebugSymbolLoader().findDebugInfo(middle, eff);
for (int i = 0; i < eff; ++i) {
QCOMPARE(middle[i].function, names[i]);
QString imageFile = QString::fromStdString(middle[i].imageFile);
QVERIFY(!imageFile.isEmpty() && QFile::exists(imageFile));
QVERIFY(imageFile.contains("unit_test"));
}
#ifdef DEBUG
// Esse loop pode falhar se nao houver simbolos de debug
for (int i = 0; i < eff; ++i) {
QString sourceFile = QString::fromStdString(middle[i].sourceFile);
QVERIFY(sourceFile.endsWith("unit_test/src/BacktraceTest.cpp"));
QVERIFY(middle[i].line >= lines[i][0]);
QVERIFY(middle[i].line <= lines[i][1]);
}
#endif
}
<commit_msg>Remocao de warnings<commit_after>#include "BacktraceTest.h"
#include "TestSuite.h"
REGISTER_TEST_CLASS(BacktraceTest)
#include "BackTrace.h"
#include "StackAddressLoader.h"
#include "DebugSymbolLoader.h"
#include <iostream>
using namespace std;
static const int STACK_DEPTH = 20;
#ifdef __GNUC__
// O asm é bom para esse teste porque impede o inline e a reodenacao
#define GET_CURRENT_ADDR(var) __asm__ volatile ("1: mov $1b, %0" : "=r" (var));
#else
#define GET_CURRENT_ADDR(var) var = (void*)~0;
#endif
void level5(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
*eff = Backtrace::getPlatformStackLoader().getStack(STACK_DEPTH, stack);
GET_CURRENT_ADDR(vstack[0]);
}
void level4(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
level5(eff, stack, vstack);
GET_CURRENT_ADDR(vstack[1]);
}
void level3(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
level4(eff, stack, vstack);
GET_CURRENT_ADDR(vstack[2]);
}
void level2(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
level3(eff, stack, vstack);
GET_CURRENT_ADDR(vstack[3]);
}
void level1(int* eff, Backtrace::StackFrame* stack, void** vstack)
{
level2(eff, stack, vstack);
GET_CURRENT_ADDR(vstack[4]);
}
BacktraceTest::BacktraceTest() :
QObject(NULL)
{
Backtrace::initializeExecutablePath(qApp->applicationFilePath().toAscii().data());
}
void BacktraceTest::testBacktrace()
{
void* start[5];
Backtrace::StackFrame middle[STACK_DEPTH];
void* end[5];
int eff = 0;
start[0] = (void*)level5;
start[1] = (void*)level4;
start[2] = (void*)level3;
start[3] = (void*)level2;
start[4] = (void*)level1;
const char* names[] = {
"level5(int*, Backtrace::StackFrame*, void**)",
"level4(int*, Backtrace::StackFrame*, void**)",
"level3(int*, Backtrace::StackFrame*, void**)",
"level2(int*, Backtrace::StackFrame*, void**)",
"level1(int*, Backtrace::StackFrame*, void**)"
};
level1(&eff, middle, end);
for (int i = 0; i < eff; ++i) {
QVERIFY(middle[i].imageFile.empty() || QFile::exists(QString::fromStdString(middle[i].imageFile)));
}
eff = std::min(eff, 5) ;
for (int i = 0; i < eff; ++i) {
QVERIFY( start[i] <= middle[i].addr );
QVERIFY( middle[i].addr <= end[i] );
if (!middle[i].function.empty()) {
QCOMPARE(middle[i].function, names[i]);
}
}
}
void BacktraceTest::testBacktraceDebugInfo()
{
Backtrace::StackFrame middle[STACK_DEPTH];
void* end[5];
const char* names[] = {
"level5(int*, Backtrace::StackFrame*, void**)",
"level4(int*, Backtrace::StackFrame*, void**)",
"level3(int*, Backtrace::StackFrame*, void**)",
"level2(int*, Backtrace::StackFrame*, void**)",
"level1(int*, Backtrace::StackFrame*, void**)"
};
// int lines[][2] = {
// {20,24},
// {26,30},
// {32,36},
// {39,42},
// {44,48}
// };
int eff = 0;
level1(&eff, middle, end);
eff = std::min(eff, 5);
Backtrace::getPlatformDebugSymbolLoader().findDebugInfo(middle, eff);
for (int i = 0; i < eff; ++i) {
QCOMPARE(middle[i].function, names[i]);
QString imageFile = QString::fromStdString(middle[i].imageFile);
QVERIFY(!imageFile.isEmpty() && QFile::exists(imageFile));
QVERIFY(imageFile.contains("unit_test"));
}
#ifdef DEBUG
// Esse loop pode falhar se nao houver simbolos de debug
for (int i = 0; i < eff; ++i) {
QString sourceFile = QString::fromStdString(middle[i].sourceFile);
QVERIFY(sourceFile.endsWith("unit_test/src/BacktraceTest.cpp"));
QVERIFY(middle[i].line >= lines[i][0]);
QVERIFY(middle[i].line <= lines[i][1]);
}
#endif
}
<|endoftext|> |
<commit_before>//===- llvm/unittest/ADT/StringMapMap.cpp - StringMap unit tests ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/StringMap.h"
using namespace llvm;
namespace llvm {
template <>
class StringMapEntryInitializer<uint32_t> {
public:
template <typename InitTy>
static void Initialize(StringMapEntry<uint32_t> &T, InitTy InitVal) {
T.second = InitVal;
}
};
}
namespace {
// Test fixture
class StringMapTest : public testing::Test {
protected:
StringMap<uint32_t> testMap;
static const char testKey[];
static const uint32_t testValue;
static const char* testKeyFirst;
static const char* testKeyLast;
static const std::string testKeyStr;
void assertEmptyMap() {
// Size tests
EXPECT_EQ(0u, testMap.size());
EXPECT_TRUE(testMap.empty());
// Iterator tests
EXPECT_TRUE(testMap.begin() == testMap.end());
// Lookup tests
EXPECT_EQ(0u, testMap.count(testKey));
EXPECT_EQ(0u, testMap.count(testKeyFirst, testKeyLast));
EXPECT_EQ(0u, testMap.count(testKeyStr));
EXPECT_TRUE(testMap.find(testKey) == testMap.end());
EXPECT_TRUE(testMap.find(testKeyFirst, testKeyLast) == testMap.end());
EXPECT_TRUE(testMap.find(testKeyStr) == testMap.end());
}
void assertSingleItemMap() {
// Size tests
EXPECT_EQ(1u, testMap.size());
EXPECT_FALSE(testMap.begin() == testMap.end());
EXPECT_FALSE(testMap.empty());
// Iterator tests
StringMap<uint32_t>::iterator it = testMap.begin();
EXPECT_STREQ(testKey, it->first());
EXPECT_EQ(testValue, it->second);
++it;
EXPECT_TRUE(it == testMap.end());
// Lookup tests
EXPECT_EQ(1u, testMap.count(testKey));
EXPECT_EQ(1u, testMap.count(testKeyFirst, testKeyLast));
EXPECT_EQ(1u, testMap.count(testKeyStr));
EXPECT_TRUE(testMap.find(testKey) == testMap.begin());
EXPECT_TRUE(testMap.find(testKeyFirst, testKeyLast) == testMap.begin());
EXPECT_TRUE(testMap.find(testKeyStr) == testMap.begin());
}
};
const char StringMapTest::testKey[] = "key";
const uint32_t StringMapTest::testValue = 1u;
const char* StringMapTest::testKeyFirst = testKey;
const char* StringMapTest::testKeyLast = testKey + sizeof(testKey) - 1;
const std::string StringMapTest::testKeyStr(testKey);
// Empty map tests
TEST_F(StringMapTest, EmptyMapTest) {
SCOPED_TRACE("EmptyMapTest");
assertEmptyMap();
}
// Constant map tests
TEST_F(StringMapTest, ConstEmptyMapTest) {
const StringMap<uint32_t>& constTestMap = testMap;
// Size tests
EXPECT_EQ(0u, constTestMap.size());
EXPECT_TRUE(constTestMap.empty());
// Iterator tests
EXPECT_TRUE(constTestMap.begin() == constTestMap.end());
// Lookup tests
EXPECT_EQ(0u, constTestMap.count(testKey));
EXPECT_EQ(0u, constTestMap.count(testKeyFirst, testKeyLast));
EXPECT_EQ(0u, constTestMap.count(testKeyStr));
EXPECT_TRUE(constTestMap.find(testKey) == constTestMap.end());
EXPECT_TRUE(constTestMap.find(testKeyFirst, testKeyLast) ==
constTestMap.end());
EXPECT_TRUE(constTestMap.find(testKeyStr) == constTestMap.end());
}
// A map with a single entry
TEST_F(StringMapTest, SingleEntryMapTest) {
SCOPED_TRACE("SingleEntryMapTest");
testMap[testKey] = testValue;
assertSingleItemMap();
}
// Test clear() method
TEST_F(StringMapTest, ClearTest) {
SCOPED_TRACE("ClearTest");
testMap[testKey] = testValue;
testMap.clear();
assertEmptyMap();
}
// Test erase(iterator) method
TEST_F(StringMapTest, EraseIteratorTest) {
SCOPED_TRACE("EraseIteratorTest");
testMap[testKey] = testValue;
testMap.erase(testMap.begin());
assertEmptyMap();
}
// Test erase(value) method
TEST_F(StringMapTest, EraseValueTest) {
SCOPED_TRACE("EraseValueTest");
testMap[testKey] = testValue;
testMap.erase(testKey);
assertEmptyMap();
}
// Test inserting two values and erasing one
TEST_F(StringMapTest, InsertAndEraseTest) {
SCOPED_TRACE("InsertAndEraseTest");
testMap[testKey] = testValue;
testMap["otherKey"] = 2;
testMap.erase("otherKey");
assertSingleItemMap();
}
// Test StringMapEntry::Create() method.
// DISABLED because this fails without a StringMapEntryInitializer, and
// I can't get it to compile with one.
TEST_F(StringMapTest, StringMapEntryTest) {
MallocAllocator A;
StringMap<uint32_t>::value_type* entry =
StringMap<uint32_t>::value_type::Create(
testKeyFirst, testKeyLast, A, 1u);
EXPECT_STREQ(testKey, entry->first());
EXPECT_EQ(1u, entry->second);
}
// Test insert() method
// DISABLED because this fails without a StringMapEntryInitializer, and
// I can't get it to compile with one.
TEST_F(StringMapTest, InsertTest) {
SCOPED_TRACE("InsertTest");
testMap.insert(
StringMap<uint32_t>::value_type::Create(
testKeyFirst, testKeyLast, testMap.getAllocator(), 1u));
assertSingleItemMap();
}
// A more complex iteration test
TEST_F(StringMapTest, IterationTest) {
bool visited[100];
// Insert 100 numbers into the map
for (int i = 0; i < 100; ++i) {
std::stringstream ss;
ss << "key_" << i;
testMap[ss.str()] = i;
visited[i] = false;
}
// Iterate over all numbers and mark each one found.
for (StringMap<uint32_t>::iterator it = testMap.begin();
it != testMap.end(); ++it) {
std::stringstream ss;
ss << "key_" << it->second;
ASSERT_STREQ(ss.str().c_str(), it->first());
visited[it->second] = true;
}
// Ensure every number was visited.
for (int i = 0; i < 100; ++i) {
ASSERT_TRUE(visited[i]) << "Entry #" << i << " was never visited";
}
}
}
<commit_msg>Some generic clean-ups. Also make the StringMapEntryInitializer specialization apply only to the tests that are actually testing it.<commit_after>//===- llvm/unittest/ADT/StringMapMap.cpp - StringMap unit tests ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/StringMap.h"
using namespace llvm;
namespace {
// Test fixture
class StringMapTest : public testing::Test {
protected:
StringMap<uint32_t> testMap;
static const char testKey[];
static const uint32_t testValue;
static const char* testKeyFirst;
static const char* testKeyLast;
static const std::string testKeyStr;
void assertEmptyMap() {
// Size tests
EXPECT_EQ(0u, testMap.size());
EXPECT_TRUE(testMap.empty());
// Iterator tests
EXPECT_TRUE(testMap.begin() == testMap.end());
// Lookup tests
EXPECT_EQ(0u, testMap.count(testKey));
EXPECT_EQ(0u, testMap.count(testKeyFirst, testKeyLast));
EXPECT_EQ(0u, testMap.count(testKeyStr));
EXPECT_TRUE(testMap.find(testKey) == testMap.end());
EXPECT_TRUE(testMap.find(testKeyFirst, testKeyLast) == testMap.end());
EXPECT_TRUE(testMap.find(testKeyStr) == testMap.end());
}
void assertSingleItemMap() {
// Size tests
EXPECT_EQ(1u, testMap.size());
EXPECT_FALSE(testMap.begin() == testMap.end());
EXPECT_FALSE(testMap.empty());
// Iterator tests
StringMap<uint32_t>::iterator it = testMap.begin();
EXPECT_STREQ(testKey, it->first());
EXPECT_EQ(testValue, it->second);
++it;
EXPECT_TRUE(it == testMap.end());
// Lookup tests
EXPECT_EQ(1u, testMap.count(testKey));
EXPECT_EQ(1u, testMap.count(testKeyFirst, testKeyLast));
EXPECT_EQ(1u, testMap.count(testKeyStr));
EXPECT_TRUE(testMap.find(testKey) == testMap.begin());
EXPECT_TRUE(testMap.find(testKeyFirst, testKeyLast) == testMap.begin());
EXPECT_TRUE(testMap.find(testKeyStr) == testMap.begin());
}
};
const char StringMapTest::testKey[] = "key";
const uint32_t StringMapTest::testValue = 1u;
const char* StringMapTest::testKeyFirst = testKey;
const char* StringMapTest::testKeyLast = testKey + sizeof(testKey) - 1;
const std::string StringMapTest::testKeyStr(testKey);
// Empty map tests.
TEST_F(StringMapTest, EmptyMapTest) {
SCOPED_TRACE("EmptyMapTest");
assertEmptyMap();
}
// Constant map tests.
TEST_F(StringMapTest, ConstEmptyMapTest) {
const StringMap<uint32_t>& constTestMap = testMap;
// Size tests
EXPECT_EQ(0u, constTestMap.size());
EXPECT_TRUE(constTestMap.empty());
// Iterator tests
EXPECT_TRUE(constTestMap.begin() == constTestMap.end());
// Lookup tests
EXPECT_EQ(0u, constTestMap.count(testKey));
EXPECT_EQ(0u, constTestMap.count(testKeyFirst, testKeyLast));
EXPECT_EQ(0u, constTestMap.count(testKeyStr));
EXPECT_TRUE(constTestMap.find(testKey) == constTestMap.end());
EXPECT_TRUE(constTestMap.find(testKeyFirst, testKeyLast) ==
constTestMap.end());
EXPECT_TRUE(constTestMap.find(testKeyStr) == constTestMap.end());
}
// A map with a single entry.
TEST_F(StringMapTest, SingleEntryMapTest) {
SCOPED_TRACE("SingleEntryMapTest");
testMap[testKey] = testValue;
assertSingleItemMap();
}
// Test clear() method.
TEST_F(StringMapTest, ClearTest) {
SCOPED_TRACE("ClearTest");
testMap[testKey] = testValue;
testMap.clear();
assertEmptyMap();
}
// Test erase(iterator) method.
TEST_F(StringMapTest, EraseIteratorTest) {
SCOPED_TRACE("EraseIteratorTest");
testMap[testKey] = testValue;
testMap.erase(testMap.begin());
assertEmptyMap();
}
// Test erase(value) method.
TEST_F(StringMapTest, EraseValueTest) {
SCOPED_TRACE("EraseValueTest");
testMap[testKey] = testValue;
testMap.erase(testKey);
assertEmptyMap();
}
// Test inserting two values and erasing one.
TEST_F(StringMapTest, InsertAndEraseTest) {
SCOPED_TRACE("InsertAndEraseTest");
testMap[testKey] = testValue;
testMap["otherKey"] = 2;
testMap.erase("otherKey");
assertSingleItemMap();
}
// A more complex iteration test.
TEST_F(StringMapTest, IterationTest) {
bool visited[100];
// Insert 100 numbers into the map
for (int i = 0; i < 100; ++i) {
std::stringstream ss;
ss << "key_" << i;
testMap[ss.str()] = i;
visited[i] = false;
}
// Iterate over all numbers and mark each one found.
for (StringMap<uint32_t>::iterator it = testMap.begin();
it != testMap.end(); ++it) {
std::stringstream ss;
ss << "key_" << it->second;
ASSERT_STREQ(ss.str().c_str(), it->first());
visited[it->second] = true;
}
// Ensure every number was visited.
for (int i = 0; i < 100; ++i) {
ASSERT_TRUE(visited[i]) << "Entry #" << i << " was never visited";
}
}
} // end anonymous namespace
namespace llvm {
template <>
class StringMapEntryInitializer<uint32_t> {
public:
template <typename InitTy>
static void Initialize(StringMapEntry<uint32_t> &T, InitTy InitVal) {
T.second = InitVal;
}
};
} // end llvm namespace
namespace {
// Test StringMapEntry::Create() method.
TEST_F(StringMapTest, StringMapEntryTest) {
StringMap<uint32_t>::value_type* entry =
StringMap<uint32_t>::value_type::Create(
testKeyFirst, testKeyLast, 1u);
EXPECT_STREQ(testKey, entry->first());
EXPECT_EQ(1u, entry->second);
}
// Test insert() method.
TEST_F(StringMapTest, InsertTest) {
SCOPED_TRACE("InsertTest");
testMap.insert(
StringMap<uint32_t>::value_type::Create(
testKeyFirst, testKeyLast, testMap.getAllocator(), 1u));
assertSingleItemMap();
}
} // end anonymous namespace
<|endoftext|> |
<commit_before>/*=========================================================================
Library: AnatomicAugmentedRealityProjector
Author: Maeliss Jallais
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "io_util.hpp"
#include "PointCloudInput.hpp"
#include "ProjectorWidget.hpp"
#include "FlyCapture2.h"
#include "itkImage.h"
#include "itkVector.h"
#include "itkGaussianMembershipFunction.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include <opencv2/imgproc/imgproc.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <time.h>
PointCloudInput::PointCloudInput( CameraInput *CamInput, ProjectorWidget *Projector, CalibrationData *Calib ) :
CamInput( CamInput ), Projector( Projector ), Calib( Calib )
{
}
PointCloudInput::~PointCloudInput()
{
}
PointCloud PointCloudInput::ComputePointCloud( int numrows )
{
CamInput->SetCameraTriggerDelay( .014 );
cv::Mat mat_color_ref = this->CamInput->GetImageFromBuffer();
double max_delay = .0119;
double delta = max_delay / numrows;
cv::Mat pointcloud = cv::Mat::zeros( numrows, mat_color_ref.cols, CV_32FC3 );
cv::Mat pointcloud_colors = cv::Mat( numrows, mat_color_ref.cols, CV_8UC3 );
/***********************3D Reconstruction of every lines****************************/
std::cout << "Start : 3D reconstruction of every line" << std::endl;
// imageTest is used to control which points have been used on the projector for the reconstruction
cv::Mat imageTest = cv::Mat::zeros( mat_color_ref.rows, mat_color_ref.cols, CV_8UC3 );
QString imagename;
cv::Mat crt_mat;
cv::Mat color_image = cv::Mat::zeros( mat_color_ref.rows, mat_color_ref.cols, CV_8UC3 );
this->CamInput->SetCameraTriggerDelay( 0 );
for( int depth_map_row = 0; depth_map_row < numrows; depth_map_row++ )
{
crt_mat = this->CamInput->GetImageFromBuffer();
double nextDelay = ( depth_map_row + 1 ) * delta;
// Begin changing the delay for the next image before processing the current image. There are silent errors
// If you take a picture too soon after changing the delay
this->CamInput->SetCameraTriggerDelay( nextDelay );
ComputePointCloudRow( &pointcloud, &pointcloud_colors, mat_color_ref, crt_mat, imageTest, color_image, nextDelay - delta, depth_map_row );
}
//imagename = QString( "C:\\Camera_Projector_Calibration\\Tests_publication\\color_image.png" );
//cv::imwrite( qPrintable( imagename ), color_image );
std::cout << "End : 3D reconstruction of every line" << std::endl;
return{ pointcloud, pointcloud_colors };
}
cv::Point3d PointCloudInput::approximate_ray_plane_intersection( const cv::Mat & T, const cv::Point3d & vc, const cv::Point3d & vp )
{
cv::Mat vcMat = cv::Mat( vc );
cv::Mat vpMat = cv::Mat( vp );
cv::Mat num = vpMat.t() * ( T );
cv::Mat denum = vpMat.t()*vcMat;
double lambda = num.at<double>( 0, 0 ) / denum.at<double>( 0, 0 );
cv::Point3d p = lambda*vc;
return p;
}
bool PointCloudInput::ComputePointCloudRow( cv::Mat *pointcloud, cv::Mat *pointcloud_colors,
cv::Mat mat_color_ref, cv::Mat mat_color, cv::Mat imageTest, cv::Mat color_image, double delay, int storage_row )
{
cv::Mat mat_BGR;
cv::Mat mat_gray;
std::vector<cv::Point2d> cam_points;
std::vector<cv::Point2d>::iterator it_cam_points;
cv::Point3d p;
cv::Mat inp1( 1, 1, CV_64FC2 );
cv::Mat outp1;
cv::Point3d u1;
cv::Point3d projectorNormal, cameraVector;
cv::Mat distortedProjectorPoints( 1, 2, CV_64FC2 );
cv::Mat undistortedProjectorPoints;
cv::Point3d projectorVector1;
cv::Point3d projectorVector2;
cv::Point3d w2, v2;
unsigned char sat_max;
int sum;
double average;
cv::Point2i point_max;
if( !mat_color_ref.data || mat_color_ref.type() != CV_8UC3 || !mat_color.data || mat_color.type() != CV_8UC3 )
{
std::cerr << "ERROR invalid cv::Mat data\n" << std::endl;
return false;
}
cv::subtract( mat_color, mat_color_ref, mat_BGR );
if( !mat_BGR.data || mat_BGR.type() != CV_8UC3 )
{
std::cerr << "ERROR invalid cv::Mat data\n" << std::endl;
return false;
}
//Convert the captured frame from BGR to gray
cv::cvtColor( mat_BGR, mat_gray, cv::COLOR_BGR2GRAY );
// Looking for the point with th maximum intensity for each column
for( int j = 0; j < mat_gray.cols; j++ )
{
sum = mat_gray.at< unsigned char >( 0, j ) + mat_gray.at< unsigned char >( 1, j ) + mat_gray.at< unsigned char >( 2, j );
sat_max = sum;
point_max = cv::Point2i( 0, 0 );
for( int i = 2; i < mat_gray.rows - 1; ++i )
{
sum = sum - mat_gray.at< unsigned char >( i - 2, j ) + mat_gray.at< unsigned char >( i + 1, j );
average = sum / 3;
if( average > sat_max && average > 27 )
{
point_max = cv::Point2i( j, i );
sat_max = average;
}
}
if( point_max != cv::Point2i( 0, 0 ) )
{
double average = 0;
double COM = 0;
for( int y = std::max( 0, point_max.y - 3 ); y <= std::min( point_max.y + 3, mat_gray.rows - 1 ); y++ )
{
average += mat_gray.at<unsigned char>( y, point_max.x );
COM += y * mat_gray.at<unsigned char>( y, point_max.x );
}
double y = COM / average;
cam_points.push_back( cv::Point2d( point_max.x, y ) );
imageTest.at<cv::Vec3b>( point_max ) = { 255, 0, 0 };
}
}
double normalizedDelay = delay / .0119;
double row = delayParam1 * normalizedDelay + delayParam2 * ( 1 - normalizedDelay );
std::cout << delayParam1 << " " << delayParam2 << " " << row << std::endl;
//double row = (delayParam1 - delay / delayParam2) *this->Projector->GetHeight();
// TODO : check wether the computed row is consistent or not
/*if( row <= 0 || row > this->Projector->GetHeight() )
{
std::cout << "The computed row is not valid. The line is skipped. Computed row = " << row << std::endl;
return false; // We skip the line
}*/
// Computation of the point used to define the plane of the projector
// to image camera coordinates
distortedProjectorPoints.at<cv::Vec2d>( 0, 0 ) = cv::Vec2d( this->Projector->GetWidth(), row );
distortedProjectorPoints.at<cv::Vec2d>( 0, 1 ) = cv::Vec2d( 0, row );
cv::undistortPoints( distortedProjectorPoints, undistortedProjectorPoints, this->Calib->Proj_K, cv::Mat() );
assert( undistortedProjectorPoints.type() == CV_64FC2 && undistortedProjectorPoints.rows == 1 && undistortedProjectorPoints.cols == 2 );
const cv::Vec2d & outvec2 = undistortedProjectorPoints.at<cv::Vec2d>( 0, 0 );
projectorVector1 = cv::Point3d( outvec2[ 0 ], outvec2[ 1 ], 1.0 );
const cv::Vec2d & outvec3 = undistortedProjectorPoints.at<cv::Vec2d>( 0, 1 );
projectorVector2 = cv::Point3d( outvec3[ 0 ], outvec3[ 1 ], 1.0 );
//find normal of laser plane via cross product of two vectors in plane
projectorNormal = cv::Point3d( cv::Mat( this->Calib->R*( cv::Mat( projectorVector1 ).cross( cv::Mat( projectorVector2 ) ) ) ) );
it_cam_points = cam_points.begin();
for( it_cam_points; it_cam_points != cam_points.end(); ++it_cam_points )
{
//to image camera coordinates
inp1.at<cv::Vec2d>( 0, 0 ) = cv::Vec2d( it_cam_points->x, it_cam_points->y );
cv::undistortPoints( inp1, outp1, this->Calib->Cam_K, this->Calib->Cam_kc );
assert( outp1.type() == CV_64FC2 && outp1.rows == 1 && outp1.cols == 1 );
const cv::Vec2d & outvec1 = outp1.at<cv::Vec2d>( 0, 0 );
cameraVector = cv::Point3d( outvec1[ 0 ], -outvec1[ 1 ], 1 );
p = approximate_ray_plane_intersection( this->Calib->T, cameraVector, projectorNormal );
if( sqrt( p.x*p.x + p.y * p.y + p.z * p.z ) < 400 )
{
cv::Vec3f & cloud_point = ( *pointcloud ).at<cv::Vec3f>( storage_row, ( *it_cam_points ).x );
cloud_point[ 0 ] = p.x;
cloud_point[ 1 ] = -p.y;
cloud_point[ 2 ] = p.z;
//std::cout << cloud_point << std::endl;
double B = mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y - 1, ( *it_cam_points ).x )[ 0 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x )[ 0 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y + 1, ( *it_cam_points ).x )[ 0 ];
double G = mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y - 1, ( *it_cam_points ).x )[ 1 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x )[ 1 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y + 1, ( *it_cam_points ).x )[ 1 ];
double R = mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y - 1, ( *it_cam_points ).x )[ 2 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x )[ 2 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y + 1, ( *it_cam_points ).x )[ 2 ];
unsigned char vec_B = ( B ) / 3;
unsigned char vec_G = ( G ) / 3;
unsigned char vec_R = ( R ) / 3;
cv::Vec3b & cloud_color = ( *pointcloud_colors ).at<cv::Vec3b>( storage_row, ( *it_cam_points ).x );
cloud_color[ 0 ] = vec_B;
cloud_color[ 1 ] = vec_G;
cloud_color[ 2 ] = vec_R;
color_image.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x ) = cv::Vec3b{ vec_B, vec_G, vec_R };
if( row < 780 && row > 395 )
{
imageTest.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x ) = { 0, 255, 0 };
}
else
{
imageTest.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x ) = { 255, 255, 255 };
}
}
}
return true;
}
<commit_msg>ENH: Add minimum delay for the trigger<commit_after>/*=========================================================================
Library: AnatomicAugmentedRealityProjector
Author: Maeliss Jallais
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "io_util.hpp"
#include "PointCloudInput.hpp"
#include "ProjectorWidget.hpp"
#include "FlyCapture2.h"
#include "itkImage.h"
#include "itkVector.h"
#include "itkGaussianMembershipFunction.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include <opencv2/imgproc/imgproc.hpp>
#include <fstream>
#include <iostream>
#include <map>
#include <time.h>
PointCloudInput::PointCloudInput( CameraInput *CamInput, ProjectorWidget *Projector, CalibrationData *Calib ) :
CamInput( CamInput ), Projector( Projector ), Calib( Calib )
{
}
PointCloudInput::~PointCloudInput()
{
}
PointCloud PointCloudInput::ComputePointCloud( int numrows )
{
CamInput->SetCameraTriggerDelay( .014 );
cv::Mat mat_color_ref = this->CamInput->GetImageFromBuffer();
double max_delay = .0119;
double min_delay = 0.0;
double delta = ( max_delay - min_delay ) / numrows;
cv::Mat pointcloud = cv::Mat::zeros( numrows, mat_color_ref.cols, CV_32FC3 );
cv::Mat pointcloud_colors = cv::Mat( numrows, mat_color_ref.cols, CV_8UC3 );
/***********************3D Reconstruction of every lines****************************/
std::cout << "Start : 3D reconstruction of every line" << std::endl;
// imageTest is used to control which points have been used on the projector for the reconstruction
cv::Mat imageTest = cv::Mat::zeros( mat_color_ref.rows, mat_color_ref.cols, CV_8UC3 );
QString imagename;
cv::Mat crt_mat;
cv::Mat color_image = cv::Mat::zeros( mat_color_ref.rows, mat_color_ref.cols, CV_8UC3 );
this->CamInput->SetCameraTriggerDelay( 0 );
for( int depth_map_row = 0; depth_map_row < numrows; depth_map_row++ )
{
crt_mat = this->CamInput->GetImageFromBuffer();
double nextDelay = ( depth_map_row + 1 ) * delta + min_delay;
// Begin changing the delay for the next image before processing the current image. There are silent errors
// If you take a picture too soon after changing the delay
this->CamInput->SetCameraTriggerDelay( nextDelay );
ComputePointCloudRow( &pointcloud, &pointcloud_colors, mat_color_ref, crt_mat, imageTest, color_image, nextDelay - delta, depth_map_row );
}
//imagename = QString( "C:\\Camera_Projector_Calibration\\Tests_publication\\color_image.png" );
//cv::imwrite( qPrintable( imagename ), color_image );
std::cout << "End : 3D reconstruction of every line" << std::endl;
return{ pointcloud, pointcloud_colors };
}
cv::Point3d PointCloudInput::approximate_ray_plane_intersection( const cv::Mat & T, const cv::Point3d & vc, const cv::Point3d & vp )
{
cv::Mat vcMat = cv::Mat( vc );
cv::Mat vpMat = cv::Mat( vp );
cv::Mat num = vpMat.t() * ( T );
cv::Mat denum = vpMat.t()*vcMat;
double lambda = num.at<double>( 0, 0 ) / denum.at<double>( 0, 0 );
cv::Point3d p = lambda*vc;
return p;
}
bool PointCloudInput::ComputePointCloudRow( cv::Mat *pointcloud, cv::Mat *pointcloud_colors,
cv::Mat mat_color_ref, cv::Mat mat_color, cv::Mat imageTest, cv::Mat color_image, double delay, int storage_row )
{
cv::Mat mat_BGR;
cv::Mat mat_gray;
std::vector<cv::Point2d> cam_points;
std::vector<cv::Point2d>::iterator it_cam_points;
cv::Point3d p;
cv::Mat inp1( 1, 1, CV_64FC2 );
cv::Mat outp1;
cv::Point3d u1;
cv::Point3d projectorNormal, cameraVector;
cv::Mat distortedProjectorPoints( 1, 2, CV_64FC2 );
cv::Mat undistortedProjectorPoints;
cv::Point3d projectorVector1;
cv::Point3d projectorVector2;
cv::Point3d w2, v2;
unsigned char sat_max;
int sum;
double average;
cv::Point2i point_max;
if( !mat_color_ref.data || mat_color_ref.type() != CV_8UC3 || !mat_color.data || mat_color.type() != CV_8UC3 )
{
std::cerr << "ERROR invalid cv::Mat data\n" << std::endl;
return false;
}
cv::subtract( mat_color, mat_color_ref, mat_BGR );
if( !mat_BGR.data || mat_BGR.type() != CV_8UC3 )
{
std::cerr << "ERROR invalid cv::Mat data\n" << std::endl;
return false;
}
//Convert the captured frame from BGR to gray
cv::cvtColor( mat_BGR, mat_gray, cv::COLOR_BGR2GRAY );
// Looking for the point with th maximum intensity for each column
for( int j = 0; j < mat_gray.cols; j++ )
{
sum = mat_gray.at< unsigned char >( 0, j ) + mat_gray.at< unsigned char >( 1, j ) + mat_gray.at< unsigned char >( 2, j );
sat_max = sum;
point_max = cv::Point2i( 0, 0 );
for( int i = 2; i < mat_gray.rows - 1; ++i )
{
sum = sum - mat_gray.at< unsigned char >( i - 2, j ) + mat_gray.at< unsigned char >( i + 1, j );
average = sum / 3;
if( average > sat_max && average > 27 )
{
point_max = cv::Point2i( j, i );
sat_max = average;
}
}
if( point_max != cv::Point2i( 0, 0 ) )
{
double average = 0;
double COM = 0;
for( int y = std::max( 0, point_max.y - 3 ); y <= std::min( point_max.y + 3, mat_gray.rows - 1 ); y++ )
{
average += mat_gray.at<unsigned char>( y, point_max.x );
COM += y * mat_gray.at<unsigned char>( y, point_max.x );
}
double y = COM / average;
cam_points.push_back( cv::Point2d( point_max.x, y ) );
imageTest.at<cv::Vec3b>( point_max ) = { 255, 0, 0 };
}
}
double normalizedDelay = delay / .0119;
double row = delayParam1 * normalizedDelay + delayParam2 * ( 1 - normalizedDelay );
std::cout << delayParam1 << " " << delayParam2 << " " << row << std::endl;
//double row = (delayParam1 - delay / delayParam2) *this->Projector->GetHeight();
// TODO : check wether the computed row is consistent or not
/*if( row <= 0 || row > this->Projector->GetHeight() )
{
std::cout << "The computed row is not valid. The line is skipped. Computed row = " << row << std::endl;
return false; // We skip the line
}*/
// Computation of the point used to define the plane of the projector
// to image camera coordinates
distortedProjectorPoints.at<cv::Vec2d>( 0, 0 ) = cv::Vec2d( this->Projector->GetWidth(), row );
distortedProjectorPoints.at<cv::Vec2d>( 0, 1 ) = cv::Vec2d( 0, row );
cv::undistortPoints( distortedProjectorPoints, undistortedProjectorPoints, this->Calib->Proj_K, cv::Mat() );
assert( undistortedProjectorPoints.type() == CV_64FC2 && undistortedProjectorPoints.rows == 1 && undistortedProjectorPoints.cols == 2 );
const cv::Vec2d & outvec2 = undistortedProjectorPoints.at<cv::Vec2d>( 0, 0 );
projectorVector1 = cv::Point3d( outvec2[ 0 ], outvec2[ 1 ], 1.0 );
const cv::Vec2d & outvec3 = undistortedProjectorPoints.at<cv::Vec2d>( 0, 1 );
projectorVector2 = cv::Point3d( outvec3[ 0 ], outvec3[ 1 ], 1.0 );
//find normal of laser plane via cross product of two vectors in plane
projectorNormal = cv::Point3d( cv::Mat( this->Calib->R*( cv::Mat( projectorVector1 ).cross( cv::Mat( projectorVector2 ) ) ) ) );
it_cam_points = cam_points.begin();
for( it_cam_points; it_cam_points != cam_points.end(); ++it_cam_points )
{
//to image camera coordinates
inp1.at<cv::Vec2d>( 0, 0 ) = cv::Vec2d( it_cam_points->x, it_cam_points->y );
cv::undistortPoints( inp1, outp1, this->Calib->Cam_K, this->Calib->Cam_kc );
assert( outp1.type() == CV_64FC2 && outp1.rows == 1 && outp1.cols == 1 );
const cv::Vec2d & outvec1 = outp1.at<cv::Vec2d>( 0, 0 );
cameraVector = cv::Point3d( outvec1[ 0 ], -outvec1[ 1 ], 1 );
p = approximate_ray_plane_intersection( this->Calib->T, cameraVector, projectorNormal );
if( sqrt( p.x*p.x + p.y * p.y + p.z * p.z ) < 400 )
{
cv::Vec3f & cloud_point = ( *pointcloud ).at<cv::Vec3f>( storage_row, ( *it_cam_points ).x );
cloud_point[ 0 ] = p.x;
cloud_point[ 1 ] = -p.y;
cloud_point[ 2 ] = p.z;
//std::cout << cloud_point << std::endl;
double B = mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y - 1, ( *it_cam_points ).x )[ 0 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x )[ 0 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y + 1, ( *it_cam_points ).x )[ 0 ];
double G = mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y - 1, ( *it_cam_points ).x )[ 1 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x )[ 1 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y + 1, ( *it_cam_points ).x )[ 1 ];
double R = mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y - 1, ( *it_cam_points ).x )[ 2 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x )[ 2 ] + mat_BGR.at<cv::Vec3b>( ( *it_cam_points ).y + 1, ( *it_cam_points ).x )[ 2 ];
unsigned char vec_B = ( B ) / 3;
unsigned char vec_G = ( G ) / 3;
unsigned char vec_R = ( R ) / 3;
cv::Vec3b & cloud_color = ( *pointcloud_colors ).at<cv::Vec3b>( storage_row, ( *it_cam_points ).x );
cloud_color[ 0 ] = vec_B;
cloud_color[ 1 ] = vec_G;
cloud_color[ 2 ] = vec_R;
color_image.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x ) = cv::Vec3b{ vec_B, vec_G, vec_R };
if( row < 780 && row > 395 )
{
imageTest.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x ) = { 0, 255, 0 };
}
else
{
imageTest.at<cv::Vec3b>( ( *it_cam_points ).y, ( *it_cam_points ).x ) = { 255, 255, 255 };
}
}
}
return true;
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/config.h>
#include <cassert>
#include <utility>
#include <GL/glew.h>
#include <visionaray/cpu_buffer_rt.h>
#if VSNRAY_HAVE_CUDA
#include <visionaray/gpu_buffer_rt.h>
#include <visionaray/pixel_unpack_buffer_rt.h>
#endif
#include "host_device_rt.h"
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// Private implementation
//
struct host_device_rt::impl
{
// CPU or GPU rendering
mode_type mode;
// If true, render target uses double buffering
bool double_buffering;
// If true, use PBO, otherwise copy over host
bool direct_rendering;
// Framebuffer color space, either RGB or SRGB
color_space_type color_space;
// Host render target
cpu_buffer_rt<PF_RGBA8, PF_UNSPECIFIED, PF_RGBA32F> host_rt[2];
#if VSNRAY_HAVE_CUDA
// Device render target, uses PBO
pixel_unpack_buffer_rt<PF_RGBA8, PF_UNSPECIFIED, PF_RGBA32F> direct_rt[2];
// Device render target, copy pixels over host
gpu_buffer_rt<PF_RGBA8, PF_UNSPECIFIED, PF_RGBA32F> indirect_rt[2];
#endif
// Index of front and back buffer, either 0 or 1
bool buffer_index[2];
};
//-------------------------------------------------------------------------------------------------
// host_device_rt
//
host_device_rt::host_device_rt(
mode_type mode,
bool double_buffering,
bool direct_rendering,
color_space_type color_space
)
: impl_(new impl)
{
impl_->mode = mode;
set_double_buffering(double_buffering);
impl_->direct_rendering = direct_rendering;
impl_->color_space = color_space;
}
host_device_rt::~host_device_rt()
{
}
host_device_rt::mode_type& host_device_rt::mode()
{
return impl_->mode;
}
host_device_rt::mode_type const& host_device_rt::mode() const
{
return impl_->mode;
}
void host_device_rt::set_double_buffering(bool double_buffering)
{
impl_->double_buffering = double_buffering;
if (impl_->double_buffering)
{
impl_->buffer_index[0] = 0;
impl_->buffer_index[1] = 1;
}
else
{
// Both indices the same, so when we swap buffers, in
// the single buffering case nothing gets ever swapped
impl_->buffer_index[0] = 0;
impl_->buffer_index[1] = 0;
}
}
bool host_device_rt::get_double_buffering() const
{
return impl_->double_buffering;
}
bool& host_device_rt::direct_rendering()
{
return impl_->direct_rendering;
}
bool const& host_device_rt::direct_rendering() const
{
return impl_->direct_rendering;
}
host_device_rt::color_space_type& host_device_rt::color_space()
{
return impl_->color_space;
}
host_device_rt::color_space_type const& host_device_rt::color_space() const
{
return impl_->color_space;
}
void host_device_rt::swap_buffers()
{
std::swap(impl_->buffer_index[Front], impl_->buffer_index[Back]);
}
host_device_rt::color_type const* host_device_rt::color(buffer buf) const
{
return impl_->host_rt[impl_->buffer_index[buf]].color();
}
host_device_rt::ref_type host_device_rt::ref(buffer buf)
{
if (impl_->mode == CPU)
{
return impl_->host_rt[impl_->buffer_index[buf]].ref();
}
else
{
#if VSNRAY_HAVE_CUDA
if (impl_->direct_rendering)
{
return impl_->direct_rt[impl_->buffer_index[buf]].ref();
}
else
{
return impl_->indirect_rt[impl_->buffer_index[buf]].ref();
}
#else
assert(0);
return {};
#endif
}
}
void host_device_rt::clear(vec4 const& color, buffer buf)
{
impl_->host_rt[impl_->buffer_index[buf]].clear_color_buffer(color);
impl_->host_rt[impl_->buffer_index[buf]].clear_accum_buffer(color);
#if VSNRAY_HAVE_CUDA
if (impl_->direct_rendering)
{
impl_->direct_rt[impl_->buffer_index[buf]].clear_color_buffer(color);
}
else
{
impl_->indirect_rt[impl_->buffer_index[buf]].clear_color_buffer(color);
}
#endif
}
void host_device_rt::begin_frame(buffer buf)
{
if (impl_->mode == CPU)
{
impl_->host_rt[impl_->buffer_index[buf]].begin_frame();
}
#if VSNRAY_HAVE_CUDA
else
{
if (impl_->direct_rendering)
{
impl_->direct_rt[impl_->buffer_index[buf]].begin_frame();
}
else
{
impl_->indirect_rt[impl_->buffer_index[buf]].begin_frame();
}
}
#endif
}
void host_device_rt::end_frame(buffer buf)
{
if (impl_->mode == CPU)
{
impl_->host_rt[impl_->buffer_index[buf]].end_frame();
}
#if VSNRAY_HAVE_CUDA
else
{
if (impl_->direct_rendering)
{
impl_->direct_rt[impl_->buffer_index[buf]].end_frame();
}
else
{
impl_->indirect_rt[impl_->buffer_index[buf]].end_frame();
}
}
#endif
}
void host_device_rt::resize(int w, int h)
{
render_target::resize(w, h);
int num_buffers = impl_->double_buffering ? 2 : 1;
for (int buf = 0; buf < num_buffers; ++buf)
{
impl_->host_rt[buf].resize(w, h);
#if VSNRAY_HAVE_CUDA
if (impl_->direct_rendering)
{
impl_->direct_rt[buf].resize(w, h);
}
else
{
impl_->indirect_rt[buf].resize(w, h);
}
#endif
}
}
void host_device_rt::display_color_buffer(buffer buf) const
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Store OpenGL state
GLboolean prev_srgb_enabled = glIsEnabled(GL_FRAMEBUFFER_SRGB);
if (impl_->color_space == SRGB)
{
glEnable(GL_FRAMEBUFFER_SRGB);
}
else
{
glDisable(GL_FRAMEBUFFER_SRGB);
}
if (impl_->mode == CPU)
{
impl_->host_rt[impl_->buffer_index[buf]].display_color_buffer();
}
#if VSNRAY_HAVE_CUDA
else
{
if (impl_->direct_rendering)
{
impl_->direct_rt[impl_->buffer_index[buf]].display_color_buffer();
}
else
{
impl_->indirect_rt[impl_->buffer_index[buf]].display_color_buffer();
}
}
#endif
if (prev_srgb_enabled)
{
glEnable(GL_FRAMEBUFFER_SRGB);
}
else
{
glDisable(GL_FRAMEBUFFER_SRGB);
}
}
} // visionaray
<commit_msg>minor<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/config.h>
#include <cassert>
#include <utility>
#include <GL/glew.h>
#include <visionaray/cpu_buffer_rt.h>
#if VSNRAY_HAVE_CUDA
#include <visionaray/gpu_buffer_rt.h>
#include <visionaray/pixel_unpack_buffer_rt.h>
#endif
#include "host_device_rt.h"
namespace visionaray
{
//-------------------------------------------------------------------------------------------------
// Private implementation
//
struct host_device_rt::impl
{
// CPU or GPU rendering
mode_type mode;
// If true, render target uses double buffering
bool double_buffering;
// If true, use PBO, otherwise copy over host
bool direct_rendering;
// Framebuffer color space, either RGB or SRGB
color_space_type color_space;
// Host render target
cpu_buffer_rt<PF_RGBA8, PF_UNSPECIFIED, PF_RGBA32F> host_rt[2];
#if VSNRAY_HAVE_CUDA
// Device render target, uses PBO
pixel_unpack_buffer_rt<PF_RGBA8, PF_UNSPECIFIED, PF_RGBA32F> direct_rt[2];
// Device render target, copy pixels over host
gpu_buffer_rt<PF_RGBA8, PF_UNSPECIFIED, PF_RGBA32F> indirect_rt[2];
#endif
// Index of front and back buffer, either 0 or 1
bool buffer_index[2];
};
//-------------------------------------------------------------------------------------------------
// host_device_rt
//
host_device_rt::host_device_rt(
mode_type mode,
bool double_buffering,
bool direct_rendering,
color_space_type color_space
)
: impl_(new impl)
{
impl_->mode = mode;
set_double_buffering(double_buffering);
impl_->direct_rendering = direct_rendering;
impl_->color_space = color_space;
}
host_device_rt::~host_device_rt()
{
}
host_device_rt::mode_type& host_device_rt::mode()
{
return impl_->mode;
}
host_device_rt::mode_type const& host_device_rt::mode() const
{
return impl_->mode;
}
void host_device_rt::set_double_buffering(bool double_buffering)
{
impl_->double_buffering = double_buffering;
if (impl_->double_buffering)
{
impl_->buffer_index[0] = 0;
impl_->buffer_index[1] = 1;
}
else
{
// Both indices the same, so when we swap buffers, in the
// single buffering case nothing will ever get swapped
impl_->buffer_index[0] = 0;
impl_->buffer_index[1] = 0;
}
}
bool host_device_rt::get_double_buffering() const
{
return impl_->double_buffering;
}
bool& host_device_rt::direct_rendering()
{
return impl_->direct_rendering;
}
bool const& host_device_rt::direct_rendering() const
{
return impl_->direct_rendering;
}
host_device_rt::color_space_type& host_device_rt::color_space()
{
return impl_->color_space;
}
host_device_rt::color_space_type const& host_device_rt::color_space() const
{
return impl_->color_space;
}
void host_device_rt::swap_buffers()
{
std::swap(impl_->buffer_index[Front], impl_->buffer_index[Back]);
}
host_device_rt::color_type const* host_device_rt::color(buffer buf) const
{
return impl_->host_rt[impl_->buffer_index[buf]].color();
}
host_device_rt::ref_type host_device_rt::ref(buffer buf)
{
if (impl_->mode == CPU)
{
return impl_->host_rt[impl_->buffer_index[buf]].ref();
}
else
{
#if VSNRAY_HAVE_CUDA
if (impl_->direct_rendering)
{
return impl_->direct_rt[impl_->buffer_index[buf]].ref();
}
else
{
return impl_->indirect_rt[impl_->buffer_index[buf]].ref();
}
#else
assert(0);
return {};
#endif
}
}
void host_device_rt::clear(vec4 const& color, buffer buf)
{
impl_->host_rt[impl_->buffer_index[buf]].clear_color_buffer(color);
impl_->host_rt[impl_->buffer_index[buf]].clear_accum_buffer(color);
#if VSNRAY_HAVE_CUDA
if (impl_->direct_rendering)
{
impl_->direct_rt[impl_->buffer_index[buf]].clear_color_buffer(color);
}
else
{
impl_->indirect_rt[impl_->buffer_index[buf]].clear_color_buffer(color);
}
#endif
}
void host_device_rt::begin_frame(buffer buf)
{
if (impl_->mode == CPU)
{
impl_->host_rt[impl_->buffer_index[buf]].begin_frame();
}
#if VSNRAY_HAVE_CUDA
else
{
if (impl_->direct_rendering)
{
impl_->direct_rt[impl_->buffer_index[buf]].begin_frame();
}
else
{
impl_->indirect_rt[impl_->buffer_index[buf]].begin_frame();
}
}
#endif
}
void host_device_rt::end_frame(buffer buf)
{
if (impl_->mode == CPU)
{
impl_->host_rt[impl_->buffer_index[buf]].end_frame();
}
#if VSNRAY_HAVE_CUDA
else
{
if (impl_->direct_rendering)
{
impl_->direct_rt[impl_->buffer_index[buf]].end_frame();
}
else
{
impl_->indirect_rt[impl_->buffer_index[buf]].end_frame();
}
}
#endif
}
void host_device_rt::resize(int w, int h)
{
render_target::resize(w, h);
int num_buffers = impl_->double_buffering ? 2 : 1;
for (int buf = 0; buf < num_buffers; ++buf)
{
impl_->host_rt[buf].resize(w, h);
#if VSNRAY_HAVE_CUDA
if (impl_->direct_rendering)
{
impl_->direct_rt[buf].resize(w, h);
}
else
{
impl_->indirect_rt[buf].resize(w, h);
}
#endif
}
}
void host_device_rt::display_color_buffer(buffer buf) const
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Store OpenGL state
GLboolean prev_srgb_enabled = glIsEnabled(GL_FRAMEBUFFER_SRGB);
if (impl_->color_space == SRGB)
{
glEnable(GL_FRAMEBUFFER_SRGB);
}
else
{
glDisable(GL_FRAMEBUFFER_SRGB);
}
if (impl_->mode == CPU)
{
impl_->host_rt[impl_->buffer_index[buf]].display_color_buffer();
}
#if VSNRAY_HAVE_CUDA
else
{
if (impl_->direct_rendering)
{
impl_->direct_rt[impl_->buffer_index[buf]].display_color_buffer();
}
else
{
impl_->indirect_rt[impl_->buffer_index[buf]].display_color_buffer();
}
}
#endif
if (prev_srgb_enabled)
{
glEnable(GL_FRAMEBUFFER_SRGB);
}
else
{
glDisable(GL_FRAMEBUFFER_SRGB);
}
}
} // visionaray
<|endoftext|> |
<commit_before>#include "musicuserwindow.h"
#include "musicuiobject.h"
#include "ui_musicuserwindow.h"
#include "musicuserdialog.h"
#include "musicusermodel.h"
#include "musicusermanager.h"
#include "musicmessagebox.h"
#include <QTimer>
MusicUserWindow::MusicUserWindow(QWidget *parent)
: QStackedWidget(parent), ui(new Ui::MusicUserWindow)
{
ui->setupUi(this);
ui->userLogin->setStyleSheet(MusicUIObject::MPushButtonStyle07);
ui->userName->setStyleSheet(MusicUIObject::MPushButtonStyle11);
ui->userLogin->setCursor(QCursor(Qt::PointingHandCursor));
ui->userName->setCursor(QCursor(Qt::PointingHandCursor));
ui->userIcon->setStyleSheet(MusicUIObject::MCustomStyle28);
connectDatabase();
m_userManager = new MusicUserManager(this);
connect(ui->userLogin,SIGNAL(clicked()),SLOT(musicUserLogin()));
connect(ui->userName,SIGNAL(clicked()),m_userManager,SLOT(exec()));
connect(m_userManager,SIGNAL(userStateChanged(QString)),SLOT(userStateChanged(QString)));
}
MusicUserWindow::~MusicUserWindow()
{
disConnectDatabase();
delete m_userManager;
delete ui;
}
bool MusicUserWindow::disConnectDatabase()
{
QString connectionName;
{
QSqlDatabase data = QSqlDatabase::database("user-data");
connectionName = data.connectionName();
if( data.isValid() )
{
data.close();
}
else
{
return false;
}
}
QSqlDatabase::removeDatabase( connectionName );
return true;
}
bool MusicUserWindow::connectDatabase()
{
try
{
QSqlDatabase data;
if(QSqlDatabase::contains("user-data"))
{
data = QSqlDatabase::database("user-data");
}
else
{
data = QSqlDatabase::addDatabase(DATABASETYPE, "user-data");
}
data.setDatabaseName(MusicObject::getAppDir() + DARABASEPATH);
if( !data.isDriverAvailable(DATABASETYPE) )
{
throw QString("The driver name is not available!");
}
if( !data.isValid() )
{
throw QString("The database has not a vaild driver!");
}
if (!data.isOpen() && !data.open() )
{
throw QString("Can not open database connection!");
}
if(!data.tables().contains("MusicUser"))
{
QSqlQuery query(data);
QString musicUserSql = QString("create table MusicUser (USERID vchar(%1) PRIMARY KEY,"
"PASSWD vchar(%2),EMAIL vchar(%3),USERNAME vchar(%4),LOGINTIME vchar(%5))")
.arg(USERID).arg(PASSWD).arg(EMAIL).arg(USERNAME).arg(LOGINTIME);
query.exec(musicUserSql);
}
}
catch(QString exception)
{
MusicMessageBox message;
message.setText( exception );
message.exec();
return false;
}
return true;
}
void MusicUserWindow::userStateChanged(const QString &name)
{
ui->userName->setText(QFontMetrics(font())
.elidedText(name, Qt::ElideRight,44));
if(currentIndex() == 1)
{
setCurrentIndex(0);
}
else
{
m_userManager->setUserName(name);
setCurrentIndex(1);
}
}
void MusicUserWindow::musicUserLogin()
{
MusicUserDialog dialog;
connect(&dialog, SIGNAL(userLoginSuccess(QString)), SLOT(userStateChanged(QString)));
dialog.exec();
}
void MusicUserWindow::musicUserContextLogin()
{
if(currentIndex() == 1)
{
setCurrentIndex(0);
}
QTimer::singleShot(1, this, SLOT(musicUserLogin()));
}
<commit_msg>clean code for musicuserwindow[121717]<commit_after>#include "musicuserwindow.h"
#include "musicuiobject.h"
#include "ui_musicuserwindow.h"
#include "musicuserdialog.h"
#include "musicusermodel.h"
#include "musicusermanager.h"
#include "musicmessagebox.h"
#include <QTimer>
MusicUserWindow::MusicUserWindow(QWidget *parent)
: QStackedWidget(parent),
ui(new Ui::MusicUserWindow)
{
ui->setupUi(this);
ui->userLogin->setStyleSheet(MusicUIObject::MPushButtonStyle07);
ui->userName->setStyleSheet(MusicUIObject::MPushButtonStyle11);
ui->userLogin->setCursor(QCursor(Qt::PointingHandCursor));
ui->userName->setCursor(QCursor(Qt::PointingHandCursor));
ui->userIcon->setStyleSheet(MusicUIObject::MCustomStyle28);
connectDatabase();
m_userManager = new MusicUserManager(this);
connect(ui->userLogin, SIGNAL(clicked()), SLOT(musicUserLogin()));
connect(ui->userName, SIGNAL(clicked()), m_userManager, SLOT(exec()));
connect(m_userManager, SIGNAL(userStateChanged(QString)), SLOT(userStateChanged(QString)));
}
MusicUserWindow::~MusicUserWindow()
{
disConnectDatabase();
delete m_userManager;
delete ui;
}
bool MusicUserWindow::disConnectDatabase()
{
QString connectionName;
{
QSqlDatabase data = QSqlDatabase::database("user-data");
connectionName = data.connectionName();
if( data.isValid() )
{
data.close();
}
else
{
return false;
}
}
QSqlDatabase::removeDatabase( connectionName );
return true;
}
bool MusicUserWindow::connectDatabase()
{
try
{
QSqlDatabase data;
if(QSqlDatabase::contains("user-data"))
{
data = QSqlDatabase::database("user-data");
}
else
{
data = QSqlDatabase::addDatabase(DATABASETYPE, "user-data");
}
data.setDatabaseName(MusicObject::getAppDir() + DARABASEPATH);
if( !data.isDriverAvailable(DATABASETYPE) )
{
throw QString("The driver name is not available!");
}
if( !data.isValid() )
{
throw QString("The database has not a vaild driver!");
}
if (!data.isOpen() && !data.open() )
{
throw QString("Can not open database connection!");
}
if(!data.tables().contains("MusicUser"))
{
QSqlQuery query(data);
QString musicUserSql = QString("create table MusicUser (USERID vchar(%1) PRIMARY KEY,"
"PASSWD vchar(%2),EMAIL vchar(%3),USERNAME vchar(%4),LOGINTIME vchar(%5))")
.arg(USERID).arg(PASSWD).arg(EMAIL).arg(USERNAME).arg(LOGINTIME);
query.exec(musicUserSql);
}
}
catch(QString exception)
{
MusicMessageBox message;
message.setText( exception );
message.exec();
return false;
}
return true;
}
void MusicUserWindow::userStateChanged(const QString &name)
{
ui->userName->setText(QFontMetrics(font()).elidedText(name, Qt::ElideRight, 44));
if(currentIndex() == 1)
{
setCurrentIndex(0);
}
else
{
m_userManager->setUserName(name);
setCurrentIndex(1);
}
}
void MusicUserWindow::musicUserLogin()
{
MusicUserDialog dialog;
connect(&dialog, SIGNAL(userLoginSuccess(QString)), SLOT(userStateChanged(QString)));
dialog.exec();
}
void MusicUserWindow::musicUserContextLogin()
{
if(currentIndex() == 1)
{
setCurrentIndex(0);
}
QTimer::singleShot(1, this, SLOT(musicUserLogin()));
}
<|endoftext|> |
<commit_before>/// HEADER
#include "import_ros.h"
/// COMPONENT
#include <csapex_ros/ros_handler.h>
#include <csapex_ros/ros_message_conversion.h>
/// PROJECT
#include <csapex/msg/input.h>
#include <csapex/msg/output.h>
#include <csapex/msg/message_factory.h>
#include <csapex/utility/stream_interceptor.h>
#include <csapex/msg/message.h>
#include <csapex/utility/qt_helper.hpp>
#include <utils_param/parameter_factory.h>
#include <utils_param/set_parameter.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_worker.h>
#include <csapex_ros/time_stamp_message.h>
/// SYSTEM
#include <yaml-cpp/eventhandler.h>
#include <sensor_msgs/Image.h>
#include <QAction>
#include <QComboBox>
#include <QPushButton>
#include <QLabel>
CSAPEX_REGISTER_CLASS(csapex::ImportRos, csapex::Node)
using namespace csapex;
const std::string ImportRos::no_topic_("-----");
namespace {
ros::Time rosTime(u_int64_t ns) {
ros::Time t;
t.fromNSec(ns);
return t;
}
}
ImportRos::ImportRos()
: connector_(NULL), retries_(0), running_(true)
{
}
void ImportRos::setup()
{
input_time_ = modifier_->addOptionalInput<connection_types::TimeStampMessage>("time");
connector_ = modifier_->addOutput<connection_types::AnyMessage>("Something");
boost::function<bool()> connected_condition = (boost::bind(&Input::isConnected, input_time_));
param::Parameter::Ptr buffer_p = param::ParameterFactory::declareRange("buffer/length", 0.0, 10.0, 1.0, 0.1);
addConditionalParameter(buffer_p, connected_condition);
param::Parameter::Ptr max_wait_p = param::ParameterFactory::declareRange("buffer/max_wait", 0.0, 10.0, 1.0, 0.1);
addConditionalParameter(max_wait_p, connected_condition);
}
void ImportRos::setupParameters()
{
std::vector<std::string> set;
set.push_back(no_topic_);
addParameter(param::ParameterFactory::declareParameterStringSet("topic", set),
boost::bind(&ImportRos::update, this));
addParameter(param::ParameterFactory::declareTrigger("refresh"),
boost::bind(&ImportRos::refresh, this));
addParameter(param::ParameterFactory::declareRange("rate", 0.1, 100.0, 60.0, 0.1),
boost::bind(&ImportRos::updateRate, this));
addParameter(param::ParameterFactory::declareRange("queue", 0, 30, 1, 1),
boost::bind(&ImportRos::updateSubscriber, this));
addParameter(param::ParameterFactory::declareBool("latch", false));
}
void ImportRos::setupROS()
{
refresh();
}
void ImportRos::refresh()
{
ROSHandler& rh = getRosHandler();
if(rh.nh()) {
std::string old_topic = readParameter<std::string>("topic");
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
param::SetParameter::Ptr setp = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("topic"));
if(setp) {
setError(false);
bool found = false;
std::vector<std::string> topics_str;
topics_str.push_back(no_topic_);
for(ros::master::V_TopicInfo::const_iterator it = topics.begin(); it != topics.end(); ++it) {
topics_str.push_back(it->name);
if(it->name == old_topic) {
found = true;
}
}
if(!found) {
topics_str.push_back(old_topic);
}
setp->setSet(topics_str);
if(old_topic != no_topic_) {
setp->set(old_topic);
}
return;
}
}
setError(true, "no ROS connection", EL_WARNING);
}
void ImportRos::update()
{
retries_ = 5;
doSetTopic();
}
void ImportRos::updateRate()
{
getNodeWorker()->setTickFrequency(readParameter<double>("rate"));
}
void ImportRos::updateSubscriber()
{
if(!current_topic_.name.empty()) {
current_subscriber = RosMessageConversion::instance().subscribe(current_topic_, readParameter<int>("queue"), boost::bind(&ImportRos::callback, this, _1));
}
}
void ImportRos::doSetTopic()
{
getRosHandler().refresh();
if(!getRosHandler().isConnected()) {
setError(true, "no connection to ROS");
return;
}
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
std::string topic = readParameter<std::string>("topic");
if(topic == no_topic_) {
return;
}
for(ros::master::V_TopicInfo::iterator it = topics.begin(); it != topics.end(); ++it) {
if(it->name == topic) {
setTopic(*it);
retries_ = 0;
return;
}
}
std::stringstream ss;
ss << "cannot set topic, " << topic << " doesn't exist";
if(retries_ > 0) {
ss << ", " << retries_ << " retries left";
}
ss << ".";
setError(true, ss.str());
}
void ImportRos::processROS()
{
if(!input_time_->isConnected()) {
return;
}
// INPUT CONNECTED
connection_types::TimeStampMessage::Ptr time = input_time_->getMessage<connection_types::TimeStampMessage>();
if(msgs_.empty()) {
return;
}
if(time->value == ros::Time(0)) {
setError(true, "incoming time is 0, using default behaviour", EL_WARNING);
publishLatestMessage();
return;
}
if(ros::Time(msgs_.back()->stamp) == ros::Time(0)) {
setError(true, "buffered time is 0, using default behaviour", EL_WARNING);
publishLatestMessage();
return;
}
// drop old messages
ros::Duration keep_duration(readParameter<double>("buffer/length"));
while(!msgs_.empty() && rosTime(msgs_.front()->stamp) + keep_duration < time->value) {
msgs_.pop_front();
}
if(!msgs_.empty()) {
if(rosTime(msgs_.front()->stamp) > time->value) {
aerr << "time stamp " << time->value << " is too old, oldest buffered is " << rosTime(msgs_.front()->stamp) << std::endl;
return;
}
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.back()->stamp) + max_wait_duration < time->value) {
aerr << "time stamp " << time->value << " is too new" << std::endl;
return;
}
}
// wait until we have a message
if(!isStampCovered(time->value)) {
ros::Rate r(10);
while(!isStampCovered(time->value) && running_) {
r.sleep();
ros::spinOnce();
if(!msgs_.empty()) {
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.back()->stamp) + max_wait_duration < time->value) {
aerr << "time stamp " << time->value << " is too new" << std::endl;
return;
}
}
}
}
std::deque<connection_types::Message::Ptr>::iterator first_after = msgs_.begin();
while(rosTime((*first_after)->stamp) < time->value) {
++first_after;
}
std::deque<connection_types::Message::Ptr>::iterator last_before = first_after - 1;
ros::Duration diff1 = rosTime((*first_after)->stamp) - time->value;
ros::Duration diff2 = rosTime((*last_before)->stamp) - time->value;
if(diff1 < diff2) {
connector_->publish(*first_after);
} else {
connector_->publish(*last_before);
}
}
bool ImportRos::isStampCovered(const ros::Time &stamp)
{
return rosTime(msgs_.back()->stamp) >= stamp;
}
void ImportRos::tickROS()
{
if(retries_ > 0) {
if(ros::WallTime::now() > next_retry_) {
doSetTopic();
--retries_;
next_retry_ = ros::WallTime::now() + ros::WallDuration(0.5);
}
}
if(input_time_->isConnected()) {
return;
}
// NO INPUT CONNECTED -> ONLY KEEP CURRENT MESSAGE
while(msgs_.size() > 1) {
msgs_.pop_front();
}
publishLatestMessage();
}
void ImportRos::publishLatestMessage()
{
if(msgs_.empty()) {
ros::Rate r(10);
while(msgs_.empty() && running_) {
r.sleep();
ros::spinOnce();
}
}
connector_->publish(msgs_.back());
if(!readParameter<bool>("latch")) {
msgs_.clear();
}
}
void ImportRos::callback(ConnectionTypePtr message)
{
connection_types::Message::Ptr msg = boost::dynamic_pointer_cast<connection_types::Message>(message);
if(msg) {
if(!msgs_.empty() && msg->stamp < msgs_.front()->stamp) {
awarn << "detected time anomaly -> reset";
msgs_.clear();
}
msgs_.push_back(msg);
}
}
void ImportRos::setTopic(const ros::master::TopicInfo &topic)
{
if(topic.name == current_topic_.name) {
return;
}
current_subscriber.shutdown();
if(RosMessageConversion::instance().canHandle(topic)) {
setError(false);
current_topic_ = topic;
updateSubscriber();
} else {
setError(true, std::string("cannot import topic of type ") + topic.datatype);
return;
}
}
void ImportRos::setParameterState(Memento::Ptr memento)
{
Node::setParameterState(memento);
}
void ImportRos::abort()
{
running_ = false;
}
<commit_msg>minor<commit_after>/// HEADER
#include "import_ros.h"
/// COMPONENT
#include <csapex_ros/ros_handler.h>
#include <csapex_ros/ros_message_conversion.h>
/// PROJECT
#include <csapex/msg/input.h>
#include <csapex/msg/output.h>
#include <csapex/msg/message_factory.h>
#include <csapex/utility/stream_interceptor.h>
#include <csapex/msg/message.h>
#include <csapex/utility/qt_helper.hpp>
#include <utils_param/parameter_factory.h>
#include <utils_param/set_parameter.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_worker.h>
#include <csapex_ros/time_stamp_message.h>
/// SYSTEM
#include <yaml-cpp/eventhandler.h>
#include <sensor_msgs/Image.h>
#include <QAction>
#include <QComboBox>
#include <QPushButton>
#include <QLabel>
CSAPEX_REGISTER_CLASS(csapex::ImportRos, csapex::Node)
using namespace csapex;
const std::string ImportRos::no_topic_("-----");
namespace {
ros::Time rosTime(u_int64_t ns) {
ros::Time t;
t.fromNSec(ns);
return t;
}
}
ImportRos::ImportRos()
: connector_(NULL), retries_(0), running_(true)
{
}
void ImportRos::setup()
{
input_time_ = modifier_->addOptionalInput<connection_types::TimeStampMessage>("time");
connector_ = modifier_->addOutput<connection_types::AnyMessage>("Something");
boost::function<bool()> connected_condition = (boost::bind(&Input::isConnected, input_time_));
param::Parameter::Ptr buffer_p = param::ParameterFactory::declareRange("buffer/length", 0.0, 10.0, 1.0, 0.1);
addConditionalParameter(buffer_p, connected_condition);
param::Parameter::Ptr max_wait_p = param::ParameterFactory::declareRange("buffer/max_wait", 0.0, 10.0, 1.0, 0.1);
addConditionalParameter(max_wait_p, connected_condition);
}
void ImportRos::setupParameters()
{
std::vector<std::string> set;
set.push_back(no_topic_);
addParameter(param::ParameterFactory::declareParameterStringSet("topic", set),
boost::bind(&ImportRos::update, this));
addParameter(param::ParameterFactory::declareTrigger("refresh"),
boost::bind(&ImportRos::refresh, this));
addParameter(param::ParameterFactory::declareRange("rate", 0.1, 100.0, 60.0, 0.1),
boost::bind(&ImportRos::updateRate, this));
addParameter(param::ParameterFactory::declareRange("queue", 0, 30, 1, 1),
boost::bind(&ImportRos::updateSubscriber, this));
addParameter(param::ParameterFactory::declareBool("latch", false));
}
void ImportRos::setupROS()
{
refresh();
}
void ImportRos::refresh()
{
ROSHandler& rh = getRosHandler();
if(rh.nh()) {
std::string old_topic = readParameter<std::string>("topic");
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
param::SetParameter::Ptr setp = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("topic"));
if(setp) {
setError(false);
bool found = false;
std::vector<std::string> topics_str;
topics_str.push_back(no_topic_);
for(ros::master::V_TopicInfo::const_iterator it = topics.begin(); it != topics.end(); ++it) {
topics_str.push_back(it->name);
if(it->name == old_topic) {
found = true;
}
}
if(!found) {
topics_str.push_back(old_topic);
}
setp->setSet(topics_str);
if(old_topic != no_topic_) {
setp->set(old_topic);
}
return;
}
}
setError(true, "no ROS connection", EL_WARNING);
}
void ImportRos::update()
{
retries_ = 5;
doSetTopic();
}
void ImportRos::updateRate()
{
getNodeWorker()->setTickFrequency(readParameter<double>("rate"));
}
void ImportRos::updateSubscriber()
{
if(!current_topic_.name.empty()) {
current_subscriber = RosMessageConversion::instance().subscribe(current_topic_, readParameter<int>("queue"), boost::bind(&ImportRos::callback, this, _1));
}
}
void ImportRos::doSetTopic()
{
getRosHandler().refresh();
if(!getRosHandler().isConnected()) {
setError(true, "no connection to ROS");
return;
}
ros::master::V_TopicInfo topics;
ros::master::getTopics(topics);
std::string topic = readParameter<std::string>("topic");
if(topic == no_topic_) {
return;
}
for(ros::master::V_TopicInfo::iterator it = topics.begin(); it != topics.end(); ++it) {
if(it->name == topic) {
setTopic(*it);
retries_ = 0;
return;
}
}
std::stringstream ss;
ss << "cannot set topic, " << topic << " doesn't exist";
if(retries_ > 0) {
ss << ", " << retries_ << " retries left";
}
ss << ".";
setError(true, ss.str());
}
void ImportRos::processROS()
{
// first check if connected -> if not connected, we only use tick
if(!input_time_->isConnected()) {
return;
}
// now that we are connected, check that we have a valid message
if(!input_time_->hasMessage()) {
return;
}
// INPUT CONNECTED
connection_types::TimeStampMessage::Ptr time = input_time_->getMessage<connection_types::TimeStampMessage>();
if(msgs_.empty()) {
return;
}
if(time->value == ros::Time(0)) {
setError(true, "incoming time is 0, using default behaviour", EL_WARNING);
publishLatestMessage();
return;
}
if(ros::Time(msgs_.back()->stamp) == ros::Time(0)) {
setError(true, "buffered time is 0, using default behaviour", EL_WARNING);
publishLatestMessage();
return;
}
// drop old messages
ros::Duration keep_duration(readParameter<double>("buffer/length"));
while(!msgs_.empty() && rosTime(msgs_.front()->stamp) + keep_duration < time->value) {
msgs_.pop_front();
}
if(!msgs_.empty()) {
if(rosTime(msgs_.front()->stamp) > time->value) {
aerr << "time stamp " << time->value << " is too old, oldest buffered is " << rosTime(msgs_.front()->stamp) << std::endl;
return;
}
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.back()->stamp) + max_wait_duration < time->value) {
aerr << "time stamp " << time->value << " is too new" << std::endl;
return;
}
}
// wait until we have a message
if(!isStampCovered(time->value)) {
ros::Rate r(10);
while(!isStampCovered(time->value) && running_) {
r.sleep();
ros::spinOnce();
if(!msgs_.empty()) {
ros::Duration max_wait_duration(readParameter<double>("buffer/max_wait"));
if(rosTime(msgs_.back()->stamp) + max_wait_duration < time->value) {
aerr << "time stamp " << time->value << " is too new" << std::endl;
return;
}
}
}
}
std::deque<connection_types::Message::Ptr>::iterator first_after = msgs_.begin();
while(rosTime((*first_after)->stamp) < time->value) {
++first_after;
}
std::deque<connection_types::Message::Ptr>::iterator last_before = first_after - 1;
ros::Duration diff1 = rosTime((*first_after)->stamp) - time->value;
ros::Duration diff2 = rosTime((*last_before)->stamp) - time->value;
if(diff1 < diff2) {
connector_->publish(*first_after);
} else {
connector_->publish(*last_before);
}
}
bool ImportRos::isStampCovered(const ros::Time &stamp)
{
return rosTime(msgs_.back()->stamp) >= stamp;
}
void ImportRos::tickROS()
{
if(retries_ > 0) {
if(ros::WallTime::now() > next_retry_) {
doSetTopic();
--retries_;
next_retry_ = ros::WallTime::now() + ros::WallDuration(0.5);
}
}
if(input_time_->isConnected()) {
return;
}
// NO INPUT CONNECTED -> ONLY KEEP CURRENT MESSAGE
while(msgs_.size() > 1) {
msgs_.pop_front();
}
publishLatestMessage();
}
void ImportRos::publishLatestMessage()
{
if(msgs_.empty()) {
ros::Rate r(10);
while(msgs_.empty() && running_) {
r.sleep();
ros::spinOnce();
}
if(!running_) {
return;
}
}
connector_->publish(msgs_.back());
if(!readParameter<bool>("latch")) {
msgs_.clear();
}
}
void ImportRos::callback(ConnectionTypePtr message)
{
connection_types::Message::Ptr msg = boost::dynamic_pointer_cast<connection_types::Message>(message);
if(msg) {
if(!msgs_.empty() && msg->stamp < msgs_.front()->stamp) {
awarn << "detected time anomaly -> reset";
msgs_.clear();
}
msgs_.push_back(msg);
}
}
void ImportRos::setTopic(const ros::master::TopicInfo &topic)
{
if(topic.name == current_topic_.name) {
return;
}
current_subscriber.shutdown();
if(RosMessageConversion::instance().canHandle(topic)) {
setError(false);
current_topic_ = topic;
updateSubscriber();
} else {
setError(true, std::string("cannot import topic of type ") + topic.datatype);
return;
}
}
void ImportRos::setParameterState(Memento::Ptr memento)
{
Node::setParameterState(memento);
}
void ImportRos::abort()
{
running_ = false;
}
<|endoftext|> |
<commit_before>/*
* transition_qtblend.cpp -- Qt composite transition
* Copyright (c) 2016 Jean-Baptiste Mardelle <jb@kdenlive.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 "common.h"
#include <framework/mlt.h>
#include <stdio.h>
#include <QImage>
#include <QPainter>
#include <QTransform>
static int get_image( mlt_frame a_frame, uint8_t **image, mlt_image_format *format, int *width, int *height, int writable )
{
int error = 0;
mlt_frame b_frame = mlt_frame_pop_frame( a_frame );
mlt_properties b_properties = MLT_FRAME_PROPERTIES( b_frame );
mlt_properties properties = MLT_FRAME_PROPERTIES( a_frame );
mlt_transition transition = MLT_TRANSITION( mlt_frame_pop_service( a_frame ) );
mlt_properties transition_properties = MLT_TRANSITION_PROPERTIES( transition );
uint8_t *b_image = NULL;
bool hasAlpha = false;
double opacity = 1.0;
QTransform transform;
// reference rect
mlt_rect rect;
// Determine length
mlt_position length = mlt_transition_get_length( transition );
// Get current position
mlt_position position = mlt_transition_get_position( transition, a_frame );
// Obtain the normalised width and height from the a_frame
mlt_profile profile = mlt_service_profile( MLT_TRANSITION_SERVICE( transition ) );
int normalised_width = profile->width;
int normalised_height = profile->height;
double consumer_ar = mlt_profile_sar( profile );
int b_width = mlt_properties_get_int( b_properties, "meta.media.width" );
int b_height = mlt_properties_get_int( b_properties, "meta.media.height" );
double b_ar = mlt_frame_get_aspect_ratio( b_frame );
double b_dar = b_ar * b_width / b_height;
rect.w = -1;
rect.h = -1;
// Check transform
if ( mlt_properties_get( transition_properties, "rect" ) )
{
rect = mlt_properties_anim_get_rect( transition_properties, "rect", position, length );
transform.translate(rect.x, rect.y);
opacity = rect.o;
}
double output_ar = mlt_profile_sar( profile );
if ( mlt_frame_get_aspect_ratio( b_frame ) == 0 )
{
mlt_frame_set_aspect_ratio( b_frame, output_ar );
}
if ( mlt_properties_get( transition_properties, "rotation" ) )
{
double angle = mlt_properties_anim_get_double( transition_properties, "rotation", position, length );
transform.rotate( angle );
hasAlpha = true;
}
// This is not a field-aware transform.
mlt_properties_set_int( b_properties, "consumer_deinterlace", 1 );
// Suppress padding and aspect normalization.
char *interps = mlt_properties_get( properties, "rescale.interp" );
if ( interps )
interps = strdup( interps );
if ( error )
{
return error;
}
if ( rect.w != -1 )
{
// resize to rect
if ( mlt_properties_get_int( transition_properties, "distort" ) && b_width != 0 && b_height != 0 )
{
transform.scale( rect.w / b_width, rect.h / b_height );
}
else
{
float scale_x = MIN( rect.w / b_width, rect.h / b_height );
float scale_y = scale_x;
// Determine scale with respect to aspect ratio.
double consumer_dar = consumer_ar * normalised_width / normalised_height;
if ( b_dar > consumer_dar )
{
scale_y = scale_x;
scale_y *= consumer_ar / b_ar;
}
else
{
scale_x = scale_y;
scale_x *= b_ar / consumer_ar;
}
transform.translate((rect.w - (b_width * scale_x)) / 2.0, (rect.h - (b_height * scale_y)) / 2.0);
transform.scale( scale_x, scale_y );
}
if ( opacity < 1 || transform.isScaling() || transform.isTranslating() )
{
// we will process operations on top frame, so also process b_frame
hasAlpha = true;
}
}
else
{
// No transform, request profile sized image
b_width = *width;
b_height = *height;
}
if ( !hasAlpha && ( mlt_properties_get_int( transition_properties, "compositing" ) != 0 || b_width < *width || b_height < *height || b_width < normalised_width || b_height < normalised_height ) )
{
hasAlpha = true;
}
// Check if we have transparency
if ( !hasAlpha )
{
// fetch image
error = mlt_frame_get_image( b_frame, &b_image, format, width, height, 1 );
if ( *format == mlt_image_rgb24a || mlt_frame_get_alpha( b_frame ) )
{
hasAlpha = true;
}
}
if ( !hasAlpha )
{
// Prepare output image
*image = b_image;
mlt_frame_replace_image( a_frame, b_image, *format, *width, *height );
free( interps );
return 0;
}
// Get RGBA image to process
*format = mlt_image_rgb24a;
error = mlt_frame_get_image( b_frame, &b_image, format, &b_width, &b_height, writable );
// Get bottom frame
uint8_t *a_image = NULL;
error = mlt_frame_get_image( a_frame, &a_image, format, width, height, 1 );
if (error)
{
free( interps );
return error;
}
// Prepare output image
int image_size = mlt_image_format_size( *format, *width, *height, NULL );
*image = (uint8_t *) mlt_pool_alloc( image_size );
// Copy bottom frame in output
memcpy( *image, a_image, image_size );
bool hqPainting = false;
if ( interps )
{
if ( strcmp( interps, "bilinear" ) == 0 || strcmp( interps, "bicubic" ) == 0 )
{
hqPainting = true;
}
}
// convert bottom mlt image to qimage
QImage bottomImg;
convert_mlt_to_qimage_rgba( *image, &bottomImg, *width, *height );
// convert top mlt image to qimage
QImage topImg;
convert_mlt_to_qimage_rgba( b_image, &topImg, b_width, b_height );
// setup Qt drawing
QPainter painter( &bottomImg );
painter.setCompositionMode( ( QPainter::CompositionMode ) mlt_properties_get_int( transition_properties, "compositing" ) );
painter.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform, hqPainting );
painter.setTransform(transform);
painter.setOpacity(opacity);
// Composite top frame
painter.drawImage(0, 0, topImg);
// finish Qt drawing
painter.end();
convert_qimage_to_mlt_rgba( &bottomImg, *image, *width, *height );
mlt_frame_set_image( a_frame, *image, image_size, mlt_pool_release);
free( interps );
return error;
}
static mlt_frame process( mlt_transition transition, mlt_frame a_frame, mlt_frame b_frame )
{
mlt_frame_push_service( a_frame, transition );
mlt_frame_push_frame( a_frame, b_frame );
mlt_frame_push_get_image( a_frame, get_image );
return a_frame;
}
extern "C" {
mlt_transition transition_qtblend_init( mlt_profile profile, mlt_service_type type, const char *id, void *arg )
{
mlt_transition transition = mlt_transition_new();
if ( transition )
{
mlt_properties properties = MLT_TRANSITION_PROPERTIES( transition );
if ( !createQApplicationIfNeeded( MLT_TRANSITION_SERVICE(transition) ) )
{
mlt_transition_close( transition );
return NULL;
}
transition->process = process;
mlt_properties_set_int( properties, "_transition_type", 1 ); // video only
mlt_properties_set( properties, "rect", (char *) arg );
mlt_properties_set_int( properties, "compositing", 0 );
mlt_properties_set_int( properties, "distort", 0 );
}
return transition;
}
} // extern "C"
<commit_msg>Fix aspect ratio of qtblend transition with some profiles, activate transparency when compositing clips with different display ratio<commit_after>/*
* transition_qtblend.cpp -- Qt composite transition
* Copyright (c) 2016 Jean-Baptiste Mardelle <jb@kdenlive.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 "common.h"
#include <framework/mlt.h>
#include <stdio.h>
#include <QImage>
#include <QPainter>
#include <QTransform>
static int get_image( mlt_frame a_frame, uint8_t **image, mlt_image_format *format, int *width, int *height, int writable )
{
int error = 0;
mlt_frame b_frame = mlt_frame_pop_frame( a_frame );
mlt_properties b_properties = MLT_FRAME_PROPERTIES( b_frame );
mlt_properties properties = MLT_FRAME_PROPERTIES( a_frame );
mlt_transition transition = MLT_TRANSITION( mlt_frame_pop_service( a_frame ) );
mlt_properties transition_properties = MLT_TRANSITION_PROPERTIES( transition );
uint8_t *b_image = NULL;
bool hasAlpha = false;
double opacity = 1.0;
QTransform transform;
// reference rect
mlt_rect rect;
// Determine length
mlt_position length = mlt_transition_get_length( transition );
// Get current position
mlt_position position = mlt_transition_get_position( transition, a_frame );
// Obtain the normalised width and height from the a_frame
mlt_profile profile = mlt_service_profile( MLT_TRANSITION_SERVICE( transition ) );
int normalised_width = profile->width;
int normalised_height = profile->height;
double consumer_ar = mlt_profile_sar( profile );
int b_width = mlt_properties_get_int( b_properties, "meta.media.width" );
int b_height = mlt_properties_get_int( b_properties, "meta.media.height" );
if ( b_height == 0 )
{
b_width = normalised_width;
b_height = normalised_height;
}
double b_ar = mlt_frame_get_aspect_ratio( b_frame );
double b_dar = b_ar * b_width / b_height;
rect.w = -1;
rect.h = -1;
// Check transform
if ( mlt_properties_get( transition_properties, "rect" ) )
{
rect = mlt_properties_anim_get_rect( transition_properties, "rect", position, length );
transform.translate(rect.x, rect.y);
opacity = rect.o;
}
double output_ar = mlt_profile_sar( profile );
if ( mlt_frame_get_aspect_ratio( b_frame ) == 0 )
{
mlt_frame_set_aspect_ratio( b_frame, output_ar );
}
if ( mlt_properties_get( transition_properties, "rotation" ) )
{
double angle = mlt_properties_anim_get_double( transition_properties, "rotation", position, length );
transform.rotate( angle );
hasAlpha = true;
}
// This is not a field-aware transform.
mlt_properties_set_int( b_properties, "consumer_deinterlace", 1 );
// Suppress padding and aspect normalization.
char *interps = mlt_properties_get( properties, "rescale.interp" );
if ( interps )
interps = strdup( interps );
if ( error )
{
return error;
}
if ( rect.w != -1 )
{
// resize to rect
if ( mlt_properties_get_int( transition_properties, "distort" ) && b_width != 0 && b_height != 0 )
{
transform.scale( rect.w / b_width, rect.h / b_height );
}
else
{
float scale_x = MIN( rect.w / b_width * ( consumer_ar / b_ar ) , rect.h / b_height );
float scale_y = scale_x;
// Determine scale with respect to aspect ratio.
double consumer_dar = consumer_ar * normalised_width / normalised_height;
transform.translate((rect.w - (b_width * scale_x)) / 2.0, (rect.h - (b_height * scale_y)) / 2.0);
transform.scale( scale_x, scale_y );
}
if ( opacity < 1 || transform.isScaling() || transform.isTranslating() )
{
// we will process operations on top frame, so also process b_frame
hasAlpha = true;
}
}
else
{
// No transform, request profile sized image
if (b_dar != mlt_profile_dar( profile ) )
{
// Activate transparency if the clips don't have the same aspect ratio
hasAlpha = true;
}
b_width = *width;
b_height = *height;
}
if ( !hasAlpha && ( mlt_properties_get_int( transition_properties, "compositing" ) != 0 || b_width < *width || b_height < *height || b_width < normalised_width || b_height < normalised_height ) )
{
hasAlpha = true;
}
// Check if we have transparency
if ( !hasAlpha )
{
// fetch image
error = mlt_frame_get_image( b_frame, &b_image, format, width, height, 1 );
if ( *format == mlt_image_rgb24a || mlt_frame_get_alpha( b_frame ) )
{
hasAlpha = true;
}
}
if ( !hasAlpha )
{
// Prepare output image
*image = b_image;
mlt_frame_replace_image( a_frame, b_image, *format, *width, *height );
free( interps );
return 0;
}
// Get RGBA image to process
*format = mlt_image_rgb24a;
error = mlt_frame_get_image( b_frame, &b_image, format, &b_width, &b_height, writable );
// Get bottom frame
uint8_t *a_image = NULL;
error = mlt_frame_get_image( a_frame, &a_image, format, width, height, 1 );
if (error)
{
free( interps );
return error;
}
// Prepare output image
int image_size = mlt_image_format_size( *format, *width, *height, NULL );
*image = (uint8_t *) mlt_pool_alloc( image_size );
// Copy bottom frame in output
memcpy( *image, a_image, image_size );
bool hqPainting = false;
if ( interps )
{
if ( strcmp( interps, "bilinear" ) == 0 || strcmp( interps, "bicubic" ) == 0 )
{
hqPainting = true;
}
}
// convert bottom mlt image to qimage
QImage bottomImg;
convert_mlt_to_qimage_rgba( *image, &bottomImg, *width, *height );
// convert top mlt image to qimage
QImage topImg;
convert_mlt_to_qimage_rgba( b_image, &topImg, b_width, b_height );
// setup Qt drawing
QPainter painter( &bottomImg );
painter.setCompositionMode( ( QPainter::CompositionMode ) mlt_properties_get_int( transition_properties, "compositing" ) );
painter.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform, hqPainting );
painter.setTransform(transform);
painter.setOpacity(opacity);
// Composite top frame
painter.drawImage(0, 0, topImg);
// finish Qt drawing
painter.end();
convert_qimage_to_mlt_rgba( &bottomImg, *image, *width, *height );
mlt_frame_set_image( a_frame, *image, image_size, mlt_pool_release);
free( interps );
return error;
}
static mlt_frame process( mlt_transition transition, mlt_frame a_frame, mlt_frame b_frame )
{
mlt_frame_push_service( a_frame, transition );
mlt_frame_push_frame( a_frame, b_frame );
mlt_frame_push_get_image( a_frame, get_image );
return a_frame;
}
extern "C" {
mlt_transition transition_qtblend_init( mlt_profile profile, mlt_service_type type, const char *id, void *arg )
{
mlt_transition transition = mlt_transition_new();
if ( transition )
{
mlt_properties properties = MLT_TRANSITION_PROPERTIES( transition );
if ( !createQApplicationIfNeeded( MLT_TRANSITION_SERVICE(transition) ) )
{
mlt_transition_close( transition );
return NULL;
}
transition->process = process;
mlt_properties_set_int( properties, "_transition_type", 1 ); // video only
mlt_properties_set( properties, "rect", (char *) arg );
mlt_properties_set_int( properties, "compositing", 0 );
mlt_properties_set_int( properties, "distort", 0 );
}
return transition;
}
} // extern "C"
<|endoftext|> |
<commit_before>#include "TextInputWidget.hpp"
#include <iostream>
gsf::TextInputWidget::TextInputWidget(float width, float height, sf::Font &font)
: ChildWidget{ width, height }
//, m_text{ "", font, 12, sf::Color::Black }
, m_text{ nullptr }
, m_cursor{ "|", font, 12 }
, m_scrollable{ nullptr }
, m_isFocused{ false }
, m_cursorPos{ 0 }
, m_lBreaksBefCur{ 0 }
, m_isCursorShown{ true }
, m_blinkFreq{ 0.8f }
, m_lastBlinkTime{ 0.f }
, m_minBreakCharCnt{ 0 }
{
std::unique_ptr<TextWidget> text{
std::make_unique<TextWidget>("", font, 12, sf::Color::Black) };
std::unique_ptr<ScrollableWidget> scrollabe{
std::make_unique<ScrollableWidget>(width, height) };
m_scrollable = scrollabe.get();
m_text = text.get();
scrollabe->setBackgroundColor(sf::Color::Red);
scrollabe->attachChild(std::move(text));
//attachChild(std::move(text));
attachChild(std::move(scrollabe));
m_cursor.setFillColor(sf::Color::Black);
//m_text.setFont(font);
//m_text.setCharacterSize(12);
//m_text.setTextColor(sf::Color::Black);
//m_text.setOrigin(0.f, 0.f);
//m_text.setPosition(0.f, 0.f);
//m_scrollableWidget.attachChild();
}
void gsf::TextInputWidget::setText(const std::string &text)
{
m_text->setText(text);
}
std::string gsf::TextInputWidget::getText() const
{
return m_text->getText().toAnsiString();
}
void gsf::TextInputWidget::setCharacterSize(const unsigned int size)
{
m_text->setCharacterSize(size);
}
unsigned int gsf::TextInputWidget::getCharacterSize() const
{
return m_text->getCharacterSize();
}
void gsf::TextInputWidget::setTextColor(const sf::Color color)
{
m_text->setTextColor(color);
}
sf::Color gsf::TextInputWidget::getTextColor() const
{
return m_text->getTextColor();
}
bool gsf::TextInputWidget::isFocused() const
{
return m_isFocused;
}
void gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled)
{
m_scrollable->setIsVerticalScrollEnabled(isEnabled);
}
bool gsf::TextInputWidget::isVerticalScrollEnabled() const
{
return m_scrollable->isVerticalScrollEnabled();
}
void gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled)
{
m_scrollable->setIsHorizontalScrollEnabled(isEnabled);
}
bool gsf::TextInputWidget::isHorizontalScrollEnabled() const
{
return m_scrollable->isHorizontalScrollEnabled();
}
void gsf::TextInputWidget::drawCurrent(sf::RenderTarget &target,
sf::RenderStates states) const
{
}
void gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target,
sf::RenderStates states) const
{
// Draw cursor after children, so that children are not drawn over cursor
if (m_isCursorShown)
{
target.draw(m_cursor, states);
}
}
void gsf::TextInputWidget::updateCurrent(float dt)
{
// Update cursor stuff
m_lastBlinkTime += dt;
if (m_lastBlinkTime >= m_blinkFreq)
{
m_isCursorShown = !m_isCursorShown;
m_lastBlinkTime = 0.f;
}
//std::wstring text{ m_currentText };
//std::wstring text{ m_shownText };
//m_text->setText(text);
}
bool gsf::TextInputWidget::handleEventCurrent(sf::Event &event)
{
//bool handled{ ChildWidget::handleEvent(event) };/*||
// m_scrollable->handleEventWidget(event) };*/
// Check if actual Widget is focused
if (event.type == sf::Event::MouseButtonPressed)
{
sf::Vector2f mousePos{ (float) event.mouseButton.x,
(float) event.mouseButton.y };
bool isMouseInShownArea{ getShownArea().contains(mousePos) };
bool intersecting{ isIntersecting(mousePos) };
if (isMouseInShownArea && intersecting)
{
m_isFocused = true;
}
else
{
m_isFocused = false;
}
}
if (event.type == sf::Event::KeyPressed && m_isFocused)
{
switch (event.key.code)
{
case sf::Keyboard::Left:
if (m_cursorPos > 0)
{
m_cursorPos--;
}
// when cursor is moved it should be drawn so we reset its status
resetCursorStatus();
adjustShownText();
return true;
case sf::Keyboard::Right:
if (m_cursorPos < m_currentText.length())
{
m_cursorPos++;
}
resetCursorStatus();
adjustShownText();
m_cursor.setPosition
(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
return true;
default: break;
}
}
// If Widget is focused and Text entered, handle entered text
if (m_isFocused && event.type == sf::Event::TextEntered)
{
// To handle umlauts and other 'exotic' chars we use widestring
// and wide char
//std::wstring actualTxt{ m_text.getString().toWideString() };
wchar_t c{ static_cast<wchar_t>(event.text.unicode) };
std::cout << "Entered: " << c << std::endl;
switch (c)
{
// Backspace
case 8:
if (m_currentText.length() > 0)
{
// Remove chars right of cursor when there are chars
if (m_cursorPos > 0 && m_cursorPos < m_currentText.length())
{
m_currentText.erase(m_cursorPos - 1, 1);
m_cursorPos--;
}
// When cursos is at the end of the text, p
// place cursor behind char which we want to delete,
else if (m_cursorPos == m_currentText.length())
{
// Delete last char
m_currentText.pop_back();
m_cursorPos--;
}
}
break;
// Delete Pressed
case 127:
if (m_currentText.length() > 0 &&
m_cursorPos < m_currentText.length())
{
m_currentText.erase(m_cursorPos, 1);
}
break;
// Enter key
case 13: m_currentText.insert(m_cursorPos, L"\n"); m_cursorPos++; break;
// Add char to text
default: m_currentText.insert(m_cursorPos, std::wstring() + c); m_cursorPos++;
}
resetCursorStatus();
m_shownText = m_currentText;
m_text->setText(m_shownText);
adjustShownText();
m_cursor.setPosition(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
m_scrollable->recalculateScroll();
m_scrollable->scrollToRight();
m_scrollable->scrollToBottom();
return true;
}
return false;
//return handled;
}
void gsf::TextInputWidget::adjustShownText()
{
if (!m_scrollable->isHorizontalScrollEnabled())
{
m_lBreaksBefCur = 0;
std::wstring shownString{ L"" };
// The chars which are in the actual line
unsigned int charCntLine{ 0 };
// The total width of all chars in the current line
float lineWidth{ 0.f };
for (unsigned int i{ 0 }; i < m_currentText.size(); i++)
{
wchar_t c{ m_currentText[i] };
// Width of the current char
float cWidth { m_text->getFont().getGlyph(c, m_text->getCharacterSize(),
false).advance };
lineWidth += cWidth;
// When Text is out of scrollable widget, we have to add a new line
if (lineWidth > m_scrollable->getWidth())
{
if (i < m_cursorPos)
{
// We have to increase the "line breaks befor cursor" counter
// so we add the cursor later on the right position
m_lBreaksBefCur++;
}
//shownString += m_currentText.substr(i - charCntLine, charCntLine);
// Add new line
shownString += L"\n";
// add the char with which the line was to wide in the new line
shownString += c;
// We have added the char c in the new line, so we have now 1 char in the current line
charCntLine = 1;
lineWidth = cWidth;
}
else
{
charCntLine++;
shownString += c;
}
}
m_shownText = shownString;
m_text->setText(m_shownText);
}
}
void gsf::TextInputWidget::resetCursorStatus()
{
m_lastBlinkTime = 0.f;
m_isCursorShown = true;
}
<commit_msg>Fix bug by movin cursor left<commit_after>#include "TextInputWidget.hpp"
#include <iostream>
gsf::TextInputWidget::TextInputWidget(float width, float height, sf::Font &font)
: ChildWidget{ width, height }
//, m_text{ "", font, 12, sf::Color::Black }
, m_text{ nullptr }
, m_cursor{ "|", font, 12 }
, m_scrollable{ nullptr }
, m_isFocused{ false }
, m_cursorPos{ 0 }
, m_lBreaksBefCur{ 0 }
, m_isCursorShown{ true }
, m_blinkFreq{ 0.8f }
, m_lastBlinkTime{ 0.f }
, m_minBreakCharCnt{ 0 }
{
std::unique_ptr<TextWidget> text{
std::make_unique<TextWidget>("", font, 12, sf::Color::Black) };
std::unique_ptr<ScrollableWidget> scrollabe{
std::make_unique<ScrollableWidget>(width, height) };
m_scrollable = scrollabe.get();
m_text = text.get();
scrollabe->setBackgroundColor(sf::Color::Red);
scrollabe->attachChild(std::move(text));
//attachChild(std::move(text));
attachChild(std::move(scrollabe));
m_cursor.setFillColor(sf::Color::Black);
//m_text.setFont(font);
//m_text.setCharacterSize(12);
//m_text.setTextColor(sf::Color::Black);
//m_text.setOrigin(0.f, 0.f);
//m_text.setPosition(0.f, 0.f);
//m_scrollableWidget.attachChild();
}
void gsf::TextInputWidget::setText(const std::string &text)
{
m_text->setText(text);
}
std::string gsf::TextInputWidget::getText() const
{
return m_text->getText().toAnsiString();
}
void gsf::TextInputWidget::setCharacterSize(const unsigned int size)
{
m_text->setCharacterSize(size);
}
unsigned int gsf::TextInputWidget::getCharacterSize() const
{
return m_text->getCharacterSize();
}
void gsf::TextInputWidget::setTextColor(const sf::Color color)
{
m_text->setTextColor(color);
}
sf::Color gsf::TextInputWidget::getTextColor() const
{
return m_text->getTextColor();
}
bool gsf::TextInputWidget::isFocused() const
{
return m_isFocused;
}
void gsf::TextInputWidget::setIsVerticalScrollEnabled(bool isEnabled)
{
m_scrollable->setIsVerticalScrollEnabled(isEnabled);
}
bool gsf::TextInputWidget::isVerticalScrollEnabled() const
{
return m_scrollable->isVerticalScrollEnabled();
}
void gsf::TextInputWidget::setIsHorizontalScrollEnabled(bool isEnabled)
{
m_scrollable->setIsHorizontalScrollEnabled(isEnabled);
}
bool gsf::TextInputWidget::isHorizontalScrollEnabled() const
{
return m_scrollable->isHorizontalScrollEnabled();
}
void gsf::TextInputWidget::drawCurrent(sf::RenderTarget &target,
sf::RenderStates states) const
{
}
void gsf::TextInputWidget::drawCurrentAfterChildren(sf::RenderTarget &target,
sf::RenderStates states) const
{
// Draw cursor after children, so that children are not drawn over cursor
if (m_isCursorShown)
{
target.draw(m_cursor, states);
}
}
void gsf::TextInputWidget::updateCurrent(float dt)
{
// Update cursor stuff
m_lastBlinkTime += dt;
if (m_lastBlinkTime >= m_blinkFreq)
{
m_isCursorShown = !m_isCursorShown;
m_lastBlinkTime = 0.f;
}
//std::wstring text{ m_currentText };
//std::wstring text{ m_shownText };
//m_text->setText(text);
}
bool gsf::TextInputWidget::handleEventCurrent(sf::Event &event)
{
//bool handled{ ChildWidget::handleEvent(event) };/*||
// m_scrollable->handleEventWidget(event) };*/
// Check if actual Widget is focused
if (event.type == sf::Event::MouseButtonPressed)
{
sf::Vector2f mousePos{ (float) event.mouseButton.x,
(float) event.mouseButton.y };
bool isMouseInShownArea{ getShownArea().contains(mousePos) };
bool intersecting{ isIntersecting(mousePos) };
if (isMouseInShownArea && intersecting)
{
m_isFocused = true;
}
else
{
m_isFocused = false;
}
}
if (event.type == sf::Event::KeyPressed && m_isFocused)
{
switch (event.key.code)
{
case sf::Keyboard::Left:
if (m_cursorPos > 0)
{
m_cursorPos--;
}
// when cursor is moved it should be drawn so we reset its status
resetCursorStatus();
adjustShownText();
m_cursor.setPosition(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
return true;
case sf::Keyboard::Right:
if (m_cursorPos < m_currentText.length())
{
m_cursorPos++;
}
resetCursorStatus();
adjustShownText();
m_cursor.setPosition
(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
return true;
default: break;
}
}
// If Widget is focused and Text entered, handle entered text
if (m_isFocused && event.type == sf::Event::TextEntered)
{
// To handle umlauts and other 'exotic' chars we use widestring
// and wide char
//std::wstring actualTxt{ m_text.getString().toWideString() };
wchar_t c{ static_cast<wchar_t>(event.text.unicode) };
std::cout << "Entered: " << c << std::endl;
switch (c)
{
// Backspace
case 8:
if (m_currentText.length() > 0)
{
// Remove chars right of cursor when there are chars
if (m_cursorPos > 0 && m_cursorPos < m_currentText.length())
{
m_currentText.erase(m_cursorPos - 1, 1);
m_cursorPos--;
}
// When cursos is at the end of the text, p
// place cursor behind char which we want to delete,
else if (m_cursorPos == m_currentText.length())
{
// Delete last char
m_currentText.pop_back();
m_cursorPos--;
}
}
break;
// Delete Pressed
case 127:
if (m_currentText.length() > 0 &&
m_cursorPos < m_currentText.length())
{
m_currentText.erase(m_cursorPos, 1);
}
break;
// Enter key
case 13: m_currentText.insert(m_cursorPos, L"\n"); m_cursorPos++; break;
// Add char to text
default: m_currentText.insert(m_cursorPos, std::wstring() + c); m_cursorPos++;
}
resetCursorStatus();
m_shownText = m_currentText;
m_text->setText(m_shownText);
adjustShownText();
m_cursor.setPosition(m_text->findCharacterPos(m_cursorPos + m_lBreaksBefCur));
m_scrollable->recalculateScroll();
m_scrollable->scrollToRight();
m_scrollable->scrollToBottom();
return true;
}
return false;
//return handled;
}
void gsf::TextInputWidget::adjustShownText()
{
if (!m_scrollable->isHorizontalScrollEnabled())
{
m_lBreaksBefCur = 0;
std::wstring shownString{ L"" };
// The chars which are in the actual line
unsigned int charCntLine{ 0 };
// The total width of all chars in the current line
float lineWidth{ 0.f };
for (unsigned int i{ 0 }; i < m_currentText.size(); i++)
{
wchar_t c{ m_currentText[i] };
// Width of the current char
float cWidth { m_text->getFont().getGlyph(c, m_text->getCharacterSize(),
false).advance };
lineWidth += cWidth;
// When Text is out of scrollable widget, we have to add a new line
if (lineWidth > m_scrollable->getWidth())
{
if (i < m_cursorPos)
{
// We have to increase the "line breaks befor cursor" counter
// so we add the cursor later on the right position
m_lBreaksBefCur++;
}
//shownString += m_currentText.substr(i - charCntLine, charCntLine);
// Add new line
shownString += L"\n";
// add the char with which the line was to wide in the new line
shownString += c;
// We have added the char c in the new line, so we have now 1 char in the current line
charCntLine = 1;
lineWidth = cWidth;
}
else
{
charCntLine++;
shownString += c;
}
}
m_shownText = shownString;
m_text->setText(m_shownText);
}
}
void gsf::TextInputWidget::resetCursorStatus()
{
m_lastBlinkTime = 0.f;
m_isCursorShown = true;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2011 Google
// 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.
//
// This model implements a simple jobshop problem.
//
// A jobshop is a standard scheduling problem where you must schedule a
// set of jobs on a set of machines. Each job is a sequence of tasks
// (a task can only start when the preceding task finished), each of
// which occupies a single specific machine during a specific
// duration. Therefore, a job is simply given by a sequence of pairs
// (machine id, duration).
// The objective is to minimize the 'makespan', which is the duration
// between the start of the first task (across all machines) and the
// completion of the last task (across all machines).
//
// This will be modelled by sets of intervals variables (see class
// IntervalVar in constraint_solver/constraint_solver.h), one per
// task, representing the [start_time, end_time] of the task. Tasks
// in the same job will be linked by precedence constraints. Tasks on
// the same machine will be covered by Sequence constraints.
//
// Search will then be applied on the sequence constraints.
#include <cstdio>
#include <cstdlib>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/strtoint.h"
#include "base/file.h"
#include "base/split.h"
#include "constraint_solver/constraint_solver.h"
DEFINE_string(
data_file,
"",
"Required: input file description the scheduling problem to solve, "
"in our jssp format:\n"
" - the first line is \"instance <instance name>\"\n"
" - the second line is \"<number of jobs> <number of machines>\"\n"
" - then one line per job, with a single space-separated "
"list of \"<machine index> <duration>\"\n"
"note: jobs with one task are not supported");
DEFINE_int32(time_limit_in_ms, 0, "Time limit in ms, 0 means no limit.");
namespace operations_research {
// ----- JobShopData -----
// A JobShopData parses data files and stores all data internally for
// easy retrieval.
class JobShopData {
public:
// A task is the basic block of a jobshop.
struct Task {
Task(int j, int m, int d) : job_id(j), machine_id(m), duration(d) {}
int job_id;
int machine_id;
int duration;
};
JobShopData()
: name_(""),
machine_count_(0),
job_count_(0),
horizon_(0),
current_job_index_(0) {}
~JobShopData() {}
// Parses a file in jssp format and loads the model. See the flag
// --data_file for a description of the format. Note that the format
// is only partially checked: bad inputs might cause undefined
// behavior.
void Load(const string& filename) {
const int kMaxLineLength = 1024;
File* const data_file = File::Open(filename, "r");
scoped_array<char> line(new char[kMaxLineLength]);
while (data_file->ReadLine(line.get(), kMaxLineLength)) {
ProcessNewLine(line.get());
}
data_file->Close();
}
// The number of machines in the jobshop.
int machine_count() const { return machine_count_; }
// The number of jobs in the jobshop.
int job_count() const { return job_count_; }
// The name of the jobshop instance.
const string& name() const { return name_; }
// The horizon of the workshop (the sum of all durations), which is
// a trivial upper bound of the optimal make_span.
int horizon() const { return horizon_; }
// Returns the tasks of a job, ordered by precedence.
const std::vector<Task>& TasksOfJob(int job_id) const {
return all_tasks_[job_id];
}
private:
void ProcessNewLine(char* const line) {
// TODO(user): more robust logic to support single-task jobs.
static const char kWordDelimiters[] = " ";
std::vector<string> words;
SplitStringUsing(line, kWordDelimiters, &words);
if (words.size() == 2) {
if (words[0] == "instance") {
LOG(INFO) << "Name = " << words[1];
name_ = words[1];
} else {
job_count_ = atoi32(words[0]);
machine_count_ = atoi32(words[1]);
CHECK_GT(machine_count_, 0);
CHECK_GT(job_count_, 0);
LOG(INFO) << machine_count_ << " machines and "
<< job_count_ << " jobs";
all_tasks_.resize(job_count_);
}
}
if (words.size() > 2 && machine_count_ != 0) {
CHECK_EQ(words.size(), machine_count_ * 2);
for (int i = 0; i < machine_count_; ++i) {
const int machine_id = atoi32(words[2 * i]);
const int duration = atoi32(words[2 * i + 1]);
AddTask(current_job_index_, machine_id, duration);
}
current_job_index_++;
}
}
void AddTask(int job_id, int machine_id, int duration) {
all_tasks_[job_id].push_back(Task(job_id, machine_id, duration));
horizon_ += duration;
}
string name_;
int machine_count_;
int job_count_;
int horizon_;
std::vector<std::vector<Task> > all_tasks_;
int current_job_index_;
};
void Jobshop(const JobShopData& data) {
Solver solver("jobshop");
const int machine_count = data.machine_count();
const int job_count = data.job_count();
const int horizon = data.horizon();
// ----- Creates all Intervals and vars -----
// Stores all tasks attached interval variables per job.
std::vector<std::vector<IntervalVar*> > jobs_to_tasks(job_count);
// machines_to_tasks stores the same interval variables as above, but
// grouped my machines instead of grouped by jobs.
std::vector<std::vector<IntervalVar*> > machines_to_tasks(machine_count);
// Creates all individual interval variables.
for (int job_id = 0; job_id < job_count; ++job_id) {
const std::vector<JobShopData::Task>& tasks = data.TasksOfJob(job_id);
for (int task_index = 0; task_index < tasks.size(); ++task_index) {
const JobShopData::Task& task = tasks[task_index];
CHECK_EQ(job_id, task.job_id);
const string name = StringPrintf("J%dM%dI%dD%d",
task.job_id,
task.machine_id,
task_index,
task.duration);
IntervalVar* const one_task =
solver.MakeFixedDurationIntervalVar(0,
horizon,
task.duration,
false,
name);
jobs_to_tasks[task.job_id].push_back(one_task);
machines_to_tasks[task.machine_id].push_back(one_task);
}
}
// ----- Creates model -----
// Creates precedences inside jobs.
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
for (int task_index = 0; task_index < task_count - 1; ++task_index) {
IntervalVar* const t1 = jobs_to_tasks[job_id][task_index];
IntervalVar* const t2 = jobs_to_tasks[job_id][task_index + 1];
Constraint* const prec =
solver.MakeIntervalVarRelation(t2, Solver::STARTS_AFTER_END, t1);
solver.AddConstraint(prec);
}
}
// Adds disjunctive constraints on unary resources.
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
solver.AddConstraint(
solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id]));
}
// Creates sequences variables on machines. A sequence variable is a
// dedicated variable whose job is to sequence interval variables.
std::vector<SequenceVar*> all_sequences;
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
const string name = StringPrintf("Machine_%d", machine_id);
SequenceVar* const sequence =
solver.MakeSequenceVar(machines_to_tasks[machine_id], name);
all_sequences.push_back(sequence);
}
// Creates array of end_times of jobs.
std::vector<IntVar*> all_ends;
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
IntervalVar* const task = jobs_to_tasks[job_id][task_count - 1];
all_ends.push_back(task->EndExpr()->Var());
}
// Objective: minimize the makespan (maximum end times of all tasks)
// of the problem.
IntVar* const objective_var = solver.MakeMax(all_ends)->Var();
OptimizeVar* const objective_monitor = solver.MakeMinimize(objective_var, 1);
// ----- Search monitors and decision builder -----
// This decision builder will rank all tasks on all machines.
DecisionBuilder* const sequence_phase =
solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT);
// After the ranking of tasks, the schedule is still loose and any
// task can be postponed at will. But, because the problem is now a PERT
// (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique),
// we can schedule each task at its earliest start time. This is
// conveniently done by fixing the objective variable to its
// minimum value.
DecisionBuilder* const obj_phase =
solver.MakePhase(objective_var,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
// The main decision builder (ranks all tasks, then fixes the
// objective_variable).
DecisionBuilder* const main_phase =
solver.Compose(sequence_phase, obj_phase);
// Search log.
const int kLogFrequency = 1000000;
SearchMonitor* const search_log =
solver.MakeSearchLog(kLogFrequency, objective_monitor);
SearchLimit* limit = NULL;
if (FLAGS_time_limit_in_ms > 0) {
limit = solver.MakeTimeLimit(FLAGS_time_limit_in_ms);
}
// Search.
solver.Solve(main_phase, search_log, objective_monitor, limit);
}
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a simple job shop optimization "
"output besides the debug LOGs of the solver.";
int main(int argc, char **argv) {
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_data_file.empty()) {
LOG(INFO) << "Please supply a data file with --data_file=";
return 0;
}
operations_research::JobShopData data;
data.Load(FLAGS_data_file);
operations_research::Jobshop(data);
return 0;
}
<commit_msg>improve error handling<commit_after>// Copyright 2010-2011 Google
// 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.
//
// This model implements a simple jobshop problem.
//
// A jobshop is a standard scheduling problem where you must schedule a
// set of jobs on a set of machines. Each job is a sequence of tasks
// (a task can only start when the preceding task finished), each of
// which occupies a single specific machine during a specific
// duration. Therefore, a job is simply given by a sequence of pairs
// (machine id, duration).
// The objective is to minimize the 'makespan', which is the duration
// between the start of the first task (across all machines) and the
// completion of the last task (across all machines).
//
// This will be modelled by sets of intervals variables (see class
// IntervalVar in constraint_solver/constraint_solver.h), one per
// task, representing the [start_time, end_time] of the task. Tasks
// in the same job will be linked by precedence constraints. Tasks on
// the same machine will be covered by Sequence constraints.
//
// Search will then be applied on the sequence constraints.
#include <cstdio>
#include <cstdlib>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/strtoint.h"
#include "base/file.h"
#include "base/split.h"
#include "constraint_solver/constraint_solver.h"
DEFINE_string(
data_file,
"",
"Required: input file description the scheduling problem to solve, "
"in our jssp format:\n"
" - the first line is \"instance <instance name>\"\n"
" - the second line is \"<number of jobs> <number of machines>\"\n"
" - then one line per job, with a single space-separated "
"list of \"<machine index> <duration>\"\n"
"note: jobs with one task are not supported");
DEFINE_int32(time_limit_in_ms, 0, "Time limit in ms, 0 means no limit.");
namespace operations_research {
// ----- JobShopData -----
// A JobShopData parses data files and stores all data internally for
// easy retrieval.
class JobShopData {
public:
// A task is the basic block of a jobshop.
struct Task {
Task(int j, int m, int d) : job_id(j), machine_id(m), duration(d) {}
int job_id;
int machine_id;
int duration;
};
JobShopData()
: name_(""),
machine_count_(0),
job_count_(0),
horizon_(0),
current_job_index_(0) {}
~JobShopData() {}
// Parses a file in jssp format and loads the model. See the flag
// --data_file for a description of the format. Note that the format
// is only partially checked: bad inputs might cause undefined
// behavior.
void Load(const string& filename) {
const int kMaxLineLength = 1024;
File* const data_file = File::Open(filename, "r");
scoped_array<char> line(new char[kMaxLineLength]);
while (data_file->ReadLine(line.get(), kMaxLineLength)) {
ProcessNewLine(line.get());
}
data_file->Close();
}
// The number of machines in the jobshop.
int machine_count() const { return machine_count_; }
// The number of jobs in the jobshop.
int job_count() const { return job_count_; }
// The name of the jobshop instance.
const string& name() const { return name_; }
// The horizon of the workshop (the sum of all durations), which is
// a trivial upper bound of the optimal make_span.
int horizon() const { return horizon_; }
// Returns the tasks of a job, ordered by precedence.
const std::vector<Task>& TasksOfJob(int job_id) const {
return all_tasks_[job_id];
}
private:
void ProcessNewLine(char* const line) {
// TODO(user): more robust logic to support single-task jobs.
static const char kWordDelimiters[] = " ";
std::vector<string> words;
SplitStringUsing(line, kWordDelimiters, &words);
if (words.size() == 2) {
if (words[0] == "instance") {
LOG(INFO) << "Name = " << words[1];
name_ = words[1];
} else {
job_count_ = atoi32(words[0]);
machine_count_ = atoi32(words[1]);
CHECK_GT(machine_count_, 0);
CHECK_GT(job_count_, 0);
LOG(INFO) << machine_count_ << " machines and "
<< job_count_ << " jobs";
all_tasks_.resize(job_count_);
}
}
if (words.size() > 2 && machine_count_ != 0) {
CHECK_EQ(words.size(), machine_count_ * 2);
for (int i = 0; i < machine_count_; ++i) {
const int machine_id = atoi32(words[2 * i]);
const int duration = atoi32(words[2 * i + 1]);
AddTask(current_job_index_, machine_id, duration);
}
current_job_index_++;
}
}
void AddTask(int job_id, int machine_id, int duration) {
all_tasks_[job_id].push_back(Task(job_id, machine_id, duration));
horizon_ += duration;
}
string name_;
int machine_count_;
int job_count_;
int horizon_;
std::vector<std::vector<Task> > all_tasks_;
int current_job_index_;
};
void Jobshop(const JobShopData& data) {
Solver solver("jobshop");
const int machine_count = data.machine_count();
const int job_count = data.job_count();
const int horizon = data.horizon();
// ----- Creates all Intervals and vars -----
// Stores all tasks attached interval variables per job.
std::vector<std::vector<IntervalVar*> > jobs_to_tasks(job_count);
// machines_to_tasks stores the same interval variables as above, but
// grouped my machines instead of grouped by jobs.
std::vector<std::vector<IntervalVar*> > machines_to_tasks(machine_count);
// Creates all individual interval variables.
for (int job_id = 0; job_id < job_count; ++job_id) {
const std::vector<JobShopData::Task>& tasks = data.TasksOfJob(job_id);
for (int task_index = 0; task_index < tasks.size(); ++task_index) {
const JobShopData::Task& task = tasks[task_index];
CHECK_EQ(job_id, task.job_id);
const string name = StringPrintf("J%dM%dI%dD%d",
task.job_id,
task.machine_id,
task_index,
task.duration);
IntervalVar* const one_task =
solver.MakeFixedDurationIntervalVar(0,
horizon,
task.duration,
false,
name);
jobs_to_tasks[task.job_id].push_back(one_task);
machines_to_tasks[task.machine_id].push_back(one_task);
}
}
// ----- Creates model -----
// Creates precedences inside jobs.
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
for (int task_index = 0; task_index < task_count - 1; ++task_index) {
IntervalVar* const t1 = jobs_to_tasks[job_id][task_index];
IntervalVar* const t2 = jobs_to_tasks[job_id][task_index + 1];
Constraint* const prec =
solver.MakeIntervalVarRelation(t2, Solver::STARTS_AFTER_END, t1);
solver.AddConstraint(prec);
}
}
// Adds disjunctive constraints on unary resources.
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
solver.AddConstraint(
solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id]));
}
// Creates sequences variables on machines. A sequence variable is a
// dedicated variable whose job is to sequence interval variables.
std::vector<SequenceVar*> all_sequences;
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
const string name = StringPrintf("Machine_%d", machine_id);
SequenceVar* const sequence =
solver.MakeSequenceVar(machines_to_tasks[machine_id], name);
all_sequences.push_back(sequence);
}
// Creates array of end_times of jobs.
std::vector<IntVar*> all_ends;
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
IntervalVar* const task = jobs_to_tasks[job_id][task_count - 1];
all_ends.push_back(task->EndExpr()->Var());
}
// Objective: minimize the makespan (maximum end times of all tasks)
// of the problem.
IntVar* const objective_var = solver.MakeMax(all_ends)->Var();
OptimizeVar* const objective_monitor = solver.MakeMinimize(objective_var, 1);
// ----- Search monitors and decision builder -----
// This decision builder will rank all tasks on all machines.
DecisionBuilder* const sequence_phase =
solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT);
// After the ranking of tasks, the schedule is still loose and any
// task can be postponed at will. But, because the problem is now a PERT
// (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique),
// we can schedule each task at its earliest start time. This is
// conveniently done by fixing the objective variable to its
// minimum value.
DecisionBuilder* const obj_phase =
solver.MakePhase(objective_var,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
// The main decision builder (ranks all tasks, then fixes the
// objective_variable).
DecisionBuilder* const main_phase =
solver.Compose(sequence_phase, obj_phase);
// Search log.
const int kLogFrequency = 1000000;
SearchMonitor* const search_log =
solver.MakeSearchLog(kLogFrequency, objective_monitor);
SearchLimit* limit = NULL;
if (FLAGS_time_limit_in_ms > 0) {
limit = solver.MakeTimeLimit(FLAGS_time_limit_in_ms);
}
// Search.
solver.Solve(main_phase, search_log, objective_monitor, limit);
}
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a simple job shop optimization "
"output besides the debug LOGs of the solver.";
int main(int argc, char **argv) {
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_data_file.empty()) {
LOG(FATAL) << "Please supply a data file with --data_file=";
}
operations_research::JobShopData data;
data.Load(FLAGS_data_file);
operations_research::Jobshop(data);
return 0;
}
<|endoftext|> |
<commit_before>#include "Chimera_Win.h"
#include <boost/algorithm/string/replace.hpp>
#include <QtCore/qglobal.h>
#include <QtPlugin>
#include <QQmlContext.h>
#include <QtQml/QQml.h>
#include <QtEndian>
#include <QAbstractNativeEventFilter>
#include <QScreen>
#include "QmlVlc/QmlVlcSurfacePlayerProxy.h"
#ifdef QT_STATIC
Q_IMPORT_PLUGIN( QWindowsIntegrationPlugin );
Q_IMPORT_PLUGIN( QtQuick2Plugin );
Q_IMPORT_PLUGIN( QtQuickLayoutsPlugin );
#endif
static std::string qtConf_resource_data;
static const unsigned char qtConf_resource_name[] = {
// qt
0x0,0x2,
0x0,0x0,0x7,0x84,
0x0,0x71,
0x0,0x74,
// etc
0x0,0x3,
0x0,0x0,0x6c,0xa3,
0x0,0x65,
0x0,0x74,0x0,0x63,
// qt.conf
0x0,0x7,
0x8,0x74,0xa6,0xa6,
0x0,0x71,
0x0,0x74,0x0,0x2e,0x0,0x63,0x0,0x6f,0x0,0x6e,0x0,0x66,
};
static const unsigned char qtConf_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
// :/qt
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2,
// :/qt/etc
0x0,0x0,0x0,0xa,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x3,
// :/qt/etc/qt.conf
0x0,0x0,0x0,0x16,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
};
QT_BEGIN_NAMESPACE
extern Q_CORE_EXPORT
bool qRegisterResourceData( int, const unsigned char*,
const unsigned char* ,
const unsigned char* );
extern Q_CORE_EXPORT
bool qUnregisterResourceData( int, const unsigned char*,
const unsigned char*,
const unsigned char* );
QT_END_NAMESPACE
extern std::string g_dllPath;
////////////////////////////////////////////////////////////////////////////////
//EraseBkgndEater class
////////////////////////////////////////////////////////////////////////////////
//implements workaround of incorrect WM_ERASEBKGND message handling ( at least on Qt 5.3.2 )
class EraseBkgndEater : public QAbstractNativeEventFilter
{
public:
bool nativeEventFilter( const QByteArray&, void* message, long* result ) override
{
MSG* winMessage = (MSG*)message;
if( winMessage->message == WM_ERASEBKGND ) {
*result = TRUE;
return true;
}
return false;
}
};
////////////////////////////////////////////////////////////////////////////////
//Chimera_Win class
////////////////////////////////////////////////////////////////////////////////
void Chimera_Win::StaticInitialize()
{
#ifndef _DEBUG
if( !qApp ) {
std::string qtPrefix = g_dllPath + "/../";
boost::algorithm::replace_all( qtPrefix, "\\", "/" );
qtConf_resource_data = "4321[Paths]\n";
qtConf_resource_data += "Prefix = " + qtPrefix + "\n";
uint32_t qtConfSize = qtConf_resource_data.size() - sizeof( qtConfSize );
uint32_t qtConfSwappedSize = qToBigEndian( qtConfSize );
memcpy( &qtConf_resource_data[0], &qtConfSwappedSize, sizeof( qtConfSwappedSize ) );
qRegisterResourceData( 0x01, qtConf_resource_struct,
qtConf_resource_name,
(const unsigned char*)qtConf_resource_data.data() );
}
#endif
QmlChimera::StaticInitialize();
assert( qApp );
if( qApp )
qApp->installNativeEventFilter( new EraseBkgndEater );
}
void Chimera_Win::StaticDeinitialize()
{
#ifndef _DEBUG
qUnregisterResourceData(0x01, qtConf_resource_struct,
qtConf_resource_name,
(const unsigned char*)qtConf_resource_data.data() );
#endif
}
Chimera_Win::Chimera_Win()
{
#ifdef QT_STATIC
qmlProtectModule( "QtQuick", 2 );
qmlProtectModule( "QtQuick.Layouts", 1 );
#endif
}
Chimera_Win::~Chimera_Win()
{
}
bool Chimera_Win::onWindowAttached( FB::AttachedEvent* evt, FB::PluginWindowWin* w )
{
m_pluginWindow.reset( QWindow::fromWinId( (WId) w->getHWND() ) );
vlc_open();
m_quickViewPtr.reset( new QQuickView( m_pluginWindow.data() ) );
m_quickViewPtr->setTitle( QStringLiteral( "WebChimera" ) );
m_quickViewPtr->setResizeMode( QQuickView::SizeRootObjectToView );
m_quickViewPtr->setFlags( m_quickViewPtr->flags() | Qt::FramelessWindowHint );
QQmlContext* context = m_quickViewPtr->rootContext();
m_qmlVlcPlayer = new QmlVlcSurfacePlayerProxy( (vlc::player*)this, m_quickViewPtr.data() );
m_qmlVlcPlayer->classBegin();
//have to call apply_player_options()
//after QmlVlcSurfacePlayerProxy::classBegin
//to allow attach Proxy's vmem to plugin before play
apply_player_options();
setQml();
//simulate resize
onWindowResized( 0, w );
return false;
}
bool Chimera_Win::onWindowDetached( FB::DetachedEvent*, FB::PluginWindowWin* )
{
m_quickViewPtr.reset();
m_pluginWindow.reset();
return false;
}
bool Chimera_Win::onWindowResized( FB::ResizedEvent*, FB::PluginWindowWin* w )
{
const int newWidth = w->getWindowWidth();
const int newHeight = w->getWindowHeight();
if( m_quickViewPtr && !is_fullscreen() ) {
if( newWidth > 0 && newHeight > 0 ) {
if( !m_quickViewPtr->isVisible() )
m_quickViewPtr->show();
m_quickViewPtr->setX( 0 ); m_quickViewPtr->setY( 0 );
m_quickViewPtr->resize( newWidth, newHeight );
} else
m_quickViewPtr->hide();
}
return false;
}
bool Chimera_Win::onWindowsEvent( FB::WindowsEvent* event, FB::PluginWindowWin* w )
{
if( WM_SETCURSOR == event->uMsg ) {
event->lRes = FALSE; //allow change cursor by child windows
return true;
}
return false;
}
bool Chimera_Win::is_fullscreen()
{
if( m_quickViewPtr )
return 0 != ( m_quickViewPtr->visibility() & QWindow::FullScreen );
return false;
}
QScreen* ScreenFromWindow( FB::PluginWindowWin* w )
{
POINT topLeft = { 0, 0 };
ClientToScreen( w->getHWND(), &topLeft );
QRect winRect = QRect( 0, 0, w->getWindowWidth(), w->getWindowHeight() );
winRect.moveTo( topLeft.x, topLeft.y );
QPoint winCenter = winRect.center();
QList<QScreen*> screens = QGuiApplication::screens();
QScreen* bestScreen = QGuiApplication::primaryScreen();
unsigned intersectedArea = 0;
for( auto* screen : screens ) {
QRect screenRect = screen->geometry();
if( screenRect.contains( winCenter ) ) {
return screen;
} else {
QRect ir = screenRect.intersected( winRect );
unsigned ia = ir.width() * ir.height();
if( ir.isValid() && ia > intersectedArea )
bestScreen = screen;
}
}
return bestScreen;
}
void Chimera_Win::set_fullscreen( bool fs )
{
if( m_quickViewPtr && m_pluginWindow ) {
if( fs && !is_fullscreen() ) {
QScreen* screen = ScreenFromWindow( static_cast<FB::PluginWindowWin*>( GetWindow() ) );
m_quickViewPtr->setParent( 0 );
m_quickViewPtr->setScreen( screen );
m_quickViewPtr->showFullScreen();
Q_EMIT fullscreenChanged( true );
} else if( !fs && is_fullscreen() ) {
m_quickViewPtr->showNormal();
m_quickViewPtr->setParent( m_pluginWindow.data() );
onWindowResized( 0, static_cast<FB::PluginWindowWin*>( GetWindow() ) );
m_quickViewPtr->requestActivate();
Q_EMIT fullscreenChanged( false );
}
}
}
<commit_msg>really fix fullscreen on second screen issue<commit_after>#include "Chimera_Win.h"
#include <boost/algorithm/string/replace.hpp>
#include <QtCore/qglobal.h>
#include <QtPlugin>
#include <QQmlContext.h>
#include <QtQml/QQml.h>
#include <QtEndian>
#include <QAbstractNativeEventFilter>
#include <QScreen>
#include "QmlVlc/QmlVlcSurfacePlayerProxy.h"
#ifdef QT_STATIC
Q_IMPORT_PLUGIN( QWindowsIntegrationPlugin );
Q_IMPORT_PLUGIN( QtQuick2Plugin );
Q_IMPORT_PLUGIN( QtQuickLayoutsPlugin );
#endif
static std::string qtConf_resource_data;
static const unsigned char qtConf_resource_name[] = {
// qt
0x0,0x2,
0x0,0x0,0x7,0x84,
0x0,0x71,
0x0,0x74,
// etc
0x0,0x3,
0x0,0x0,0x6c,0xa3,
0x0,0x65,
0x0,0x74,0x0,0x63,
// qt.conf
0x0,0x7,
0x8,0x74,0xa6,0xa6,
0x0,0x71,
0x0,0x74,0x0,0x2e,0x0,0x63,0x0,0x6f,0x0,0x6e,0x0,0x66,
};
static const unsigned char qtConf_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
// :/qt
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2,
// :/qt/etc
0x0,0x0,0x0,0xa,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x3,
// :/qt/etc/qt.conf
0x0,0x0,0x0,0x16,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
};
QT_BEGIN_NAMESPACE
extern Q_CORE_EXPORT
bool qRegisterResourceData( int, const unsigned char*,
const unsigned char* ,
const unsigned char* );
extern Q_CORE_EXPORT
bool qUnregisterResourceData( int, const unsigned char*,
const unsigned char*,
const unsigned char* );
QT_END_NAMESPACE
extern std::string g_dllPath;
////////////////////////////////////////////////////////////////////////////////
//EraseBkgndEater class
////////////////////////////////////////////////////////////////////////////////
//implements workaround of incorrect WM_ERASEBKGND message handling ( at least on Qt 5.3.2 )
class EraseBkgndEater : public QAbstractNativeEventFilter
{
public:
bool nativeEventFilter( const QByteArray&, void* message, long* result ) override
{
MSG* winMessage = (MSG*)message;
if( winMessage->message == WM_ERASEBKGND ) {
*result = TRUE;
return true;
}
return false;
}
};
////////////////////////////////////////////////////////////////////////////////
//Chimera_Win class
////////////////////////////////////////////////////////////////////////////////
void Chimera_Win::StaticInitialize()
{
#ifndef _DEBUG
if( !qApp ) {
std::string qtPrefix = g_dllPath + "/../";
boost::algorithm::replace_all( qtPrefix, "\\", "/" );
qtConf_resource_data = "4321[Paths]\n";
qtConf_resource_data += "Prefix = " + qtPrefix + "\n";
uint32_t qtConfSize = qtConf_resource_data.size() - sizeof( qtConfSize );
uint32_t qtConfSwappedSize = qToBigEndian( qtConfSize );
memcpy( &qtConf_resource_data[0], &qtConfSwappedSize, sizeof( qtConfSwappedSize ) );
qRegisterResourceData( 0x01, qtConf_resource_struct,
qtConf_resource_name,
(const unsigned char*)qtConf_resource_data.data() );
}
#endif
QmlChimera::StaticInitialize();
assert( qApp );
if( qApp )
qApp->installNativeEventFilter( new EraseBkgndEater );
}
void Chimera_Win::StaticDeinitialize()
{
#ifndef _DEBUG
qUnregisterResourceData(0x01, qtConf_resource_struct,
qtConf_resource_name,
(const unsigned char*)qtConf_resource_data.data() );
#endif
}
Chimera_Win::Chimera_Win()
{
#ifdef QT_STATIC
qmlProtectModule( "QtQuick", 2 );
qmlProtectModule( "QtQuick.Layouts", 1 );
#endif
}
Chimera_Win::~Chimera_Win()
{
}
bool Chimera_Win::onWindowAttached( FB::AttachedEvent* evt, FB::PluginWindowWin* w )
{
m_pluginWindow.reset( QWindow::fromWinId( (WId) w->getHWND() ) );
vlc_open();
m_quickViewPtr.reset( new QQuickView( m_pluginWindow.data() ) );
m_quickViewPtr->setTitle( QStringLiteral( "WebChimera" ) );
m_quickViewPtr->setResizeMode( QQuickView::SizeRootObjectToView );
m_quickViewPtr->setFlags( m_quickViewPtr->flags() | Qt::FramelessWindowHint );
QQmlContext* context = m_quickViewPtr->rootContext();
m_qmlVlcPlayer = new QmlVlcSurfacePlayerProxy( (vlc::player*)this, m_quickViewPtr.data() );
m_qmlVlcPlayer->classBegin();
//have to call apply_player_options()
//after QmlVlcSurfacePlayerProxy::classBegin
//to allow attach Proxy's vmem to plugin before play
apply_player_options();
setQml();
//simulate resize
onWindowResized( 0, w );
return false;
}
bool Chimera_Win::onWindowDetached( FB::DetachedEvent*, FB::PluginWindowWin* )
{
m_quickViewPtr.reset();
m_pluginWindow.reset();
return false;
}
bool Chimera_Win::onWindowResized( FB::ResizedEvent*, FB::PluginWindowWin* w )
{
const int newWidth = w->getWindowWidth();
const int newHeight = w->getWindowHeight();
if( m_quickViewPtr && !is_fullscreen() ) {
if( newWidth > 0 && newHeight > 0 ) {
if( !m_quickViewPtr->isVisible() )
m_quickViewPtr->show();
m_quickViewPtr->setX( 0 ); m_quickViewPtr->setY( 0 );
m_quickViewPtr->resize( newWidth, newHeight );
} else
m_quickViewPtr->hide();
}
return false;
}
bool Chimera_Win::onWindowsEvent( FB::WindowsEvent* event, FB::PluginWindowWin* w )
{
if( WM_SETCURSOR == event->uMsg ) {
event->lRes = FALSE; //allow change cursor by child windows
return true;
}
return false;
}
bool Chimera_Win::is_fullscreen()
{
if( m_quickViewPtr )
return 0 != ( m_quickViewPtr->visibility() & QWindow::FullScreen );
return false;
}
QScreen* ScreenFromWindow( FB::PluginWindowWin* w )
{
POINT topLeft = { 0, 0 };
ClientToScreen( w->getHWND(), &topLeft );
QRect winRect = QRect( 0, 0, w->getWindowWidth(), w->getWindowHeight() );
winRect.moveTo( topLeft.x, topLeft.y );
QPoint winCenter = winRect.center();
QList<QScreen*> screens = QGuiApplication::screens();
QScreen* bestScreen = QGuiApplication::primaryScreen();
unsigned intersectedArea = 0;
for( auto* screen : screens ) {
QRect screenRect = screen->geometry();
if( screenRect.contains( winCenter ) ) {
return screen;
} else {
QRect ir = screenRect.intersected( winRect );
unsigned ia = ir.width() * ir.height();
if( ir.isValid() && ia > intersectedArea )
bestScreen = screen;
}
}
return bestScreen;
}
void Chimera_Win::set_fullscreen( bool fs )
{
if( m_quickViewPtr && m_pluginWindow ) {
if( fs && !is_fullscreen() ) {
QScreen* screen = ScreenFromWindow( static_cast<FB::PluginWindowWin*>( GetWindow() ) );
m_quickViewPtr->hide();
m_quickViewPtr->setParent( 0 );
m_quickViewPtr->setScreen( screen );
m_quickViewPtr->setGeometry( screen->geometry() );
m_quickViewPtr->showFullScreen();
Q_EMIT fullscreenChanged( true );
} else if( !fs && is_fullscreen() ) {
m_quickViewPtr->showNormal();
m_quickViewPtr->setParent( m_pluginWindow.data() );
onWindowResized( 0, static_cast<FB::PluginWindowWin*>( GetWindow() ) );
m_quickViewPtr->requestActivate();
Q_EMIT fullscreenChanged( false );
}
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.