<commit_before>#define THRUST_DEBUG 1

#include "lcp/ChLcpVariablesGeneric.h"
#include "lcp/ChLcpVariablesBody.h"
#include "lcp/ChLcpConstraintTwoGeneric.h"
#include "lcp/ChLcpSystemDescriptor.h"
#include "lcp/ChLcpIterativeSOR.h"
#include "lcp/ChLcpIterativePMINRES.h"
#include "lcp/ChLcpIterativeBB.h"
#include "lcp/ChLcpSimplexSolver.h"
#include "core/ChLinearAlgebra.h"
#include "physics/ChSystemOpenMP.h"
#include "assets/ChSphereShape.h"
#include "physics/ChApidll.h"
#include "physics/ChSystem.h"
#include "lcp/ChLcpIterativeMINRES.h"
#include "core/ChRealtimeStep.h"
#include "lcp/ChLcpIterativeSOR.h"
#include "lcp/ChLcpIterativeJacobi.h"
#include "collision/ChCModelBullet.h"
#include "collision/ChCCollisionSystemBullet.h"
#include "physics/ChContactContainer.h"
// #include "unit_OPENGL/ChOpenGL.h"
#include "unit_POSTPROCESS/ChMitsubaRender.h"

#include "unit_GPU/ChSystemGPU.h"

// Remember to use the namespace 'chrono' because all classes
// of Chrono::Engine belong to this namespace and its children...

using namespace chrono;
using namespace postprocess;
//#define CHBODYSHAREDPTR ChSharedBodyPtr
//#define CHBODY ChBody
//#define CHCOLLISIONSYS ChCollisionSystemBullet
//#define CHLCPDESC ChLcpSystemDescriptor
//#define CHCONTACTCONT ChContactContainer
//#define CHSOLVER ChLcpIterativeJacobi
//#define CHMODEL ChModelBullet
//#define CHSYS ChSystem
#define CHBODYSHAREDPTR ChSharedBodyGPUPtr
#define CHBODY ChBodyGPU
#define CHCOLLISIONSYS ChCollisionSystemGPU
#define CHLCPDESC ChLcpSystemDescriptorGPU
#define CHCONTACTCONT ChContactContainerGPUsimple
#define CHSOLVER ChLcpIterativeJacobi
#define CHMODEL ChModelGPU
#define CHSYS ChSystemGPU
uint num_objects=0;
void dump_matricies(ChLcpSystemDescriptor& mdescriptor) {
	chrono::ChSparseMatrix mdM;
	chrono::ChSparseMatrix mdCq;
	chrono::ChSparseMatrix mdE;
	chrono::ChMatrixDynamic<double> mdf;
	chrono::ChMatrixDynamic<double> mdb;
	chrono::ChMatrixDynamic<double> mdfric;
	mdescriptor.ConvertToMatrixForm(&mdCq, &mdM, &mdE, &mdf, &mdb, &mdfric);
	chrono::ChStreamOutAsciiFile file_M("dump_M.dat");
	mdM.StreamOUTsparseMatlabFormat(file_M);
	chrono::ChStreamOutAsciiFile file_Cq("dump_Cq.dat");
	mdCq.StreamOUTsparseMatlabFormat(file_Cq);
	chrono::ChStreamOutAsciiFile file_E("dump_E.dat");
	mdE.StreamOUTsparseMatlabFormat(file_E);
	chrono::ChStreamOutAsciiFile file_f("dump_f.dat");
	mdf.StreamOUTdenseMatlabFormat(file_f);
	chrono::ChStreamOutAsciiFile file_b("dump_b.dat");
	mdb.StreamOUTdenseMatlabFormat(file_b);
	chrono::ChStreamOutAsciiFile file_fric("dump_fric.dat");
	mdfric.StreamOUTdenseMatlabFormat(file_fric);
}
template<class T>
void RunTimeStep(T* mSys, const int frame){
	Vector lpos(0, 0, 0);
	ChQuaternion<> quat(1, 0, 0, 0);
	CHBODYSHAREDPTR sphere;

    if(frame%10==0){
    for (int i = 0; i < 10; i++) {
		sphere = CHBODYSHAREDPTR(new CHBODY);
        Vector pos=Vector((rand() % 10000 / 10000.0 - .5), (.5), (rand() % 10000 / 10000.0 - .5));
		InitObject(sphere, 1.0, pos*10 , quat, 1, 1, 0, true, false, 32, 17+num_objects);
		AddCollisionGeometry(sphere, SPHERE, Vector(.3, .3, .3), lpos, quat);
		FinalizeObject(sphere, (CHSYS*) mSys);
		num_objects++;
	}
    }
}

int main(int argc, char* argv[]) {
	feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
	//cudaSetDevice(0);
	omp_set_num_threads(6);
    CHSYS* mSys = new CHSYS();
	CHLCPDESC *mdescriptor = new CHLCPDESC();
	CHCONTACTCONT *mcontactcontainer = new CHCONTACTCONT();
	CHCOLLISIONSYS *mcollisionengine = new CHCOLLISIONSYS();
	//ChLcpIterativeJacobi *msolver = new ChLcpIterativeJacobi();
	//ChLcpIterativeSOR *msolver = new ChLcpIterativeSOR();
	//ChLcpIterativeMINRES *msolver = new ChLcpIterativeMINRES();
	//ChLcpIterativePMINRES *msolver = new ChLcpIterativePMINRES();
	//ChLcpIterativeBB *msolver = new ChLcpIterativeBB();

	mSys->ChangeLcpSystemDescriptor(mdescriptor);
	mSys->ChangeContactContainer(mcontactcontainer);
	//mSys->ChangeLcpSolverSpeed(msolver);
	mSys->ChangeCollisionSystem(mcollisionengine);

	mSys->SetIntegrationType(ChSystem::INT_ANITESCU);
	mSys->Set_G_acc(Vector(0, -9.80665, 0));

	Vector lpos(0, 0, 0);
	ChQuaternion<> quat(1, 0, 0, 0);
//	ChSharedBodyPtr sphere;
//	for (int i = 0; i < 1000; i++) {
//		sphere = ChSharedBodyPtr(new ChBody);
//		InitObject(sphere, 1.0, Vector((rand() % 10000 / 1000.0 - 5), (rand() % 10000 / 1000.0 - 5), (rand() % 10000 / 1000.0 - 5)), quat, 1, 1, 0, true, false, 32, 17 + i);
//		AddCollisionGeometry(sphere, SPHERE, Vector(.3, .3, .3), lpos, quat);
//		FinalizeObject(sphere, mSys);
//	}

	float mWallMu = 1, container_width = 7.0, container_thickness = .5, container_height = 7.0, wscale = 1;
	CHBODYSHAREDPTR L = CHBODYSHAREDPTR(new CHBODY);
	CHBODYSHAREDPTR R = CHBODYSHAREDPTR(new CHBODY);
	CHBODYSHAREDPTR F = CHBODYSHAREDPTR(new CHBODY);
	CHBODYSHAREDPTR B = CHBODYSHAREDPTR(new CHBODY);
	CHBODYSHAREDPTR BTM = CHBODYSHAREDPTR(new CHBODY);

	InitObject(L, 100000, Vector(-container_width + container_thickness, 0, 0), quat, mWallMu, mWallMu, 0, true, true, -20, -20);
	InitObject(R, 100000, Vector(container_width - container_thickness, 0, 0), quat, mWallMu, mWallMu, 0, true, true, -20, -20);
	InitObject(F, 100000, Vector(0, 0, -container_width + container_thickness), quat, mWallMu, mWallMu, 0, true, true, -20, -20);
	InitObject(B, 100000, Vector(0, 0, container_width - container_thickness), quat, mWallMu, mWallMu, 0, true, true, -20, -20);
	InitObject(BTM, 100000, Vector(0, -container_height + container_thickness, 0), quat, mWallMu, mWallMu, 0, true, true, -20, -20);

	AddCollisionGeometry(L, BOX, Vector(container_thickness, container_height, container_width), lpos, quat);
	AddCollisionGeometry(R, BOX, Vector(container_thickness, container_height, container_width), lpos, quat);
	AddCollisionGeometry(F, BOX, Vector(container_width * wscale, container_height, container_thickness), lpos, quat);
	AddCollisionGeometry(B, BOX, Vector(container_width * wscale, container_height, container_thickness), lpos, quat);
	AddCollisionGeometry(BTM, BOX, Vector(container_width * wscale, container_thickness , container_width), lpos, quat);

	FinalizeObject(L, mSys);
	FinalizeObject(R, mSys);
	FinalizeObject(F, mSys);
	FinalizeObject(B, mSys);
	FinalizeObject(BTM, mSys);

	mSys->SetStep(0.01);
// 	ChOpenGLManager * window_manager = new ChOpenGLManager();
// 	ChOpenGL openGLView(window_manager, mSys, 800, 600, 0, 0, "Test_Solvers");
//     openGLView.SetCustomCallback(RunTimeStep);
// 	openGLView.StartSpinning(window_manager);
// 	window_manager->CallGlutMainLoop();
//
//	//msolver->Solve(*mdescriptor,true);
//	//dump_matricies(*mdescriptor);
//	//ChLcpIterativePMINRES msolver_krylov(20, false, 0.00001);
//	//msolver_krylov.Solve(mdescriptor);
//
//    ChMitsubaRender output(mSys);
//
//	output.SetIntegrator("photonmapper");
//	output.SetIntegratorOption("integer", "maxDepth", "32");
//	output.SetFilm("ldrfilm");
//	output.SetFilmOption("integer", "height", "1200");
//	output.SetFilmOption("integer", "width", "1920");
//
//	output.camera_target = ChVector<>(0, 0, 0);
//	output.camera_origin = ChVector<>(0, 0, -10);
//	output.camera_up = ChVector<>(0, 1, 0);
//
//	output.SetDataFolder("data");
//	output.ExportScript("test.xml");
//    output.SetRenderFolder("render");
//    output.ExportDriver("driver.sh");

    int counter=0;

    while(counter<1000){
        RunTimeStep(mSys, counter);
        mSys->DoStepDynamics(.01);

        stringstream ss;
		ss << "data/" << counter << ".xml";
		//output.ExportData(ss.str());

       cout<<counter<<endl;
        counter++;
    }
	return 0;
}

<commit_msg>Fixed CG solver, added timers<commit_after>#define THRUST_DEBUG 1

#include "lcp/ChLcpVariablesGeneric.h"
#include "lcp/ChLcpVariablesBody.h"
#include "lcp/ChLcpConstraintTwoGeneric.h"
#include "lcp/ChLcpSystemDescriptor.h"
#include "lcp/ChLcpIterativeSOR.h"
#include "lcp/ChLcpIterativePMINRES.h"
#include "lcp/ChLcpIterativeBB.h"
#include "lcp/ChLcpSimplexSolver.h"
#include "core/ChLinearAlgebra.h"
#include "physics/ChSystemOpenMP.h"
#include "assets/ChSphereShape.h"
#include "physics/ChApidll.h"
#include "physics/ChSystem.h"
#include "lcp/ChLcpIterativeMINRES.h"
#include "core/ChRealtimeStep.h"
#include "lcp/ChLcpIterativeSOR.h"
#include "lcp/ChLcpIterativeJacobi.h"
#include "collision/ChCModelBullet.h"
#include "collision/ChCCollisionSystemBullet.h"
#include "physics/ChContactContainer.h"
// #include "unit_OPENGL/ChOpenGL.h"
#include "unit_POSTPROCESS/ChMitsubaRender.h"

#include "unit_GPU/ChSystemGPU.h"

// Remember to use the namespace 'chrono' because all classes
// of Chrono::Engine belong to this namespace and its children...

using namespace chrono;
using namespace postprocess;
//#define CHBODYSHAREDPTR ChSharedBodyPtr
//#define CHBODY ChBody
//#define CHCOLLISIONSYS ChCollisionSystemBullet
//#define CHLCPDESC ChLcpSystemDescriptor
//#define CHCONTACTCONT ChContactContainer
//#define CHSOLVER ChLcpIterativeJacobi
//#define CHMODEL ChModelBullet
//#define CHSYS ChSystem
#define CHBODYSHAREDPTR ChSharedBodyGPUPtr
#define CHBODY ChBodyGPU
#define CHCOLLISIONSYS ChCollisionSystemGPU
#define CHLCPDESC ChLcpSystemDescriptorGPU
#define CHCONTACTCONT ChContactContainerGPUsimple
#define CHSOLVER ChLcpIterativeJacobi
#define CHMODEL ChModelGPU
#define CHSYS ChSystemGPU
uint num_objects=0;
void dump_matricies(ChLcpSystemDescriptor& mdescriptor) {
	chrono::ChSparseMatrix mdM;
	chrono::ChSparseMatrix mdCq;
	chrono::ChSparseMatrix mdE;
	chrono::ChMatrixDynamic<double> mdf;
	chrono::ChMatrixDynamic<double> mdb;
	chrono::ChMatrixDynamic<double> mdfric;
	mdescriptor.ConvertToMatrixForm(&mdCq, &mdM, &mdE, &mdf, &mdb, &mdfric);
	chrono::ChStreamOutAsciiFile file_M("dump_M.dat");
	mdM.StreamOUTsparseMatlabFormat(file_M);
	chrono::ChStreamOutAsciiFile file_Cq("dump_Cq.dat");
	mdCq.StreamOUTsparseMatlabFormat(file_Cq);
	chrono::ChStreamOutAsciiFile file_E("dump_E.dat");
	mdE.StreamOUTsparseMatlabFormat(file_E);
	chrono::ChStreamOutAsciiFile file_f("dump_f.dat");
	mdf.StreamOUTdenseMatlabFormat(file_f);
	chrono::ChStreamOutAsciiFile file_b("dump_b.dat");
	mdb.StreamOUTdenseMatlabFormat(file_b);
	chrono::ChStreamOutAsciiFile file_fric("dump_fric.dat");
	mdfric.StreamOUTdenseMatlabFormat(file_fric);
}
template<class T>
void RunTimeStep(T* mSys, const int frame){
	Vector lpos(0, 0, 0);
	ChQuaternion<> quat(1, 0, 0, 0);
	CHBODYSHAREDPTR sphere;

    if(frame%10==0){
    for (int i = 0; i < 10; i++) {
		sphere = CHBODYSHAREDPTR(new CHBODY);
        Vector pos=Vector((rand() % 10000 / 10000.0 - .5), (.5), (rand() % 10000 / 10000.0 - .5));
		InitObject(sphere, 1.0, pos*10 , quat, 1, 1, 0, true, false, 32, 17+num_objects);
		AddCollisionGeometry(sphere, SPHERE, Vector(.3, .3, .3), lpos, quat);
		FinalizeObject(sphere, (CHSYS*) mSys);
		num_objects++;
	}
    }
}

int main(int argc, char* argv[]) {
	feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
	//cudaSetDevice(0);
	omp_set_num_threads(6);
    CHSYS* mSys = new CHSYS();
	CHLCPDESC *mdescriptor = new CHLCPDESC();
	CHCONTACTCONT *mcontactcontainer = new CHCONTACTCONT();
	CHCOLLISIONSYS *mcollisionengine = new CHCOLLISIONSYS();
	//ChLcpIterativeJacobi *msolver = new ChLcpIterativeJacobi();
	//ChLcpIterativeSOR *msolver = new ChLcpIterativeSOR();
	//ChLcpIterativeMINRES *msolver = new ChLcpIterativeMINRES();
	//ChLcpIterativePMINRES *msolver = new ChLcpIterativePMINRES();
	//ChLcpIterativeBB *msolver = new ChLcpIterativeBB();

	mSys->ChangeLcpSystemDescriptor(mdescriptor);
	mSys->ChangeContactContainer(mcontactcontainer);
	//mSys->ChangeLcpSolverSpeed(msolver);
	mSys->ChangeCollisionSystem(mcollisionengine);

	mSys->SetIntegrationType(ChSystem::INT_ANITESCU);
	mSys->Set_G_acc(Vector(0, -9.80665, 0));

	Vector lpos(0, 0, 0);
	ChQuaternion<> quat(1, 0, 0, 0);
//	ChSharedBodyPtr sphere;
//	for (int i = 0; i < 1000; i++) {
//		sphere = ChSharedBodyPtr(new ChBody);
//		InitObject(sphere, 1.0, Vector((rand() % 10000 / 1000.0 - 5), (rand() % 10000 / 1000.0 - 5), (rand() % 10000 / 1000.0 - 5)), quat, 1, 1, 0, true, false, 32, 17 + i);
//		AddCollisionGeometry(sphere, SPHERE, Vector(.3, .3, .3), lpos, quat);
//		FinalizeObject(sphere, mSys);
//	}

	float mWallMu = 1, container_width = 7.0, container_thickness = .25, container_height = 7.0, wscale = 1;
	CHBODYSHAREDPTR L = CHBODYSHAREDPTR(new CHBODY);
	CHBODYSHAREDPTR R = CHBODYSHAREDPTR(new CHBODY);
	CHBODYSHAREDPTR F = CHBODYSHAREDPTR(new CHBODY);
	CHBODYSHAREDPTR B = CHBODYSHAREDPTR(new CHBODY);
	CHBODYSHAREDPTR BTM = CHBODYSHAREDPTR(new CHBODY);

	InitObject(L, 100000, Vector(-container_width + container_thickness, 0, 0), quat, mWallMu, mWallMu, 0, true, true, -20, -20);
	InitObject(R, 100000, Vector(container_width - container_thickness, 0, 0), quat, mWallMu, mWallMu, 0, true, true, -20, -20);
	InitObject(F, 100000, Vector(0, 0, -container_width + container_thickness), quat, mWallMu, mWallMu, 0, true, true, -20, -20);
	InitObject(B, 100000, Vector(0, 0, container_width - container_thickness), quat, mWallMu, mWallMu, 0, true, true, -20, -20);
	InitObject(BTM, 100000, Vector(0, -container_height + container_thickness, 0), quat, mWallMu, mWallMu, 0, true, true, -20, -20);

	AddCollisionGeometry(L, BOX, Vector(container_thickness, container_height, container_width), lpos, quat);
	AddCollisionGeometry(R, BOX, Vector(container_thickness, container_height, container_width), lpos, quat);
	AddCollisionGeometry(F, BOX, Vector(container_width * wscale, container_height, container_thickness), lpos, quat);
	AddCollisionGeometry(B, BOX, Vector(container_width * wscale, container_height, container_thickness), lpos, quat);
	AddCollisionGeometry(BTM, BOX, Vector(container_width * wscale, container_thickness , container_width), lpos, quat);

	FinalizeObject(L, mSys);
	FinalizeObject(R, mSys);
	FinalizeObject(F, mSys);
	FinalizeObject(B, mSys);
	FinalizeObject(BTM, mSys);

	mSys->SetStep(0.01);
// 	ChOpenGLManager * window_manager = new ChOpenGLManager();
// 	ChOpenGL openGLView(window_manager, mSys, 800, 600, 0, 0, "Test_Solvers");
//     openGLView.SetCustomCallback(RunTimeStep);
// 	openGLView.StartSpinning(window_manager);
// 	window_manager->CallGlutMainLoop();
//
//	//msolver->Solve(*mdescriptor,true);
//	//dump_matricies(*mdescriptor);
//	//ChLcpIterativePMINRES msolver_krylov(20, false, 0.00001);
//	//msolver_krylov.Solve(mdescriptor);
//
//    ChMitsubaRender output(mSys);
//
//	output.SetIntegrator("photonmapper");
//	output.SetIntegratorOption("integer", "maxDepth", "32");
//	output.SetFilm("ldrfilm");
//	output.SetFilmOption("integer", "height", "1200");
//	output.SetFilmOption("integer", "width", "1920");
//
//	output.camera_target = ChVector<>(0, 0, 0);
//	output.camera_origin = ChVector<>(0, 0, -10);
//	output.camera_up = ChVector<>(0, 1, 0);
//
//	output.SetDataFolder("data");
//	output.ExportScript("test.xml");
//    output.SetRenderFolder("render");
//    output.ExportDriver("driver.sh");

    int counter=0;

    while(counter<200){
        RunTimeStep(mSys, counter);
        mSys->DoStepDynamics(.01);

        stringstream ss;
		ss << "data/" << counter << ".xml";
		//output.ExportData(ss.str());

       cout<<counter<<endl;
        counter++;
    }
	return 0;
}

<|endoftext|>


<commit_before>// A very small portion of a SPEF parser
// just does resistor lines

/*
Copyright (c) 2016 Jeffrey E. Trull

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 <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/phoenix.hpp>

#include <boost/coroutine2/all.hpp>

struct resistor_t {
    unsigned     idx;
    unsigned     net1;
    std::string  node1;
    unsigned     net2;
    std::string  node2;
    double       value;
};

BOOST_FUSION_ADAPT_STRUCT(
    resistor_t,
    (unsigned,    idx)
    (unsigned,    net1)
    (std::string, node1)
    (unsigned,    net2)
    (std::string, node2)
    (double,      value)
)

int main() {
    using namespace std;

    string testspef(
        "*RES\n"
        "1 *1087:4 *223:B 1.2\n"
        "2 *1087:3 *1087:4 3.12\n"
    );

    using namespace boost::spirit::qi;
    rule<string::iterator,
         resistor_t(),
         ascii::space_type> rline =
        uint_ >>
        "*" >> uint_ >> ":" >> lexeme[+ascii::alnum] >>
        "*" >> uint_ >> ":" >> lexeme[+ascii::alnum] >>
        double_ ;

    using namespace boost::coroutines2;
    using coro_t = asymmetric_coroutine<resistor_t>;
    namespace phx = boost::phoenix;
    auto source_fn =
        [&](coro_t::push_type & sink) {
        auto beg = testspef.begin();
        phrase_parse(
            beg, testspef.end(),
            lit("*RES") >> *rline[phx::bind(phx::ref(sink), _1)],
            ascii::space);
    };
    coro_t::pull_type resistors(source_fn);
    for (auto const& r : resistors) {
        cout << r.value << " from " << r.net1 << ":" << r.node1;
        cout            << " to "   << r.net2 << ":" << r.node2 << "\n";
    }
}

<commit_msg>[Cadence] Eliminate Phoenix in favor of lambdas<commit_after>// A very small portion of a SPEF parser
// just does resistor lines

/*
Copyright (c) 2016 Jeffrey E. Trull

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 <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

#include <boost/coroutine2/all.hpp>

struct resistor_t {
    unsigned     idx;
    unsigned     net1;
    std::string  node1;
    unsigned     net2;
    std::string  node2;
    double       value;
};

BOOST_FUSION_ADAPT_STRUCT(
    resistor_t,
    (unsigned,    idx)
    (unsigned,    net1)
    (std::string, node1)
    (unsigned,    net2)
    (std::string, node2)
    (double,      value)
)

int main() {
    using namespace std;

    string testspef(
        "*RES\n"
        "1 *1087:4 *223:B 1.2\n"
        "2 *1087:3 *1087:4 3.12\n"
    );

    using namespace boost::spirit::qi;
    rule<string::iterator,
         resistor_t(),
         ascii::space_type> rline =
        uint_ >>
        "*" >> uint_ >> ":" >> lexeme[+ascii::alnum] >>
        "*" >> uint_ >> ":" >> lexeme[+ascii::alnum] >>
        double_ ;

    using namespace boost::coroutines2;
    using coro_t = asymmetric_coroutine<resistor_t>;
    auto source_fn =
        [&](coro_t::push_type & sink) {
        auto beg = testspef.begin();
        phrase_parse(
            beg, testspef.end(),
            lit("*RES") >> *rline[(
                [&](auto const& v) {
                    sink(v);
                })],
            ascii::space);
    };
    coro_t::pull_type resistors(source_fn);
    for (auto const& r : resistors) {
        cout << r.value << " from " << r.net1 << ":" << r.node1;
        cout            << " to "   << r.net2 << ":" << r.node2 << "\n";
    }
}

<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "main.h"
#include "bitcoinrpc.h"
#include <boost/filesystem.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>
#include <ostream>

using namespace json_spirit;
using namespace std;

extern void TxToJSON(const CTransaction& tx, const uint256& hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;

double GetDifficulty(const CBlockIndex* blockindex)
{
    // Floating point number that is a multiple of the minimum difficulty,
    // minimum difficulty = 1.0.
    if (blockindex == NULL)
    {
        if (pindexBest == NULL)
            return 1.0;
        else
            blockindex = GetLastBlockIndex(pindexBest, false);
    }

    int nShift = (blockindex->nBits >> 24) & 0xff;

    double dDiff =
        (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);

    while (nShift < 29)
    {
        dDiff *= 256.0;
        nShift++;
    }
    while (nShift > 29)
    {
        dDiff /= 256.0;
        nShift--;
    }

    return dDiff;
}

double GetPoWMHashPS()
{
    int nPoWInterval = 72;
    int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;

    CBlockIndex* pindex = pindexGenesisBlock;
    CBlockIndex* pindexPrevWork = pindexGenesisBlock;

    while (pindex)
    {
        if (pindex->IsProofOfWork())
        {
            int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
            nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
            nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
            pindexPrevWork = pindex;
        }

        pindex = pindex->pnext;
    }

    return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}

double GetPoSKernelPS()
{
    int nPoSInterval = 72;
    double dStakeKernelsTriedAvg = 0;
    int nStakesHandled = 0, nStakesTime = 0;

    CBlockIndex* pindex = pindexBest;;
    CBlockIndex* pindexPrevStake = NULL;

    while (pindex && nStakesHandled < nPoSInterval)
    {
        if (pindex->IsProofOfStake())
        {
            dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
            nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
            pindexPrevStake = pindex;
            nStakesHandled++;
        }

        pindex = pindex->pprev;
    }

    if (!nStakesHandled)
        return 0;

    return dStakeKernelsTriedAvg / nStakesTime;
}

Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
    Object result;
    result.push_back(Pair("hash", block.GetHash().GetHex()));
    CMerkleTx txGen(block.vtx[0]);
    txGen.SetMerkleBranch(&block);
    result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
    result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
    result.push_back(Pair("height", blockindex->nHeight));
    result.push_back(Pair("version", block.nVersion));
    result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
    result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
    result.push_back(Pair("time", (int64_t)block.GetBlockTime()));
    result.push_back(Pair("nonce", (uint64_t)block.nNonce));
    result.push_back(Pair("bits", HexBits(block.nBits)));
    result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
    result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
    result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
    if (blockindex->pprev)
        result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
    if (blockindex->pnext)
        result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));

    result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
    result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
    result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
    result.push_back(Pair("modifier", strprintf("%016" PRIx64, blockindex->nStakeModifier)));
    result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
    Array txinfo;
    BOOST_FOREACH (const CTransaction& tx, block.vtx)
    {
        if (fPrintTransactionDetail)
        {
            CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
            ssTx << tx;
            string strHex = HexStr(ssTx.begin(), ssTx.end());

            txinfo.push_back(strHex);
        }
        else
            txinfo.push_back(tx.GetHash().GetHex());
    }

    result.push_back(Pair("tx", txinfo));

    if ( block.IsProofOfStake() )
        result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));

    return result;
}

Value getbestblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getbestblockhash\n"
            "Returns the hash of the best block in the longest block chain.");

    return hashBestChain.GetHex();
}

Value getblockcount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getblockcount\n"
            "Returns the number of blocks in the longest block chain.");

    return nBestHeight;
}

Value getdifficulty(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getdifficulty\n"
            "Returns the difficulty as a multiple of the minimum difficulty.");

    Object obj;
    obj.push_back(Pair("proof-of-work",        GetDifficulty()));
    obj.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    obj.push_back(Pair("search-interval",      (int)nLastCoinStakeSearchInterval));
    return obj;
}

Value settxfee(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
        throw runtime_error(
            "settxfee <amount>\n"
            "<amount> is a real and is rounded to the nearest " + FormatMoney(MIN_TX_FEE));

    nTransactionFee = AmountFromValue(params[0]);
    nTransactionFee = (nTransactionFee / MIN_TX_FEE) * MIN_TX_FEE;  // round to minimum fee

    return true;
}

Value getrawmempool(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getrawmempool\n"
            "Returns all transaction ids in memory pool.");

    vector<uint256> vtxid;
    mempool.queryHashes(vtxid);

    Array a;
    BOOST_FOREACH(const uint256& hash, vtxid)
        a.push_back(hash.ToString());

    return a;
}

Value getblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getblockhash <index>\n"
            "Returns hash of block in best-block-chain at <index>.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
    return pblockindex->phashBlock->GetHex();
}

Value getblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock <hash> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-hash.");

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

Value getblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblockbynumber <number> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    pblockindex = mapBlockIndex[*pblockindex->phashBlock];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

bool ExportBlock(const string& strBlockHash, const CDataStream& ssBlock)
{
    boost::filesystem::path pathDest = GetDataDir() / strBlockHash;
    if (boost::filesystem::is_directory(pathDest))
        pathDest /= strBlockHash;

    try {
        boost::iostreams::stream_buffer<boost::iostreams::file_sink> buf(pathDest.string());
        ostream                     exportStream(&buf);
        exportStream << HexStr(ssBlock.begin(), ssBlock.end());
        exportStream.flush();

        printf("Successfully exported block to %s\n", pathDest.string().c_str());
        return true;
    } catch(const boost::filesystem::filesystem_error &e) {
        printf("error exporting the block data %s (%s)\n", pathDest.string().c_str(), e.what());
        return false;
    }
}

Value dumpblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "dumpblock <hash> [destination]\n"
            "Returns serialized contents of a block with given block-hash.");

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
    ssBlock << block;

    if (params.size() > 1)
    {
        return ExportBlock(params[1].get_str(), ssBlock);
    }

    return HexStr(ssBlock.begin(), ssBlock.end());
}

Value dumpblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "dumpblockbynumber <number>  [destination]\n"
            "Returns serialized contents of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    pblockindex = mapBlockIndex[*pblockindex->phashBlock];
    block.ReadFromDisk(pblockindex, true);

    CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
    ssBlock << block;

    if (params.size() > 1)
    {
        return ExportBlock(params[1].get_str(), ssBlock);
    }

    return HexStr(ssBlock.begin(), ssBlock.end());
}

// get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getcheckpoint\n"
            "Show info of synchronized checkpoint.\n");

    Object result;
    CBlockIndex* pindexCheckpoint;

    result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
    pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
    result.push_back(Pair("height", pindexCheckpoint->nHeight));
    result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));

    if (Checkpoints::checkpointMessage.vchSig.size() != 0)
    {
        Object msgdata;
        CUnsignedSyncCheckpoint checkpoint;

        CDataStream sMsg(Checkpoints::checkpointMessage.vchMsg, SER_NETWORK, PROTOCOL_VERSION);
        sMsg >> checkpoint;

        Object parsed; // message version and data (block hash)
        parsed.push_back(Pair("version", checkpoint.nVersion));
        parsed.push_back(Pair("hash", checkpoint.hashCheckpoint.GetHex().c_str()));
        msgdata.push_back(Pair("parsed", parsed));

        Object raw; // raw checkpoint message data
        raw.push_back(Pair("data", HexStr(Checkpoints::checkpointMessage.vchMsg).c_str()));
        raw.push_back(Pair("signature", HexStr(Checkpoints::checkpointMessage.vchSig).c_str()));
        msgdata.push_back(Pair("raw", raw));

        result.push_back(Pair("data", msgdata));
    }

    // Check that the block satisfies synchronized checkpoint
    if (CheckpointsMode == Checkpoints::STRICT)
        result.push_back(Pair("policy", "strict"));

    if (CheckpointsMode == Checkpoints::ADVISORY)
        result.push_back(Pair("policy", "advisory"));

    if (CheckpointsMode == Checkpoints::PERMISSIVE)
        result.push_back(Pair("policy", "permissive"));

    if (mapArgs.count("-checkpointkey"))
        result.push_back(Pair("checkpointmaster", true));

    return result;
}
<commit_msg>fix error<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "main.h"
#include "bitcoinrpc.h"
#include <boost/filesystem.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>
#include <ostream>

using namespace json_spirit;
using namespace std;

extern void TxToJSON(const CTransaction& tx, const uint256& hashBlock, json_spirit::Object& entry);
extern enum Checkpoints::CPMode CheckpointsMode;

double GetDifficulty(const CBlockIndex* blockindex)
{
    // Floating point number that is a multiple of the minimum difficulty,
    // minimum difficulty = 1.0.
    if (blockindex == NULL)
    {
        if (pindexBest == NULL)
            return 1.0;
        else
            blockindex = GetLastBlockIndex(pindexBest, false);
    }

    int nShift = (blockindex->nBits >> 24) & 0xff;

    double dDiff =
        (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);

    while (nShift < 29)
    {
        dDiff *= 256.0;
        nShift++;
    }
    while (nShift > 29)
    {
        dDiff /= 256.0;
        nShift--;
    }

    return dDiff;
}

double GetPoWMHashPS()
{
    int nPoWInterval = 72;
    int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;

    CBlockIndex* pindex = pindexGenesisBlock;
    CBlockIndex* pindexPrevWork = pindexGenesisBlock;

    while (pindex)
    {
        if (pindex->IsProofOfWork())
        {
            int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
            nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
            nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
            pindexPrevWork = pindex;
        }

        pindex = pindex->pnext;
    }

    return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}

double GetPoSKernelPS()
{
    int nPoSInterval = 72;
    double dStakeKernelsTriedAvg = 0;
    int nStakesHandled = 0, nStakesTime = 0;

    CBlockIndex* pindex = pindexBest;;
    CBlockIndex* pindexPrevStake = NULL;

    while (pindex && nStakesHandled < nPoSInterval)
    {
        if (pindex->IsProofOfStake())
        {
            dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0;
            nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0;
            pindexPrevStake = pindex;
            nStakesHandled++;
        }

        pindex = pindex->pprev;
    }

    if (!nStakesHandled)
        return 0;

    return dStakeKernelsTriedAvg / nStakesTime;
}

Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
    Object result;
    result.push_back(Pair("hash", block.GetHash().GetHex()));
    CMerkleTx txGen(block.vtx[0]);
    txGen.SetMerkleBranch(&block);
    result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
    result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
    result.push_back(Pair("height", blockindex->nHeight));
    result.push_back(Pair("version", block.nVersion));
    result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
    result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
    result.push_back(Pair("time", (int64_t)block.GetBlockTime()));
    result.push_back(Pair("nonce", (uint64_t)block.nNonce));
    result.push_back(Pair("bits", HexBits(block.nBits)));
    result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
    result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
    result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
    if (blockindex->pprev)
        result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
    if (blockindex->pnext)
        result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));

    result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
    result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
    result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
    result.push_back(Pair("modifier", strprintf("%016" PRIx64, blockindex->nStakeModifier)));
    result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
    Array txinfo;
    BOOST_FOREACH (const CTransaction& tx, block.vtx)
    {
        if (fPrintTransactionDetail)
        {
            CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
            ssTx << tx;
            string strHex = HexStr(ssTx.begin(), ssTx.end());

            txinfo.push_back(strHex);
        }
        else
            txinfo.push_back(tx.GetHash().GetHex());
    }

    result.push_back(Pair("tx", txinfo));

    if ( block.IsProofOfStake() )
        result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));

    return result;
}

Value getbestblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getbestblockhash\n"
            "Returns the hash of the best block in the longest block chain.");

    return hashBestChain.GetHex();
}

Value getblockcount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getblockcount\n"
            "Returns the number of blocks in the longest block chain.");

    return nBestHeight;
}

Value getdifficulty(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getdifficulty\n"
            "Returns the difficulty as a multiple of the minimum difficulty.");

    Object obj;
    obj.push_back(Pair("proof-of-work",        GetDifficulty()));
    obj.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    obj.push_back(Pair("search-interval",      (int)nLastCoinStakeSearchInterval));
    return obj;
}

Value settxfee(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
        throw runtime_error(
            "settxfee <amount>\n"
            "<amount> is a real and is rounded to the nearest " + FormatMoney(MIN_TX_FEE));

    nTransactionFee = AmountFromValue(params[0]);
    nTransactionFee = (nTransactionFee | MIN_TX_FEE) * MIN_TX_FEE;  // round to minimum fee

    return true;
}

Value getrawmempool(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getrawmempool\n"
            "Returns all transaction ids in memory pool.");

    vector<uint256> vtxid;
    mempool.queryHashes(vtxid);

    Array a;
    BOOST_FOREACH(const uint256& hash, vtxid)
        a.push_back(hash.ToString());

    return a;
}

Value getblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getblockhash <index>\n"
            "Returns hash of block in best-block-chain at <index>.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
    return pblockindex->phashBlock->GetHex();
}

Value getblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock <hash> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-hash.");

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

Value getblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblockbynumber <number> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    pblockindex = mapBlockIndex[*pblockindex->phashBlock];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

bool ExportBlock(const string& strBlockHash, const CDataStream& ssBlock)
{
    boost::filesystem::path pathDest = GetDataDir() / strBlockHash;
    if (boost::filesystem::is_directory(pathDest))
        pathDest /= strBlockHash;

    try {
        boost::iostreams::stream_buffer<boost::iostreams::file_sink> buf(pathDest.string());
        ostream                     exportStream(&buf);
        exportStream << HexStr(ssBlock.begin(), ssBlock.end());
        exportStream.flush();

        printf("Successfully exported block to %s\n", pathDest.string().c_str());
        return true;
    } catch(const boost::filesystem::filesystem_error &e) {
        printf("error exporting the block data %s (%s)\n", pathDest.string().c_str(), e.what());
        return false;
    }
}

Value dumpblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "dumpblock <hash> [destination]\n"
            "Returns serialized contents of a block with given block-hash.");

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
    ssBlock << block;

    if (params.size() > 1)
    {
        return ExportBlock(params[1].get_str(), ssBlock);
    }

    return HexStr(ssBlock.begin(), ssBlock.end());
}

Value dumpblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "dumpblockbynumber <number>  [destination]\n"
            "Returns serialized contents of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    pblockindex = mapBlockIndex[*pblockindex->phashBlock];
    block.ReadFromDisk(pblockindex, true);

    CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
    ssBlock << block;

    if (params.size() > 1)
    {
        return ExportBlock(params[1].get_str(), ssBlock);
    }

    return HexStr(ssBlock.begin(), ssBlock.end());
}

// get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getcheckpoint\n"
            "Show info of synchronized checkpoint.\n");

    Object result;
    CBlockIndex* pindexCheckpoint;

    result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
    pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
    result.push_back(Pair("height", pindexCheckpoint->nHeight));
    result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));

    if (Checkpoints::checkpointMessage.vchSig.size() != 0)
    {
        Object msgdata;
        CUnsignedSyncCheckpoint checkpoint;

        CDataStream sMsg(Checkpoints::checkpointMessage.vchMsg, SER_NETWORK, PROTOCOL_VERSION);
        sMsg >> checkpoint;

        Object parsed; // message version and data (block hash)
        parsed.push_back(Pair("version", checkpoint.nVersion));
        parsed.push_back(Pair("hash", checkpoint.hashCheckpoint.GetHex().c_str()));
        msgdata.push_back(Pair("parsed", parsed));

        Object raw; // raw checkpoint message data
        raw.push_back(Pair("data", HexStr(Checkpoints::checkpointMessage.vchMsg).c_str()));
        raw.push_back(Pair("signature", HexStr(Checkpoints::checkpointMessage.vchSig).c_str()));
        msgdata.push_back(Pair("raw", raw));

        result.push_back(Pair("data", msgdata));
    }

    // Check that the block satisfies synchronized checkpoint
    if (CheckpointsMode == Checkpoints::STRICT)
        result.push_back(Pair("policy", "strict"));

    if (CheckpointsMode == Checkpoints::ADVISORY)
        result.push_back(Pair("policy", "advisory"));

    if (CheckpointsMode == Checkpoints::PERMISSIVE)
        result.push_back(Pair("policy", "permissive"));

    if (mapArgs.count("-checkpointkey"))
        result.push_back(Pair("checkpointmaster", true));

    return result;
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2020)

#include "config.h"

#include <dune/pybindxi/pybind11.h>
#include <dune/pybindxi/stl.h>

#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/grids.hh>
#include <dune/xt/grid/gridprovider/provider.hh>

#include <dune/gdt/local/integrands/laplace.hh>

#include <python/dune/xt/common/configuration.hh>
#include <python/dune/xt/common/fvector.hh>
#include <python/dune/xt/grid/grids.bindings.hh>

namespace Dune {
namespace GDT {
namespace bindings {

template <class E, size_t r = 1, class F = double>
class LocalLaplaceIntegrand
{
  using G = std::decay_t<XT::Grid::extract_grid_t<E>>;
  using GP = XT::Grid::GridProvider<G>;
  static const size_t d = G::dimension;

public:
  using type = GDT::LocalLaplaceIntegrand<E, r, F>;
  using base_type = GDT::LocalBinaryElementIntegrandInterface<E, r, 1, F, F, r, 1, F>;
  using bound_type = pybind11::class_<type, base_type>;

private:
  template <bool oned = (d == 1), bool anything = true>
  struct add_bind /*<true, anything>*/
  {
    static void ctor(bound_type&) {}

    static void factory(pybind11::module&, const std::string&) {}
  };

  template <bool anything>
  struct add_bind<false, anything>
  {
    static void ctor(bound_type& c)
    {
      namespace py = pybind11;
      using namespace pybind11::literals;

      c.def(py::init<const FieldMatrix<F, d, d>&>(), "constant_diffusion_tensor"_a);
      c.def(py::init<const XT::Functions::FunctionInterface<d, d, d, F>&>(),
            "diffusion_tensor_function"_a,
            py::keep_alive<1, 2>());
    }

    static void factory(pybind11::module& m, const std::string& FactoryName)
    {
      namespace py = pybind11;
      using namespace pybind11::literals;

      m.def(FactoryName.c_str(),
            [](const GP&, const FieldMatrix<F, d, d>& constant_diffusion_tensor) {
              return type(constant_diffusion_tensor);
            },
            "unused_grid_to_select_type"_a,
            "constant_diffusion_tensor"_a);
      m.def(FactoryName.c_str(),
            [](const GP&, const XT::Functions::FunctionInterface<d, d, d, F>& diffusion_tensor_function) {
              return type(diffusion_tensor_function);
            },
            "unused_grid_to_select_type"_a,
            "diffusion_tensor_function"_a,
            py::keep_alive<1, 3>());
    }
  }; // struct add_bind<false, ...>

public:
  static bound_type bind(pybind11::module& m,
                         const std::string& class_id = "local_laplace_integrand",
                         const std::string& grid_id = XT::Grid::bindings::grid_name<G>::value(),
                         const std::string& layer_id = "")
  {
    namespace py = pybind11;
    using namespace pybind11::literals;

    std::string class_name = class_id;
    class_name += "_" + grid_id;
    if (!layer_id.empty())
      class_name += "_" + layer_id;
    class_name += "_" + XT::Common::to_string(r) + "d_bases";
    class_name += "_to_scalar";
    if (!std::is_same<F, double>::value)
      class_name += "_" + XT::Common::Typename<F>::value(/*fail_wo_typeid=*/true);
    const auto ClassName = XT::Common::to_camel_case(class_name);
    bound_type c(m, ClassName.c_str(), ClassName.c_str());
    c.def(py::init<const F&>(), "constant_scalar_diffusion"_a);
    c.def(py::init<const XT::Functions::FunctionInterface<d, 1, 1, F>&>(),
          "scalar_diffusion_function"_a,
          py::keep_alive<1, 2>());
    add_bind<>::ctor(c);
    c.def(py::init<const XT::Functions::GridFunctionInterface<E, 1, 1, F>&>(),
          "scalar_diffusion_grid_function"_a,
          py::keep_alive<1, 2>());
    c.def(py::init<const XT::Functions::GridFunctionInterface<E, d, d, F>&>(),
          "diffusion_tensor_grid_function"_a,
          py::keep_alive<1, 2>());

    // factories
    const auto FactoryName = XT::Common::to_camel_case(class_id);
    m.def(FactoryName.c_str(),
          [](const GP&, const F& constant_scalar_diffusion) { return type(constant_scalar_diffusion); },
          "unused_grid_to_select_type"_a,
          "constant_scalar_diffusion"_a);
    add_bind<>::factory(m, FactoryName);
    m.def(FactoryName.c_str(),
          [](const GP&, const XT::Functions::FunctionInterface<d, 1, 1, F>& scalar_diffusion_function) {
            return type(scalar_diffusion_function);
          },
          "unused_grid_to_select_type"_a,
          "scalar_diffusion_function"_a,
          py::keep_alive<1, 3>());
    m.def(FactoryName.c_str(),
          [](const XT::Functions::GridFunctionInterface<E, 1, 1, F>& scalar_diffusion_grid_function) {
            return type(scalar_diffusion_grid_function);
          },
          "scalar_diffusion_grid_function"_a,
          py::keep_alive<1, 2>());
    m.def(FactoryName.c_str(),
          [](const XT::Functions::GridFunctionInterface<E, d, d, F>& diffusion_tensor_grid_function) {
            return type(diffusion_tensor_grid_function);
          },
          "diffusion_tensor_grid_function"_a,
          py::keep_alive<1, 2>());

    return c;
  } // ... bind(...)
}; // class LocalLaplaceIntegrand

} // namespace bindings
} // namespace GDT
} // namespace Dune

template <class GridTypes = Dune::XT::Grid::AvailableGridTypes>
struct LocalLaplaceIntegrand_for_all_grids
{
  using G = typename GridTypes::head_type;
  using GV = typename G::LeafGridView;
  using E = Dune::XT::Grid::extract_entity_t<GV>;
  static const constexpr size_t d = G::dimension;

  static void bind(pybind11::module& m)
  {
    Dune::GDT::bindings::LocalLaplaceIntegrand<E>::bind(m);
    if (d > 1)
      Dune::GDT::bindings::LocalLaplaceIntegrand<E, d>::bind(m);
    // add your extra dimensions here
    // ...
    LocalLaplaceIntegrand_for_all_grids<typename GridTypes::tail_type>::bind(m);
  }
};

template <>
struct LocalLaplaceIntegrand_for_all_grids<boost::tuples::null_type>
{
  static void bind(pybind11::module& /*m*/) {}
};

PYBIND11_MODULE(_local_integrands_laplace, m)
{
  namespace py = pybind11;
  using namespace Dune;
  using namespace Dune::XT;
  using namespace Dune::GDT;

  py::module::import("dune.xt.common");
  py::module::import("dune.xt.la");
  py::module::import("dune.xt.grid");
  py::module::import("dune.xt.functions");
  py::module::import("dune.gdt._local_integrands_binary_element_interface");

  LocalLaplaceIntegrand_for_all_grids<XT::Grid::AvailableGridTypes>::bind(m);
}
<commit_msg>[python|local.integrands] fix keep alive guards<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2020)

#include "config.h"

#include <dune/pybindxi/pybind11.h>
#include <dune/pybindxi/stl.h>

#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/grids.hh>
#include <dune/xt/grid/gridprovider/provider.hh>

#include <dune/gdt/local/integrands/laplace.hh>

#include <python/dune/xt/common/configuration.hh>
#include <python/dune/xt/common/fvector.hh>
#include <python/dune/xt/grid/grids.bindings.hh>

namespace Dune {
namespace GDT {
namespace bindings {

template <class E, size_t r = 1, class F = double>
class LocalLaplaceIntegrand
{
  using G = std::decay_t<XT::Grid::extract_grid_t<E>>;
  using GP = XT::Grid::GridProvider<G>;
  static const size_t d = G::dimension;

public:
  using type = GDT::LocalLaplaceIntegrand<E, r, F>;
  using base_type = GDT::LocalBinaryElementIntegrandInterface<E, r, 1, F, F, r, 1, F>;
  using bound_type = pybind11::class_<type, base_type>;

private:
  template <bool oned = (d == 1), bool anything = true>
  struct add_bind /*<true, anything>*/
  {
    static void ctor(bound_type&) {}

    static void factory(pybind11::module&, const std::string&) {}
  };

  template <bool anything>
  struct add_bind<false, anything>
  {
    static void ctor(bound_type& c)
    {
      namespace py = pybind11;
      using namespace pybind11::literals;

      c.def(py::init<const FieldMatrix<F, d, d>&>(), "constant_diffusion_tensor"_a);
      c.def(py::init<const XT::Functions::FunctionInterface<d, d, d, F>&>(),
            "diffusion_tensor_function"_a,
            py::keep_alive<1, 2>());
    }

    static void factory(pybind11::module& m, const std::string& FactoryName)
    {
      namespace py = pybind11;
      using namespace pybind11::literals;

      m.def(FactoryName.c_str(),
            [](const GP&, const FieldMatrix<F, d, d>& constant_diffusion_tensor) {
              return type(constant_diffusion_tensor);
            },
            "unused_grid_to_select_type"_a,
            "constant_diffusion_tensor"_a);
      m.def(FactoryName.c_str(),
            [](const GP&, const XT::Functions::FunctionInterface<d, d, d, F>& diffusion_tensor_function) {
              return type(diffusion_tensor_function);
            },
            "unused_grid_to_select_type"_a,
            "diffusion_tensor_function"_a,
            py::keep_alive<0, 2>());
    }
  }; // struct add_bind<false, ...>

public:
  static bound_type bind(pybind11::module& m,
                         const std::string& class_id = "local_laplace_integrand",
                         const std::string& grid_id = XT::Grid::bindings::grid_name<G>::value(),
                         const std::string& layer_id = "")
  {
    namespace py = pybind11;
    using namespace pybind11::literals;

    std::string class_name = class_id;
    class_name += "_" + grid_id;
    if (!layer_id.empty())
      class_name += "_" + layer_id;
    class_name += "_" + XT::Common::to_string(r) + "d_bases";
    class_name += "_to_scalar";
    if (!std::is_same<F, double>::value)
      class_name += "_" + XT::Common::Typename<F>::value(/*fail_wo_typeid=*/true);
    const auto ClassName = XT::Common::to_camel_case(class_name);
    bound_type c(m, ClassName.c_str(), ClassName.c_str());
    c.def(py::init<const F&>(), "constant_scalar_diffusion"_a);
    c.def(py::init<const XT::Functions::FunctionInterface<d, 1, 1, F>&>(),
          "scalar_diffusion_function"_a,
          py::keep_alive<1, 2>());
    add_bind<>::ctor(c);
    c.def(py::init<const XT::Functions::GridFunctionInterface<E, 1, 1, F>&>(),
          "scalar_diffusion_grid_function"_a,
          py::keep_alive<1, 2>());
    c.def(py::init<const XT::Functions::GridFunctionInterface<E, d, d, F>&>(),
          "diffusion_tensor_grid_function"_a,
          py::keep_alive<1, 2>());

    // factories
    const auto FactoryName = XT::Common::to_camel_case(class_id);
    m.def(FactoryName.c_str(),
          [](const GP&, const F& constant_scalar_diffusion) { return type(constant_scalar_diffusion); },
          "unused_grid_to_select_type"_a,
          "constant_scalar_diffusion"_a);
    add_bind<>::factory(m, FactoryName);
    m.def(FactoryName.c_str(),
          [](const GP&, const XT::Functions::FunctionInterface<d, 1, 1, F>& scalar_diffusion_function) {
            return type(scalar_diffusion_function);
          },
          "unused_grid_to_select_type"_a,
          "scalar_diffusion_function"_a,
          py::keep_alive<0, 2>());
    m.def(FactoryName.c_str(),
          [](const XT::Functions::GridFunctionInterface<E, 1, 1, F>& scalar_diffusion_grid_function) {
            return type(scalar_diffusion_grid_function);
          },
          "scalar_diffusion_grid_function"_a,
          py::keep_alive<0, 1>());
    m.def(FactoryName.c_str(),
          [](const XT::Functions::GridFunctionInterface<E, d, d, F>& diffusion_tensor_grid_function) {
            return type(diffusion_tensor_grid_function);
          },
          "diffusion_tensor_grid_function"_a,
          py::keep_alive<0, 1>());

    return c;
  } // ... bind(...)
}; // class LocalLaplaceIntegrand

} // namespace bindings
} // namespace GDT
} // namespace Dune

template <class GridTypes = Dune::XT::Grid::AvailableGridTypes>
struct LocalLaplaceIntegrand_for_all_grids
{
  using G = typename GridTypes::head_type;
  using GV = typename G::LeafGridView;
  using E = Dune::XT::Grid::extract_entity_t<GV>;
  static const constexpr size_t d = G::dimension;

  static void bind(pybind11::module& m)
  {
    Dune::GDT::bindings::LocalLaplaceIntegrand<E>::bind(m);
    if (d > 1)
      Dune::GDT::bindings::LocalLaplaceIntegrand<E, d>::bind(m);
    // add your extra dimensions here
    // ...
    LocalLaplaceIntegrand_for_all_grids<typename GridTypes::tail_type>::bind(m);
  }
};

template <>
struct LocalLaplaceIntegrand_for_all_grids<boost::tuples::null_type>
{
  static void bind(pybind11::module& /*m*/) {}
};

PYBIND11_MODULE(_local_integrands_laplace, m)
{
  namespace py = pybind11;
  using namespace Dune;
  using namespace Dune::XT;
  using namespace Dune::GDT;

  py::module::import("dune.xt.common");
  py::module::import("dune.xt.la");
  py::module::import("dune.xt.grid");
  py::module::import("dune.xt.functions");
  py::module::import("dune.gdt._local_integrands_binary_element_interface");

  LocalLaplaceIntegrand_for_all_grids<XT::Grid::AvailableGridTypes>::bind(m);
}
<|endoftext|>


<commit_before>#include "testApp.h"

class myUser : public ofxOpenNIUser {
public:
    void test(){
        cout << "test" << endl;
    }
};

//-- functions and properties which might be useful for recording skeletal data
//////////////////////
// ofxOpenNITypes.cpp
//////////////////////
//    void ofxOpenNIUser::drawSkeleton() {
//        ofPushStyle();
//        // DON'T NEED TO DRAW LIMBS ANYMORE!
//        //	for(int i = 0; i < limbs.size(); i++){
//        //		limbs[i].draw();
//        //	}
//        for(int i = 0; i < joints.size(); i++){
//            joints[i].draw();
//        }
//        ofPopStyle();
//    }
//
//    ofPixels & ofxOpenNIDepthThreshold::getDepthPixels(){
//        return depthPixels;
//    }
//
//    ofPixels & ofxOpenNIDepthThreshold::getMaskPixels(){
//        return maskPixels;
//    }
//
//////////////////////
// ofxOpenNI.cpp
//////////////////////
//    ofPixels& ofxOpenNI::getDepthPixels();
//    ofPixels& ofxOpenNI::getImagePixels();
//    xn::UserGenerator& ofxOpenNI::getUserGenerator();
//    drawSkeletons();
//    if(g_bIsDepthOn) drawDepth();
//    if(g_bIsHandsOn) drawHands();
//    if(g_bIsUserOn) drawSkeletons();
//    ofTranslate(getWidth(), 0.0f);
//    if(g_bIsImageOn || g_bIsInfraOn) drawImage();
// 	currentTrackedUsers[currentTrackedUserIDs[nID]].drawSkeleton();
//
//////////////////////
// ofxOpenNI.h
//////////////////////
//    bool setSkeletonProfile(XnSkeletonProfile profile);
//    XnSkeletonProfile getSkeletonProfile();
//    xn::UserGenerator& getUserGenerator();
//    xn::DepthGenerator& getDepthGenerator();
//    xn::ImageGenerator& getImageGenerator();
//    xn::DepthMetaData& getDepthMetaData();
//    xn::ImageMetaData& getImageMetaData();
//    ofEvent<ofxOpenNIUserEvent> userEvent;
//
//////////////////////
// ofxOpenNiUtils.h
//////////////////////
//    enum Joint
//    enum Limb
//    static inline ofPoint g_worldToProjective(const ofPoint& p)
//    static inline ofPoint g_projectiveToWorld(const ofPoint& p)
//    static inline ofPoint worldToProjective(const XnVector3D& p, xn::DepthGenerator & g_Depth)
//    inline Joint XnToOfJoint(XnSkeletonJoint type)
//    inline string getXNJointAsString(XnSkeletonJoint type)
//    inline string getJointAsString(Joint type)
//    inline string getLimbAsString(Limb type)
//    inline string getUserStatusAsString(UserStatusType type)
//    inline string getCalibrationStatusAsString(XnCalibrationStatus type)
//
//////////////////////
// ofxOpenNiTypes.h
//////////////////////
// class ofxOpenNIJoint
//      ofPoint & getProjectivePosition()
//      ofPoint & getWorldPosition()
// class ofxOpenNILimb
//    void draw() {
//
//        ofPushStyle();
//        if(isFound()){
//            // draw in green
//            ofSetColor(0, 255, 0);
//        }else{
//            // draw in red
//            ofSetColor(255, 0, 0);
//        }
//        ofSetLineWidth(5);
//        ofLine(ofVec2f(startJoint->getProjectivePosition()),ofVec2f(endJoint->getProjectivePosition()));
//        ofPopStyle();
//    }
// inline int numJointsInside(ofxOpenNIUser & user)
//
////////////////////////
// ofUtils --
////////////////////////
// ofGetDay()
// ofGetFrameNum()
// ofGetHours()
// ofGetMinutes()
// ofGetMonth()
// ofGetSeconds()
// ofGetSystemTimeMicros()
// ofGetYear()
// ofToString() // "the number is " + ofToString(10)
//////////////
// ofLog -- http://www.openframeworks.cc/documentation/utils/ofLog.html
//////////////
//class methods
//    ofLog()
//    setAutoSpace()
//    setChannel()
//global functions
//    ofGetLogLevel()
//    ofGetLogLevelName()
//    ofLogToConsole()
//    ofLogToFile()
//    ofSetLogLevel()
//    ofSetLoggerChannel()

//--------------------------------------------------------------
void testApp::setup() {

    ofSetLogLevel(OF_LOG_VERBOSE);

    // TODO:
    //  - get bones showing up for player
    //      - Might need to turn the recorder off in order for the user generator of the player to work (think there can only be one instance of the user  generator)
    //  - capture bone data and save it out to a CSV that can be loaded in MATLAB
    //  - capture image and depth data, and save them to videos

    openNIRecorder.setup();
    openNIRecorder.addDepthGenerator();
    openNIRecorder.addImageGenerator();
    openNIRecorder.setRegister(true);
    openNIRecorder.setMirror(true);
    openNIRecorder.addUserGenerator();
    openNIRecorder.setMaxNumUsers(2);
    openNIRecorder.start();

    openNIPlayer.setup();
    openNIPlayer.setRegister(true);
    openNIPlayer.setMirror(true);
    openNIPlayer.addUserGenerator();
    openNIPlayer.setMaxNumUsers(2);
	openNIPlayer.start();

    verdana.loadFont(ofToDataPath("verdana.ttf"), 24);
}

//--------------------------------------------------------------
void testApp::update(){
    openNIRecorder.update();
    openNIPlayer.update();
}

//--------------------------------------------------------------
void testApp::draw(){
	ofSetColor(255, 255, 255);

    ofPushMatrix();

    openNIRecorder.drawDebug(0, 0);
    openNIPlayer.drawDebug(0, 240);

    ofPushMatrix();

	ofSetColor(0, 255, 0);
	string msg = " MILLIS: " + ofToString(ofGetElapsedTimeMillis()) + " FPS: " + ofToString(ofGetFrameRate());
	verdana.drawString(msg, 20, 2 * 480 - 20);
}

//--------------------------------------------------------------
void testApp::userEvent(ofxOpenNIUserEvent & event){
    ofLogNotice() << getUserStatusAsString(event.userStatus) << "for user" << event.id << "from device" << event.deviceID;
}

//--------------------------------------------------------------
void testApp::gestureEvent(ofxOpenNIGestureEvent & event){
    ofLogNotice() << event.gestureName << getGestureStatusAsString(event.gestureStatus) << "from device" << event.deviceID << "at" << event.timestampMillis;
}

//--------------------------------------------------------------
void testApp::exit(){
    openNIRecorder.stop();
    openNIPlayer.stop();
}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

    int cloudRes = -1;
    string fileName = "test_20140501_1904.oni";
    switch (key) {
        case ' ':
            if(!openNIRecorder.isRecording()){
//                openNIRecorder.startRecording(ofToDataPath("test"+ std::to_string(ofGetSystemTimeMicros()/1000)+".oni"));
                openNIRecorder.startRecording(ofToDataPath(fileName));
            }else{
                openNIRecorder.stopRecording();
            }
            break;
        case 'p':
            openNIPlayer.startPlayer(fileName);
            break;
        case '/':
            openNIPlayer.setPaused(!openNIPlayer.isPaused());
            break;
        case 'm':
            openNIPlayer.firstFrame();
            break;
        case '<':
        case ',':
            openNIPlayer.previousFrame();
            break;
        case '>':
        case '.':
            openNIPlayer.nextFrame();
            break;
        case 'x':
            openNIRecorder.stop();
            openNIPlayer.stop();
            break;
        case 't':
            openNIRecorder.toggleRegister();
            break;
    }

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}<commit_msg>First attempt to get bone data out of an ONI recording — no dice.<commit_after>#include "testApp.h"

class myUser : public ofxOpenNIUser {
public:
    void test(){
        cout << "test" << endl;
    }
};

//-- functions and properties which might be useful for recording skeletal data
//////////////////////
// ofxOpenNITypes.cpp
//////////////////////
//    void ofxOpenNIUser::drawSkeleton() {
//        ofPushStyle();
//        // DON'T NEED TO DRAW LIMBS ANYMORE!
//        //	for(int i = 0; i < limbs.size(); i++){
//        //		limbs[i].draw();
//        //	}
//        for(int i = 0; i < joints.size(); i++){
//            joints[i].draw();
//        }
//        ofPopStyle();
//    }
//
//    ofPixels & ofxOpenNIDepthThreshold::getDepthPixels(){
//        return depthPixels;
//    }
//
//    ofPixels & ofxOpenNIDepthThreshold::getMaskPixels(){
//        return maskPixels;
//    }
//
//////////////////////
// ofxOpenNI.cpp
//////////////////////
//    ofPixels& ofxOpenNI::getDepthPixels();
//    ofPixels& ofxOpenNI::getImagePixels();
//    xn::UserGenerator& ofxOpenNI::getUserGenerator();
//    drawSkeletons();
//    if(g_bIsDepthOn) drawDepth();
//    if(g_bIsHandsOn) drawHands();
//    if(g_bIsUserOn) drawSkeletons();
//    ofTranslate(getWidth(), 0.0f);
//    if(g_bIsImageOn || g_bIsInfraOn) drawImage();
// 	currentTrackedUsers[currentTrackedUserIDs[nID]].drawSkeleton();
//
//////////////////////
// ofxOpenNI.h
//////////////////////
//    bool setSkeletonProfile(XnSkeletonProfile profile);
//    XnSkeletonProfile getSkeletonProfile();
//    xn::UserGenerator& getUserGenerator();
//    xn::DepthGenerator& getDepthGenerator();
//    xn::ImageGenerator& getImageGenerator();
//    xn::DepthMetaData& getDepthMetaData();
//    xn::ImageMetaData& getImageMetaData();
//    ofEvent<ofxOpenNIUserEvent> userEvent;
//
//////////////////////
// ofxOpenNiUtils.h
//////////////////////
//    enum Joint
//    enum Limb
//    static inline ofPoint g_worldToProjective(const ofPoint& p)
//    static inline ofPoint g_projectiveToWorld(const ofPoint& p)
//    static inline ofPoint worldToProjective(const XnVector3D& p, xn::DepthGenerator & g_Depth)
//    inline Joint XnToOfJoint(XnSkeletonJoint type)
//    inline string getXNJointAsString(XnSkeletonJoint type)
//    inline string getJointAsString(Joint type)
//    inline string getLimbAsString(Limb type)
//    inline string getUserStatusAsString(UserStatusType type)
//    inline string getCalibrationStatusAsString(XnCalibrationStatus type)
//
//////////////////////
// ofxOpenNiTypes.h
//////////////////////
// class ofxOpenNIJoint
//      ofPoint & getProjectivePosition()
//      ofPoint & getWorldPosition()
// class ofxOpenNILimb
//    void draw() {
//
//        ofPushStyle();
//        if(isFound()){
//            // draw in green
//            ofSetColor(0, 255, 0);
//        }else{
//            // draw in red
//            ofSetColor(255, 0, 0);
//        }
//        ofSetLineWidth(5);
//        ofLine(ofVec2f(startJoint->getProjectivePosition()),ofVec2f(endJoint->getProjectivePosition()));
//        ofPopStyle();
//    }
// inline int numJointsInside(ofxOpenNIUser & user)
//
////////////////////////
// ofUtils --
////////////////////////
// ofGetDay()
// ofGetFrameNum()
// ofGetHours()
// ofGetMinutes()
// ofGetMonth()
// ofGetSeconds()
// ofGetSystemTimeMicros()
// ofGetYear()
// ofToString() // "the number is " + ofToString(10)
//////////////
// ofLog -- http://www.openframeworks.cc/documentation/utils/ofLog.html
//////////////
//class methods
//    ofLog()
//    setAutoSpace()
//    setChannel()
//global functions
//    ofGetLogLevel()
//    ofGetLogLevelName()
//    ofLogToConsole()
//    ofLogToFile()
//    ofSetLogLevel()
//    ofSetLoggerChannel()

//--------------------------------------------------------------
void testApp::setup() {

    ofSetLogLevel(OF_LOG_VERBOSE);

    // TODO:
    //  - get bones showing up for player
    //      - Might need to turn the recorder off in order for the user generator of the player to work (think there can only be one instance of the user  generator)
    //  - capture bone data and save it out to a CSV that can be loaded in MATLAB
    //  - capture image and depth data, and save them to videos

//    openNIRecorder.setup();
//    openNIRecorder.addDepthGenerator();
//    openNIRecorder.addImageGenerator();
//    openNIRecorder.setRegister(true);
//    openNIRecorder.setMirror(true);
//    openNIRecorder.addUserGenerator();
//    openNIRecorder.setMaxNumUsers(2);
//    openNIRecorder.start();

    openNIPlayer.setup();
    openNIPlayer.addDepthGenerator();
    openNIPlayer.addImageGenerator();
    openNIPlayer.setRegister(true);
    openNIPlayer.setMirror(true);
    openNIPlayer.addUserGenerator();
    openNIPlayer.setMaxNumUsers(2);
	openNIPlayer.start();

    verdana.loadFont(ofToDataPath("verdana.ttf"), 24);
}

//--------------------------------------------------------------
void testApp::update(){
//    openNIRecorder.update();
    openNIPlayer.update();
}

//--------------------------------------------------------------
void testApp::draw(){
	ofSetColor(255, 255, 255);

    ofPushMatrix();

//    openNIRecorder.drawDebug(0, 0);
    openNIPlayer.drawDebug(0, 240);
    openNIPlayer.drawSkeletons(0, 240);

//    ofxOpenNIUser::drawSkeleton();
//    ofxOpenNI::drawSkeletons();
//    ofxOpenNI::getUserGenerator()

    ofPushMatrix();

	ofSetColor(0, 255, 0);
	string msg = " MILLIS: " + ofToString(ofGetElapsedTimeMillis()) + " FPS: " + ofToString(ofGetFrameRate());
	verdana.drawString(msg, 20, 2 * 480 - 20);
}

//--------------------------------------------------------------
void testApp::userEvent(ofxOpenNIUserEvent & event){
    ofLogNotice() << getUserStatusAsString(event.userStatus) << "for user" << event.id << "from device" << event.deviceID;
}

//--------------------------------------------------------------
void testApp::gestureEvent(ofxOpenNIGestureEvent & event){
    ofLogNotice() << event.gestureName << getGestureStatusAsString(event.gestureStatus) << "from device" << event.deviceID << "at" << event.timestampMillis;
}

//--------------------------------------------------------------
void testApp::exit(){
//    openNIRecorder.stop();
    openNIPlayer.stop();
}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

    int cloudRes = -1;
    string fileName = "test_20140501_1904.oni";
    switch (key) {
        case ' ':
//            if(!openNIRecorder.isRecording()){
////                openNIRecorder.startRecording(ofToDataPath("test"+ std::to_string(ofGetSystemTimeMicros()/1000)+".oni"));
//                openNIRecorder.startRecording(ofToDataPath(fileName));
//            }else{
//                openNIRecorder.stopRecording();
//            }
            break;
        case 'p':
            openNIPlayer.startPlayer(fileName);
            break;
        case '/':
            openNIPlayer.setPaused(!openNIPlayer.isPaused());
            break;
        case 'm':
            openNIPlayer.firstFrame();
            break;
        case '<':
        case ',':
            openNIPlayer.previousFrame();
            break;
        case '>':
        case '.':
            openNIPlayer.nextFrame();
            break;
        case 'x':
//            openNIRecorder.stop();
            openNIPlayer.stop();
            break;
        case 't':
//            openNIRecorder.toggleRegister();
            break;
    }

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){

}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}<|endoftext|>