<commit_before>#include "rules.hpp"

#include <iostream>
#include <cassert>

#include <QChar>
#include <QTextStream>
#include <QString>

#include "StreamIterator"
#include "TokenRule"
#include "DiscardRule"
#include "SharedRule"
#include "MultipleRule"
#include "OptionalRule"
#include "PredicateRule"
#include "ProxyRule"
#include "AlternativeRule"
#include "ReduceRule"

#include <QRegExp>
#include <QHash>
#include <QElapsedTimer>

using namespace sprout;

enum class TokenType {
    Unknown,
    Name,
    Equal,
    List,
    StringConstant,
    Assignment
};

const char* tokenTypeName(const TokenType type)
{
    switch (type) {
        case TokenType::Unknown: return "Unknown";
        case TokenType::Name: return "Name";
        case TokenType::Equal: return "Equal";
        case TokenType::List: return "List";
        case TokenType::StringConstant: return "StringConstant";
        case TokenType::Assignment: return "Assignment";
        default:
            std::stringstream str;
            str << "Unexpected TokenType: " << static_cast<int>(type);
            throw std::logic_error(str.str());
    }
}

struct Token {
    TokenType type;
    QString value;

    Token() :
        type(TokenType::Unknown)
    {
    }

    Token(const TokenType& type) :
        type(type)
    {
    }

    Token(const TokenType& type, const QString& value) :
        type(type),
        value(value)
    {
    }
};

struct Node {
    Token token;
    std::vector<Node> children;

    Node(const Token& token) :
        token(token)
    {
    }

    Node(const Token& token, std::vector<Node> children) :
        token(token),
        children(children)
    {
    }

    TokenType type() const
    {
        return token.type;
    }

    const char* typeName() const
    {
        return tokenTypeName(type());
    }

    QString value() const
    {
        return token.value;
    }

    void add(const Node& child)
    {
        children.push_back(child);
    }

    Node operator[](const int index) const
    {
        return children[index];
    }
};

int main(int argc, char* argv[])
{
    using namespace make;

    auto whitespace = rule::whitespace<QString>();

    auto name = convert<Node>(
        aggregate<QString>(
            multiple(simplePredicate<QChar>([](const QChar& input) {
                return input.isLetter() || input == '_';
            })),
            [](QString& target, const QChar& c) {
                target += c;
            }
        ),
        [](QString& value) {
            return Node(Token(TokenType::Name, value));
        }
    );

    auto definition = proxySequence<QChar, Node>(
        discard(proxySequence<QChar, QString>(
            OrderedTokenRule<QChar, QString>("var"),
            whitespace
        )),
        name
    );

    auto stringConstant = convert<Node>(
        rule::quotedString,
        [](QString& value) {
            return Node(Token(TokenType::StringConstant, value));
        }
    );

    auto rvalue = shared(proxyAlternative<QChar, Node>(
        convert<Node>(
            rule::floating,
            [](const float& value) {
                return Node(
                    Token(TokenType::StringConstant, QString::number(value))
                );
            }
        ),
        convert<Node>(
            rule::integer,
            [](const long value) {
                return Node(
                    Token(TokenType::StringConstant, QString::number(value))
                );
            }
        ),
        stringConstant,
        name
    ));

    auto ws = discard(optional(whitespace));

    auto list = reduce<Node>(
        proxySequence<QChar, Node>(
            discard(OrderedTokenRule<QChar, QString>("[")),
            optional(proxySequence<QChar, Node>(
                ws,
                rvalue,
                ws,
                optional(multiple(proxySequence<QChar, Node>(
                    discard(OrderedTokenRule<QChar, QString>(",")),
                    ws,
                    rvalue,
                    ws
                ))),
                ws,
                discard(optional(OrderedTokenRule<QChar, QString>(",")))
            )),
            ws,
            discard(OrderedTokenRule<QChar, QString>("]"))
        ),
        [](Result<Node>& target, Result<Node>& items) {
            target << Node(
                TokenType::List,
                items.data()
            );
        }
    );

    rvalue << list;

    auto assignment = reduce<Node>(
        proxySequence<QChar, Node>(
            name,
            discard(proxySequence<QChar, QString>(
                optional(whitespace),
                OrderedTokenRule<QChar, QString>("="),
                optional(whitespace)
            )),
            rvalue,
            discard(optional(whitespace)),
            discard(optional(OrderedTokenRule<QChar, QString>(";")))
        ),
        [](Result<Node>& results, Result<Node>& subresults) {
            results << Node(
                TokenType::Assignment,
                subresults.data()
            );
        }
    );

    auto parser = proxySequence<QChar, Node>(
        proxyAlternative<QChar, Node>(
            assignment,
            name
        ),
        make::end<QChar, Node>()
    );

    QTextStream stream(stdin);
    stream.setCodec("UTF-8");

    QHash<QString, QString> globals;

    QString line;
    while (true) {
        std::cout << "sprout> ";
        line = stream.readLine();
        if (line.isNull()) {
            break;
        }

        QTextStream lineStream(&line);
        auto cursor = makeCursor<QChar>(&lineStream);

        Result<Node> nodes;
        if (parser(cursor, nodes)) {
            for (auto node : nodes) {
                switch (node.type()) {
                    case TokenType::Name:
                        {
                            auto name = node.value();
                            std::cout << globals[name].toUtf8().constData() << std::endl;
                            break;
                        }
                    case TokenType::Assignment:
                        {
                            auto name = node[0].value();
                            auto result = node[1];
                            switch (result.type()) {
                                case TokenType::Name:
                                    globals[name] = globals[result.value()];
                                    break;
                                case TokenType::StringConstant:
                                    globals[name] = result.value();
                                    break;
                                default:
                                    std::cout << "Unhandled type: " << result.typeName() << std::endl;
                                    break;
                            }
                            break;
                        }
                    default:
                        std::cout << "Unhandled type: " << node.typeName() << std::endl;
                        break;
                }
            }
        } else {
            std::cout << "Failed to parse\n";
        }
    }

    return 0;
}

// vim: set ts=4 sw=4 :
<commit_msg>Added pretty-printing for created trees<commit_after>#include "rules.hpp"

#include <iostream>
#include <cassert>

#include <QChar>
#include <QTextStream>
#include <QString>

#include "StreamIterator"
#include "TokenRule"
#include "DiscardRule"
#include "SharedRule"
#include "MultipleRule"
#include "OptionalRule"
#include "PredicateRule"
#include "ProxyRule"
#include "AlternativeRule"
#include "ReduceRule"

#include <QRegExp>
#include <QHash>
#include <QElapsedTimer>

using namespace sprout;

enum class TokenType {
    Unknown,
    Name,
    Equal,
    List,
    StringConstant,
    Assignment
};

const char* tokenTypeName(const TokenType type)
{
    switch (type) {
        case TokenType::Unknown: return "Unknown";
        case TokenType::Name: return "Name";
        case TokenType::Equal: return "Equal";
        case TokenType::List: return "List";
        case TokenType::StringConstant: return "StringConstant";
        case TokenType::Assignment: return "Assignment";
        default:
            std::stringstream str;
            str << "Unexpected TokenType: " << static_cast<int>(type);
            throw std::logic_error(str.str());
    }
}

struct Token {
    TokenType type;
    QString value;

    Token() :
        type(TokenType::Unknown)
    {
    }

    Token(const TokenType& type) :
        type(type)
    {
    }

    Token(const TokenType& type, const QString& value) :
        type(type),
        value(value)
    {
    }
};

struct Node {
    Token token;
    std::vector<Node> children;

    Node(const Token& token) :
        token(token)
    {
    }

    Node(const Token& token, std::vector<Node> children) :
        token(token),
        children(children)
    {
    }

    TokenType type() const
    {
        return token.type;
    }

    const char* typeName() const
    {
        return tokenTypeName(type());
    }

    QString value() const
    {
        return token.value;
    }

    void add(const Node& child)
    {
        children.push_back(child);
    }

    Node operator[](const int index) const
    {
        return children[index];
    }

    void dump(std::stringstream& str, const std::string& indent) const
    {
        str << typeName();
        if (!value().isNull()) {
            str << ":" << value().toUtf8().constData();
        }
        if (!children.empty()) {
            auto childIndent = indent + "    ";
            str << " [\n" << childIndent;
            for (int i = 0; i < children.size(); ++i) {
                if (i > 0) {
                    str << ",\n" << childIndent;
                }
                children[i].dump(str, childIndent);
            }
            str << "\n" << indent << "]";
        }
    }

    std::string dump() const
    {
        std::stringstream str;
        dump(str, "");
        return str.str();
    }
};

int main(int argc, char* argv[])
{
    using namespace make;

    auto whitespace = rule::whitespace<QString>();

    auto name = convert<Node>(
        aggregate<QString>(
            multiple(simplePredicate<QChar>([](const QChar& input) {
                return input.isLetter() || input == '_';
            })),
            [](QString& target, const QChar& c) {
                target += c;
            }
        ),
        [](QString& value) {
            return Node(Token(TokenType::Name, value));
        }
    );

    auto definition = proxySequence<QChar, Node>(
        discard(proxySequence<QChar, QString>(
            OrderedTokenRule<QChar, QString>("var"),
            whitespace
        )),
        name
    );

    auto stringConstant = convert<Node>(
        rule::quotedString,
        [](QString& value) {
            return Node(Token(TokenType::StringConstant, value));
        }
    );

    auto rvalue = shared(proxyAlternative<QChar, Node>(
        convert<Node>(
            rule::floating,
            [](const float& value) {
                return Node(
                    Token(TokenType::StringConstant, QString::number(value))
                );
            }
        ),
        convert<Node>(
            rule::integer,
            [](const long value) {
                return Node(
                    Token(TokenType::StringConstant, QString::number(value))
                );
            }
        ),
        stringConstant,
        name
    ));

    auto ws = discard(optional(whitespace));

    auto list = reduce<Node>(
        proxySequence<QChar, Node>(
            discard(OrderedTokenRule<QChar, QString>("[")),
            optional(proxySequence<QChar, Node>(
                ws,
                rvalue,
                ws,
                optional(multiple(proxySequence<QChar, Node>(
                    discard(OrderedTokenRule<QChar, QString>(",")),
                    ws,
                    rvalue,
                    ws
                ))),
                ws,
                discard(optional(OrderedTokenRule<QChar, QString>(",")))
            )),
            ws,
            discard(OrderedTokenRule<QChar, QString>("]"))
        ),
        [](Result<Node>& target, Result<Node>& items) {
            target << Node(
                TokenType::List,
                items.data()
            );
        }
    );

    rvalue << list;

    auto assignment = reduce<Node>(
        proxySequence<QChar, Node>(
            name,
            discard(proxySequence<QChar, QString>(
                optional(whitespace),
                OrderedTokenRule<QChar, QString>("="),
                optional(whitespace)
            )),
            rvalue,
            discard(optional(whitespace)),
            discard(optional(OrderedTokenRule<QChar, QString>(";")))
        ),
        [](Result<Node>& results, Result<Node>& subresults) {
            results << Node(
                TokenType::Assignment,
                subresults.data()
            );
        }
    );

    auto parser = proxySequence<QChar, Node>(
        proxyAlternative<QChar, Node>(
            assignment,
            name
        ),
        make::end<QChar, Node>()
    );

    QTextStream stream(stdin);
    stream.setCodec("UTF-8");

    QHash<QString, QString> globals;

    QString line;
    while (true) {
        std::cout << "sprout> ";
        line = stream.readLine();
        if (line.isNull()) {
            break;
        }

        QTextStream lineStream(&line);
        auto cursor = makeCursor<QChar>(&lineStream);

        Result<Node> nodes;
        if (parser(cursor, nodes)) {
            for (auto node : nodes) {
                switch (node.type()) {
                    case TokenType::Name:
                        {
                            auto name = node.value();
                            std::cout << globals[name].toUtf8().constData() << std::endl;
                            break;
                        }
                    case TokenType::Assignment:
                        {
                            auto name = node[0].value();
                            auto result = node[1];
                            switch (result.type()) {
                                case TokenType::Name:
                                    globals[name] = globals[result.value()];
                                    break;
                                case TokenType::StringConstant:
                                    globals[name] = result.value();
                                    break;
                                default:
                                    std::cout << "Unhandled type: " << result.typeName() << std::endl;
                                    break;
                            }
                            break;
                        }
                    default:
                        std::cout << "Unhandled type: " << node.typeName() << std::endl;
                        break;
                }
            }
        } else {
            std::cout << "Failed to parse\n";
        }
    }

    return 0;
}

// vim: set ts=4 sw=4 :
<|endoftext|>


<commit_before>#define EIGEN2_SUPPORT

#ifdef DMTruncate
#define DENSITY_MATRIX_TRUNCATION_TOLERANCE 1e-3
#define TERM_MATRIX_ELEMENT_TOLERANCE 1e-3
#define TERM_RESONANCE_TOLERANCE 1e-16
#endif

#include "config.h"
#include "output.h"
#include "LatticeAnalysis.h"
#include "Term.h"
#include "BitClassification.h"
#include "StatesClassification.h"
#include "HamiltonianPart.h"
#include "Hamiltonian.h"
#include "FieldOperatorPart.h"
#include "FieldOperator.h"
#include "GreensFunction.h"
#include "GFContainer.h"
#include "TwoParticleGF.h"
#include "TwoParticleGFContainer.h"
#include "Vertex4.h"

#include<fstream>
#include "iniconfig.h"

string input = "system.ini";

LatticeAnalysis Lattice;
BitClassification IndexInfo(Lattice);
StatesClassification S(IndexInfo);
output_handle OUT;
Hamiltonian H(IndexInfo,S,OUT,input);

ostream &OUTPUT_STREAM=std::cout;

IniConfig* pIni;

int main()
{

    cout << "=======================" << endl;
    cout << "Lattice Info" << endl;
    cout << "=======================" << endl;
    Lattice.readin();
    cout << Lattice.printSitesList().str() << flush;
    IndexInfo.prepare();
    cout << "=======================" << endl;
    cout << "System Info" << endl;
    cout << "=======================" << endl;
    IndexInfo.printBitInfoList();
    cout << "=======================" << endl;
    cout << "Hopping Matrix" << endl;
    cout << "=======================" << endl;
    IndexInfo.printHoppingMatrix();
    cout << "=======================" << endl;
    cout << "Terms check" << endl;
    cout << "=======================" << endl;
    IndexInfo.printTerms();
    //determination of system

    pIni = new IniConfig(input);

    OUT = output_handle((*pIni)["output:path"]);

    S.iniStatesClassification();

    //end of determination

    cout << "=======================" << endl;
    cout << "System is determined" << endl;
    cout << "=======================" << endl;
    cout << "=======================================" << endl;
    cout << "Process of creation and diagonalization" << endl;
    cout << "all parts of  Hamiltonian  has  started" << endl;
    cout << endl;

    //begining of creation all part of Hammiltonian

    H.enter();
    H.dump();
    H.diagonalize();
    RealType beta = (*pIni)["Green Function:beta"];
    RealType ProbabilityCutoff = RealType((*pIni)["system:ProbabilityCutoff"]);
    if (ProbabilityCutoff>0 && ProbabilityCutoff < 1) H.reduce(-log(ProbabilityCutoff)/beta);
    H.dump();

    num_cout << endl << "The value of ground energy is " << H.getGroundEnergy() << endl;

    DensityMatrix rho(S,H,beta);
//    DensityMatrix.reduce();
    rho.prepare();
    rho.compute();
    num_cout << "<H> = " << rho.getAverageEnergy() << endl;

 /*   for (QuantumState i=0; i < S.N_st(); ++i)
        cout << std::setw(20) << "E:" << H.eigenval(i) << "\t E-E0 " << H.eigenval(i) - rho.getAverageEnergy() << "\t weight: " << rho(i) << "  " << exp(-beta*(H.eigenval(i) - H.getGroundEnergy()))/1.000 << endl;
        */
    std::ofstream out;
    out.open("output/Stat.En.dat");
    out << iomanip_prefs << rho.getAverageEnergy() << endl;
    out.close();

    //finishing of creation
    cout << endl;
    cout << "All parts are created!" << endl;
    cout << endl;

    FieldOperatorContainer Operators(S,H,IndexInfo);
    GFContainer G(S,H,rho,IndexInfo,Operators);
    G.prepare();
    G.compute();
    cout << std::setprecision(9) << G(0) << endl;
    cout << std::setprecision(9) << G(1) << endl;

    if ((*pIni)["System:calculate_2PGF"]){
        cout << endl;
        cout << "==========================================" << endl;
        cout << "Two Particle Green's function calculation" << endl;
        cout << "==========================================" << endl;

        TwoParticleGFContainer::IndexCombination *comb1;
        std::vector<TwoParticleGFContainer::IndexCombination*> v1;

        comb1 = new TwoParticleGFContainer::IndexCombination(0,0,0,0);
        v1.push_back(comb1);
//
        TwoParticleGFContainer Chi4(S,H,rho,IndexInfo,Operators);
        Chi4.readNonTrivialIndices(v1);
        Chi4.prepare();
        Chi4.compute(30);

        for (unsigned short i=0;i<v1.size();i++){
            cout << std::setprecision(9) << Chi4(*v1[i],3,2,0) << endl;
            cout << Chi4(*v1[i],2,5,2) << endl;
            cout << Chi4(*v1[i],5,2,2) << endl;
            cout << Chi4(*v1[i],1,7,1) << endl;
            cout << Chi4(*v1[i],2,-2,4) << endl;
            cout << Chi4(*v1[i],29,-29,29) << endl << endl;
        cout << *v1[i] << " : " << (bool) Chi4.vanishes(*v1[i]) << endl;
        };

     //   comb1 = new TwoParticleGFContainer::IndexCombination(0,2,0,1);
     //   cout << Chi4.vanishes(*comb1) << endl;
        //DEBUG(Chi4.getNumNonResonantTerms() << " non-resonant terms");
        //DEBUG(Chi4.getNumResonantTerms() << " resonant terms");
    };

    exit(0);
    int i = 1; //(*pIni)["Green Function:i"];
    int j = 1; //(*pIni)["Green Function:j"];
    cout << endl;
    cout << "==========================================" << endl;
    cout << "Beginning of rotation of matrices C and CX" << endl;
    CreationOperator CX(S,H,i);
    CX.prepare();
    CX.compute();
    //CX.dump();

    AnnihilationOperator C(S,H,j);
    C.prepare();
    C.compute();
    //C.dump();

    // DEBUG
    /*std::list<BlockMapping> ind = CX.getNonTrivialIndices();

    std::list<std::pair<BlockNumber,BlockNumber> >::iterator it;
    for (it=ind.begin();it!=ind.end();it++)
    { cout << (*it).first << "," << (*it).second << " = " << CX.getLeftIndex((*it).second) << "," << CX.getRightIndex((*it).first) << endl;
    }
*/

/*    cout << endl;
    cout << "==========================================" << endl;
    cout << "Calculating G_{" << i << j << "}" << endl;
    cout << "==========================================" << endl;
      GreensFunction G(S,H,C,CX,rho);
        G.prepare();
        cout << G.vanishes() << endl;
        G.compute();

        //std::list<GreensFunctionPart::GreensTerm> terms = G.getTerms();
        //for(std::list<GreensFunctionPart::GreensTerm>::iterator term = terms.begin(); term != terms.end(); term++)
        //    DEBUG(*term)

    G.dumpMatsubara((int)(*pIni)["Green Function:points"]);
    cout << endl << "All done." << endl;

    cout << i << j << ": G.vanishes() = " << G.vanishes() << endl;

  */
return 0;
};
/*
    //begining of creation matrixes C and CX

    // parameters of Green Function

    if ((*pIni)["System:calculate_2PGF"]){
        cout << endl;
        cout << "==========================================" << endl;
        cout << "Two Particle Green's function calculation" << endl;
        cout << "==========================================" << endl;

        AnnihilationOperator C1(S,H,OUT,i);
        C1.prepare();
        C1.compute();
        AnnihilationOperator C2(S,H,OUT,j);
        C2.prepare();
        C2.compute();
        CreationOperator CX3(S,H,OUT,i);
        CX3.prepare();
        CX3.compute();
        CreationOperator CX4(S,H,OUT,j);
        CX4.prepare();
        CX4.compute();

        TwoParticleGF CurrentChi4(S,H,C1,C2,CX3,CX4,rho);
        CurrentChi4.prepare();
        CurrentChi4.compute(30);
        //Chi4.dump();

        cout << CurrentChi4(3,2,0) << endl;
        cout << CurrentChi4(2,5,2) << endl;
        cout << CurrentChi4(5,2,2) << endl;
        cout << CurrentChi4(1,7,1) << endl;
        cout << CurrentChi4(2,-2,4) << endl;
        cout << CurrentChi4(29,-29,29) << endl;

        //Vertex4 Gamma4(Chi4,G,G,G,G);
        //cout << Gamma4(0,2,0) << endl;
        }
    return 0;
}
*/
<commit_msg>Test line<commit_after>#define EIGEN2_SUPPORT

#ifdef DMTruncate
#define DENSITY_MATRIX_TRUNCATION_TOLERANCE 1e-3
#define TERM_MATRIX_ELEMENT_TOLERANCE 1e-3
#define TERM_RESONANCE_TOLERANCE 1e-16
#endif

#include "config.h"
#include "output.h"
#include "LatticeAnalysis.h"
#include "Term.h"
#include "BitClassification.h"
#include "StatesClassification.h"
#include "HamiltonianPart.h"
#include "Hamiltonian.h"
#include "FieldOperatorPart.h"
#include "FieldOperator.h"
#include "GreensFunction.h"
#include "GFContainer.h"
#include "TwoParticleGF.h"
#include "TwoParticleGFContainer.h"
#include "Vertex4.h"

#include<fstream>
#include "iniconfig.h"

string input = "system.ini";

LatticeAnalysis Lattice;
BitClassification IndexInfo(Lattice);
StatesClassification S(IndexInfo);
output_handle OUT;
Hamiltonian H(IndexInfo,S,OUT,input);

ostream &OUTPUT_STREAM=std::cout;

IniConfig* pIni;

int main()
{

    cout << "=======================" << endl;
    cout << "Lattice Info" << endl;
    cout << "=======================" << endl;
    Lattice.readin();
    cout << Lattice.printSitesList().str() << flush;
    IndexInfo.prepare();
    cout << "=======================" << endl;
    cout << "System Info" << endl;
    cout << "=======================" << endl;
    IndexInfo.printBitInfoList();
    cout << "=======================" << endl;
    cout << "Hopping Matrix" << endl;
    cout << "=======================" << endl;
    IndexInfo.printHoppingMatrix();
    cout << "=======================" << endl;
    cout << "Terms check" << endl;
    cout << "=======================" << endl;
    IndexInfo.printTerms();
    //determination of system

    pIni = new IniConfig(input);

    OUT = output_handle((*pIni)["output:path"]);

    S.iniStatesClassification();

    //end of determination

    cout << "=======================" << endl;
    cout << "System is determined" << endl;
    cout << "=======================" << endl;
    cout << "=======================================" << endl;
    cout << "Process of creation and diagonalization" << endl;
    cout << "all parts of  Hamiltonian  has  started" << endl;
    cout << endl;

    //begining of creation all part of Hammiltonian

    H.enter();
    H.dump();
    H.diagonalize();
    RealType beta = (*pIni)["Green Function:beta"];
    RealType ProbabilityCutoff = RealType((*pIni)["system:ProbabilityCutoff"]);
    if (ProbabilityCutoff>0 && ProbabilityCutoff < 1) H.reduce(-log(ProbabilityCutoff)/beta);
    H.dump();

    num_cout << endl << "The value of ground energy is " << H.getGroundEnergy() << endl;

    DensityMatrix rho(S,H,beta);
//    DensityMatrix.reduce();
    rho.prepare();
    rho.compute();
    num_cout << "<H> = " << rho.getAverageEnergy() << endl;

 /*   for (QuantumState i=0; i < S.N_st(); ++i)
        cout << std::setw(20) << "E:" << H.eigenval(i) << "\t E-E0 " << H.eigenval(i) - rho.getAverageEnergy() << "\t weight: " << rho(i) << "  " << exp(-beta*(H.eigenval(i) - H.getGroundEnergy()))/1.000 << endl;
        */
    std::ofstream out;
    out.open("output/Stat.En.dat");
    out << iomanip_prefs << rho.getAverageEnergy() << endl;
    out.close();

    //finishing of creation
    cout << endl;
    cout << "All parts are created!" << endl;
    cout << endl;

    FieldOperatorContainer Operators(S,H,IndexInfo);
    GFContainer G(S,H,rho,IndexInfo,Operators);
    G.prepare();
    G.compute();
    cout << std::setprecision(9) << G(0) << endl;
    cout << std::setprecision(9) << G(1) << endl;

    if ((*pIni)["System:calculate_2PGF"]){
        cout << endl;
        cout << "==========================================" << endl;
        cout << "Two Particle Green's function calculation" << endl;
        cout << "==========================================" << endl;

        TwoParticleGFContainer::IndexCombination *comb1;
        std::vector<TwoParticleGFContainer::IndexCombination*> v1;

        comb1 = new TwoParticleGFContainer::IndexCombination(0,0,0,0);
        v1.push_back(comb1);
        comb1 = new TwoParticleGFContainer::IndexCombination(0,1,0,1);
        v1.push_back(comb1);
//
        TwoParticleGFContainer Chi4(S,H,rho,IndexInfo,Operators);
        Chi4.readNonTrivialIndices(v1);
        Chi4.prepare();
        Chi4.compute(30);

        for (unsigned short i=0;i<v1.size();i++){
            cout << std::setprecision(9) << Chi4(*v1[i],3,2,0) << endl;
            cout << Chi4(*v1[i],2,5,2) << endl;
            cout << Chi4(*v1[i],5,2,2) << endl;
            cout << Chi4(*v1[i],1,7,1) << endl;
            cout << Chi4(*v1[i],2,-2,4) << endl;
            cout << Chi4(*v1[i],29,-29,29) << endl << endl;
        cout << *v1[i] << " : " << (bool) Chi4.vanishes(*v1[i]) << endl;
        };

     //   comb1 = new TwoParticleGFContainer::IndexCombination(0,2,0,1);
     //   cout << Chi4.vanishes(*comb1) << endl;
        //DEBUG(Chi4.getNumNonResonantTerms() << " non-resonant terms");
        //DEBUG(Chi4.getNumResonantTerms() << " resonant terms");
    };

    exit(0);
    int i = 1; //(*pIni)["Green Function:i"];
    int j = 1; //(*pIni)["Green Function:j"];
    cout << endl;
    cout << "==========================================" << endl;
    cout << "Beginning of rotation of matrices C and CX" << endl;
    CreationOperator CX(S,H,i);
    CX.prepare();
    CX.compute();
    //CX.dump();

    AnnihilationOperator C(S,H,j);
    C.prepare();
    C.compute();
    //C.dump();

    // DEBUG
    /*std::list<BlockMapping> ind = CX.getNonTrivialIndices();

    std::list<std::pair<BlockNumber,BlockNumber> >::iterator it;
    for (it=ind.begin();it!=ind.end();it++)
    { cout << (*it).first << "," << (*it).second << " = " << CX.getLeftIndex((*it).second) << "," << CX.getRightIndex((*it).first) << endl;
    }
*/

/*    cout << endl;
    cout << "==========================================" << endl;
    cout << "Calculating G_{" << i << j << "}" << endl;
    cout << "==========================================" << endl;
      GreensFunction G(S,H,C,CX,rho);
        G.prepare();
        cout << G.vanishes() << endl;
        G.compute();

        //std::list<GreensFunctionPart::GreensTerm> terms = G.getTerms();
        //for(std::list<GreensFunctionPart::GreensTerm>::iterator term = terms.begin(); term != terms.end(); term++)
        //    DEBUG(*term)

    G.dumpMatsubara((int)(*pIni)["Green Function:points"]);
    cout << endl << "All done." << endl;

    cout << i << j << ": G.vanishes() = " << G.vanishes() << endl;

  */
return 0;
};
/*
    //begining of creation matrixes C and CX

    // parameters of Green Function

    if ((*pIni)["System:calculate_2PGF"]){
        cout << endl;
        cout << "==========================================" << endl;
        cout << "Two Particle Green's function calculation" << endl;
        cout << "==========================================" << endl;

        AnnihilationOperator C1(S,H,OUT,i);
        C1.prepare();
        C1.compute();
        AnnihilationOperator C2(S,H,OUT,j);
        C2.prepare();
        C2.compute();
        CreationOperator CX3(S,H,OUT,i);
        CX3.prepare();
        CX3.compute();
        CreationOperator CX4(S,H,OUT,j);
        CX4.prepare();
        CX4.compute();

        TwoParticleGF CurrentChi4(S,H,C1,C2,CX3,CX4,rho);
        CurrentChi4.prepare();
        CurrentChi4.compute(30);
        //Chi4.dump();

        cout << CurrentChi4(3,2,0) << endl;
        cout << CurrentChi4(2,5,2) << endl;
        cout << CurrentChi4(5,2,2) << endl;
        cout << CurrentChi4(1,7,1) << endl;
        cout << CurrentChi4(2,-2,4) << endl;
        cout << CurrentChi4(29,-29,29) << endl;

        //Vertex4 Gamma4(Chi4,G,G,G,G);
        //cout << Gamma4(0,2,0) << endl;
        }
    return 0;
}
*/
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
//using namespace std;

int main (int argc, char **argv)
{

	//bool value use to determine when to kill rshell loop
	bool killrshell = false;

	while (!killrshell)
	{

		//string will store raw user input
		std::string rawinput;

		//simple command prompt print
		printf("%s", "$ ");

		//obtain user input commands
		std::getline(std::cin, rawinput);

		//TODO: Parse raw input string for commands and connectors

		//temporary break loop condition: user inputs 'exit'
		if (rawinput.substr(0,4) == "exit")
		{
			killrshell = true;
			break;
		}

		//temporary input handling -- if exit was not entered, output the input.
		printf("\"%s\" was entered.\n", rawinput.c_str());

	}

	return 0;
}
<commit_msg>added removal of comments from raw input<commit_after>#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
//using namespace std;

int main (int argc, char **argv)
{

	//bool value use to determine when to kill rshell loop
	bool killrshell = false;

	while (!killrshell)
	{

		//string will store raw user input
		std::string rawinput;

		//simple command prompt print
		printf("%s", "$ ");

		//obtain user input commands
		std::getline(std::cin, rawinput);

		//temporary break loop condition: user inputs 'exit'
		if (rawinput.substr(0,4) == "exit")
		{
			killrshell = true;
			break;
		}

		//parse through raw input and remove comments if entered
		if (rawinput.find('#') != std::string::npos) rawinput = rawinput.substr(0, rawinput.find('#'));

		//TODO: Parse raw input string for commands and connectors

		//temporary input handling -- if exit was not entered, output the input.
		printf("\"%s\" was entered.\n", rawinput.c_str());

	}

	return 0;
}
<|endoftext|>


<commit_before>#include "common.h"

int main(int argc, const char *argv[])
{
    // read EOS table
    // read abundances
    // browse EOS table and compute rates

    int entries = 0;

    // Read nuclear data (masses)
    entries = read_nuclear_data("data/mass.mas12");
    std::cout << "Read " << entries << " nuclear data entries\n";

    // Read abundance data
    entries = read_abundance_data("data/EOS.compo", "data/EOS.t", "data/EOS.nb", "data/EOS.yq");
    std::cout << "Read " << entries << " nuclear abundance data entries\n";

    // Read EOS data
    EOS_table table;
    int error;
    read_EOS_table("data/elec_capt_rate_ls220.h5", table, &error);
    write_EOS_table("output/table.h5", table, &error);

    entries = table.size();
    std::cout << "Read " << entries << " EOS entries\n";
    table.dump();

    // Perform calculations

    int processed = 0;
    // poor man's multithreading
    #pragma omp parallel for
    for(int m = 0; m < table.m_ln_rho; ++m)
    for(int n = 0; n < table.n_ln_t; ++n)
    for(int o = 0; o < table.o_y_e; ++o)
    for(int p = 0; p < table.p_mu; ++p)
    {
        int i = m*(table.n_ln_t*table.o_y_e*table.p_mu) + n*(table.o_y_e*table.p_mu) + o*table.p_mu + p;
        const double nb = exp(table.ln_rho_eos[m]), T = exp(table.ln_t_eos[n]), Y_e = table.y_e_eos[o], mu_nu = table.mu_nu_eos[p], ec_tab = table.elec_rate_tab_eos[i];
        //if(nb >= 0.1) continue;
        double conditions[3] = {T, nb, Y_e};

        double mu_e = electron_potential(nb, Y_e), eps_mu = average_neutrino_energy(T, mu_nu);

        double rate = 0;
        double total_abundance = 0;
        table.scattering_xs_eos[i] = 0;
        std::vector<element> elements;
        get_abundances(conditions, elements);
        table.elec_rate_tab_eos[i] = table.scattering_xs_eos[i] = 0;

        for(int j = 0; j < elements.size(); ++j)
	{
            int A = elements[j].A, Z = elements[j].Z;
	    double abundance = elements[j].abundance;
            total_abundance += abundance;
            if(A < 2 || Z < 2) continue;

	    if(abundance > 1e-30)
            {
                printf("%e (%e %e %e %e)\n", abundance, elements[j].v[0], elements[j].v[1], elements[j].v[2], elements[j].v[3]);
                table.elec_rate_tab_eos[i] += abundance * electron_capture_fit(A, Z, T, mu_e);
                table.scattering_xs_eos[i] += abundance * nucleus_scattering_cross_section(A, Z, eps_mu, abundance*nb);
            }
	}

        if(elements.size()) //printf("total=%f %d\n", total_abundance, elements.size());
        if(total_abundance > 1e-15 && nb > 1e-4 && nb < 1e-2) printf("%d %d %e %e %e %e %e %e %e %e\n", i, elements.size(), T, nb, Y_e, mu_nu, ec_tab, table.elec_rate_tab_eos[i], table.scattering_xs_eos[i]*1e36, total_abundance);
        ++processed;
        //if(processed % 1000 == 0) std::cout << "Processed " << processed << " states out of " << table.size() << std::endl;

    }

    write_EOS_table("output/table.h5", table, &error);

    return 0;
}
<commit_msg>cleanups<commit_after>#include "common.h"

int main(int argc, const char *argv[])
{
    // read EOS table
    // read abundances
    // browse EOS table and compute rates

    int entries = 0;

    // Read nuclear data (masses)
    entries = read_nuclear_data("data/mass.mas12");
    std::cout << "Read " << entries << " nuclear data entries\n";

    // Read abundance data
    entries = read_abundance_data("data/EOS.compo", "data/EOS.t", "data/EOS.nb", "data/EOS.yq");
    std::cout << "Read " << entries << " nuclear abundance data entries\n";

    // Read EOS data
    EOS_table table;
    int error;
    read_EOS_table("data/elec_capt_rate_ls220.h5", table, &error);
    write_EOS_table("output/table.h5", table, &error);

    entries = table.size();
    std::cout << "Read " << entries << " EOS entries\n";
    table.dump();

    // Perform calculations

    int processed = 0;
    // poor man's multithreading
    #pragma omp parallel for
    for(int m = 0; m < table.m_ln_rho; ++m)
    for(int n = 0; n < table.n_ln_t; ++n)
    for(int o = 0; o < table.o_y_e; ++o)
    for(int p = 0; p < table.p_mu; ++p)
    {
        int i = m*(table.n_ln_t*table.o_y_e*table.p_mu) + n*(table.o_y_e*table.p_mu) + o*table.p_mu + p;
        const double nb = exp(table.ln_rho_eos[m]), T = exp(table.ln_t_eos[n]), Y_e = table.y_e_eos[o], mu_nu = table.mu_nu_eos[p], ec_tab = table.elec_rate_tab_eos[i];
        //if(nb >= 0.1) continue;
        double conditions[3] = {T, nb, Y_e};

        double mu_e = electron_potential(nb, Y_e), eps_mu = average_neutrino_energy(T, mu_nu);

        double rate = 0;
        double total_abundance = 0;
        table.scattering_xs_eos[i] = 0;
        std::vector<element> elements;
        get_abundances(conditions, elements);
        table.elec_rate_tab_eos[i] = table.scattering_xs_eos[i] = 0;

        for(int j = 0; j < elements.size(); ++j)
	{
            int A = elements[j].A, Z = elements[j].Z;
	    double abundance = elements[j].abundance;
            total_abundance += abundance;
            if(A < 2 || Z < 2) continue;

	    if(abundance > 1e-30)
            {
                //printf("%e (%e %e %e %e)\n", abundance, elements[j].v[0], elements[j].v[1], elements[j].v[2], elements[j].v[3]);
                table.elec_rate_tab_eos[i] += abundance * electron_capture_fit(A, Z, T, mu_e);
                table.scattering_xs_eos[i] += abundance * nucleus_scattering_cross_section(A, Z, eps_mu, abundance*nb);
            }
	}

        //if(total_abundance > 1e-15 && nb > 1e-4 && nb < 1e-2) printf("%d %d %e %e %e %e %e %e %e %e\n", i, elements.size(), T, nb, Y_e, mu_nu, ec_tab, table.elec_rate_tab_eos[i], table.scattering_xs_eos[i]*1e36, total_abundance);
        ++processed;
        if(processed % 10000 == 0) std::cout << "Processed " << processed << " states out of " << table.size() << std::endl;

    }

    write_EOS_table("output/table.h5", table, &error);

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Luke San Antonio
 * All rights reserved.
 */
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <thread>

#include "common/log.h"

#include "gfx/gl/driver.h"
#include "gfx/camera.h"
#include "gfx/object.h"
#include "gfx/scene_node.h"
#include "gfx/idriver_ui_adapter.h"

#include "common/software_texture.h"
#include "common/texture_load.h"
#include "common/software_mesh.h"
#include "common/mesh_load.h"

#include "ui/load.h"
#include "ui/freetype_renderer.h"
#include "ui/mouse_logic.h"
#include "ui/simple_controller.h"

#include "map/map.h"
#include "map/json_structure.h"
#include "glad/glad.h"
#include "glfw3.h"

#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include "uv.h"

#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"

game::ui::Mouse_State gen_mouse_state(GLFWwindow* w)
{
  game::ui::Mouse_State ret;

  ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;

  game::Vec<double> pos;
  glfwGetCursorPos(w, &pos.x, &pos.y);
  ret.position = game::vec_cast<int>(pos);

  return ret;
}

void log_gl_limits(game::Log_Severity s) noexcept
{
  GLint i = 0;
  glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i);
  log(s, "GL_MAX_ELEMENTS_VERTICES: %", i);
}

struct Command_Options
{
};

Command_Options parse_command_line(int argc, char**)
{
  Command_Options opt;
  for(int i = 0; i < argc; ++i)
  {
    //auto option = argv[i];
  }
  return opt;
}

int main(int argc, char** argv)
{
  using namespace game;

  set_log_level(Log_Severity::Debug);

  uv_chdir("assets/");

  // Initialize logger.
  Scoped_Log_Init log_init_raii_lock{};

  // Parse command line arguments.
  auto options = parse_command_line(argc - 1, argv+1);

  // Init glfw.
  if(!glfwInit())
    return EXIT_FAILURE;

  auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
  if(!window)
  {
    glfwTerminate();
    return EXIT_FAILURE;
  }

  // Init context + load gl functions.
  glfwMakeContextCurrent(window);
  gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);

  // Log glfw version.
  log_i("Initialized GLFW %", glfwGetVersionString());

  int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);

  // Log GL profile.
  log_i("OpenGL core profile %.%.%", maj, min, rev);

  {
  // Make an OpenGL driver.
  gfx::gl::Driver driver{Vec<int>{1000, 1000}};

  // Make an isometric camera.
  auto cam = gfx::make_isometric_camera();
  use_camera(driver, cam);

  // Build our main mesh using our flat terrain.
  auto terrain_obj = gfx::Object{};
  make_terrain_mesh(*terrain_obj.mesh, make_flat_terrain(0, 25, 25), .01, 1);

  terrain_obj.material->diffuse_color = colors::white;

  load_png("tex/grass.png", *terrain_obj.material->texture);

  terrain_obj.model_matrix = glm::translate(glm::mat4(1.0),
                                            glm::vec3(-12.5, 0.0, -12.5));

  prepare_object(driver, terrain_obj);

  // Load our house structure
  auto house_struct = Json_Structure{"structure/house.json"};

  // This is code smell, right here. The fact that before, we were preparing
  // a temporary but it still worked because of the implementation of
  // Json_Structure and the object sharing mechanism.
  auto house_obj = house_struct.make_obj();
  prepare_object(driver, house_obj);

  std::vector<Structure_Instance> house_instances;
  Structure_Instance moveable_instance{house_struct, Orient::N};

  int fps = 0;
  int time = glfwGetTime();

  // Set up some pre-rendering state.
  driver.clear_color_value(Color{0x55, 0x66, 0x77});
  driver.clear_depth_value(1.0);

  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

  // Our quick hack to avoid splitting into multiple functions and dealing
  // either with global variables or like a bound struct or something.
  bool has_clicked_down = false;

  // Load our ui
  gfx::IDriver_UI_Adapter ui_adapter{driver};
  ui::Freetype_Renderer freetype_font;

  auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter};
  auto hud = ui::load("ui/hud.json", ui_load_params);

  auto controller = ui::Simple_Controller{};

  hud->find_child_r("build_button")->add_click_listener([](auto const& pt)
  {
    log_i("BUILD!");
  });

  hud->layout(driver.window_extents());

  controller.add_click_listener([&](auto const&)
  {
    // Commit the current position of our moveable instance.
    house_instances.push_back(moveable_instance);
  });
  controller.add_hover_listener([&](auto const& pt)
  {
    if(pt.x < 0 || pt.x > 1000.0 || pt.y < 0 || pt.y > 1000.0)
    {
      moveable_instance.obj.model_matrix = glm::mat4(1.0);
    }
    else
    {
      // Find our depth.
      GLfloat z;
      glReadPixels((float) pt.x, (float) 1000.0 - pt.y, 1, 1,
                   GL_DEPTH_COMPONENT, GL_FLOAT, &z);

      // Unproject our depth.
      auto val = glm::unProject(glm::vec3(pt.x, 1000.0 - pt.y, z),
                                camera_view_matrix(cam),
                                camera_proj_matrix(cam),
                                glm::vec4(0.0, 0.0, 1000.0, 1000.0));

      // We have our position, render a single house there.
      moveable_instance.obj.model_matrix = glm::translate(glm::mat4(1.0), val);
    }
    // Move the house by however much the structure *type* requires.
    moveable_instance.obj.model_matrix = moveable_instance.obj.model_matrix *
                                         house_struct.make_obj().model_matrix;
  });
  while(!glfwWindowShouldClose(window))
  {
    ++fps;
    glfwPollEvents();

    // Clear the screen and render the terrain.
    driver.clear();
    render_object(driver, terrain_obj);

    // Render the terrain before we calculate the depth of the mouse position.
    auto mouse_state = gen_mouse_state(window);
    controller.step(hud, mouse_state);

    // Render our movable instance of a house.
    render_object(driver, moveable_instance.obj);

    // Render all of our other house instances.
    for(auto const& instance : house_instances)
    {
      render_object(driver, instance.obj);
    }

    {
      ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter};
      hud->render(ui_adapter);
    }
    glfwSwapBuffers(window);

    if(int(glfwGetTime()) != time)
    {
      time = glfwGetTime();
      log_d("fps: %", fps);
      fps = 0;
    }

    flush_log();
  }
  }
  glfwTerminate();
  return 0;
}
<commit_msg>Load our terrain!<commit_after>/*
 * Copyright (C) 2015 Luke San Antonio
 * All rights reserved.
 */
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <thread>

#include "common/log.h"

#include "gfx/gl/driver.h"
#include "gfx/camera.h"
#include "gfx/object.h"
#include "gfx/scene_node.h"
#include "gfx/idriver_ui_adapter.h"

#include "common/software_texture.h"
#include "common/texture_load.h"
#include "common/software_mesh.h"
#include "common/mesh_load.h"

#include "ui/load.h"
#include "ui/freetype_renderer.h"
#include "ui/mouse_logic.h"
#include "ui/simple_controller.h"

#include "map/map.h"
#include "map/json_structure.h"
#include "glad/glad.h"
#include "glfw3.h"

#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#include "uv.h"

#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"

game::ui::Mouse_State gen_mouse_state(GLFWwindow* w)
{
  game::ui::Mouse_State ret;

  ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;

  game::Vec<double> pos;
  glfwGetCursorPos(w, &pos.x, &pos.y);
  ret.position = game::vec_cast<int>(pos);

  return ret;
}

void log_gl_limits(game::Log_Severity s) noexcept
{
  GLint i = 0;
  glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i);
  log(s, "GL_MAX_ELEMENTS_VERTICES: %", i);
}

struct Command_Options
{
};

Command_Options parse_command_line(int argc, char**)
{
  Command_Options opt;
  for(int i = 0; i < argc; ++i)
  {
    //auto option = argv[i];
  }
  return opt;
}

int main(int argc, char** argv)
{
  using namespace game;

  set_log_level(Log_Severity::Debug);

  uv_chdir("assets/");

  // Initialize logger.
  Scoped_Log_Init log_init_raii_lock{};

  // Parse command line arguments.
  auto options = parse_command_line(argc - 1, argv+1);

  // Init glfw.
  if(!glfwInit())
    return EXIT_FAILURE;

  auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
  if(!window)
  {
    glfwTerminate();
    return EXIT_FAILURE;
  }

  // Init context + load gl functions.
  glfwMakeContextCurrent(window);
  gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);

  // Log glfw version.
  log_i("Initialized GLFW %", glfwGetVersionString());

  int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
  int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
  int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);

  // Log GL profile.
  log_i("OpenGL core profile %.%.%", maj, min, rev);

  {
  // Make an OpenGL driver.
  gfx::gl::Driver driver{Vec<int>{1000, 1000}};

  // Make an isometric camera.
  auto cam = gfx::make_isometric_camera();
  use_camera(driver, cam);

  // Build our main mesh using our flat terrain.
  auto terrain_obj = gfx::load_object("obj/terrain.obj", "mat/terrain.json");

  terrain_obj.model_matrix = glm::scale(glm::mat4(1.0f),
                                        glm::vec3(4.0f, 2.0f, 4.0f));

  prepare_object(driver, terrain_obj);

  // Load our house structure
  auto house_struct = Json_Structure{"structure/house.json"};

  // This is code smell, right here. The fact that before, we were preparing
  // a temporary but it still worked because of the implementation of
  // Json_Structure and the object sharing mechanism.
  auto house_obj = house_struct.make_obj();
  prepare_object(driver, house_obj);

  std::vector<Structure_Instance> house_instances;
  Structure_Instance moveable_instance{house_struct, Orient::N};

  int fps = 0;
  int time = glfwGetTime();

  // Set up some pre-rendering state.
  driver.clear_color_value(Color{0x55, 0x66, 0x77});
  driver.clear_depth_value(1.0);

  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

  // Our quick hack to avoid splitting into multiple functions and dealing
  // either with global variables or like a bound struct or something.
  bool has_clicked_down = false;

  // Load our ui
  gfx::IDriver_UI_Adapter ui_adapter{driver};
  ui::Freetype_Renderer freetype_font;

  auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter};
  auto hud = ui::load("ui/hud.json", ui_load_params);

  auto controller = ui::Simple_Controller{};

  hud->find_child_r("build_button")->add_click_listener([](auto const& pt)
  {
    log_i("BUILD!");
  });

  hud->layout(driver.window_extents());

  controller.add_click_listener([&](auto const&)
  {
    // Commit the current position of our moveable instance.
    house_instances.push_back(moveable_instance);
  });
  controller.add_hover_listener([&](auto const& pt)
  {
    if(pt.x < 0 || pt.x > 1000.0 || pt.y < 0 || pt.y > 1000.0)
    {
      moveable_instance.obj.model_matrix = glm::mat4(1.0);
    }
    else
    {
      // Find our depth.
      GLfloat z;
      glReadPixels((float) pt.x, (float) 1000.0 - pt.y, 1, 1,
                   GL_DEPTH_COMPONENT, GL_FLOAT, &z);

      // Unproject our depth.
      auto val = glm::unProject(glm::vec3(pt.x, 1000.0 - pt.y, z),
                                camera_view_matrix(cam),
                                camera_proj_matrix(cam),
                                glm::vec4(0.0, 0.0, 1000.0, 1000.0));

      // We have our position, render a single house there.
      moveable_instance.obj.model_matrix = glm::translate(glm::mat4(1.0), val);
    }
    // Move the house by however much the structure *type* requires.
    moveable_instance.obj.model_matrix = moveable_instance.obj.model_matrix *
                                         house_struct.make_obj().model_matrix;
  });
  while(!glfwWindowShouldClose(window))
  {
    ++fps;
    glfwPollEvents();

    // Clear the screen and render the terrain.
    driver.clear();
    render_object(driver, terrain_obj);

    // Render the terrain before we calculate the depth of the mouse position.
    auto mouse_state = gen_mouse_state(window);
    controller.step(hud, mouse_state);

    // Render our movable instance of a house.
    render_object(driver, moveable_instance.obj);

    // Render all of our other house instances.
    for(auto const& instance : house_instances)
    {
      render_object(driver, instance.obj);
    }

    {
      ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter};
      hud->render(ui_adapter);
    }
    glfwSwapBuffers(window);

    if(int(glfwGetTime()) != time)
    {
      time = glfwGetTime();
      log_d("fps: %", fps);
      fps = 0;
    }

    flush_log();
  }
  }
  glfwTerminate();
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>

#include <boost/python.hpp>
#include <boost/python/suite/indexing/indexing_suite.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include "sdd/sdd.hh"

/*------------------------------------------------------------------------------------------------*/

namespace sdd { namespace python {

using namespace boost::python;

/*------------------------------------------------------------------------------------------------*/

struct py_values
{
  object py;

  py_values()
    : py() // default to None
  {}

  py_values(object p)
		: py(p)
  {}

  py_values(const py_values& v)
		: py(v.py)
  {}

  py_values&
  operator=(const py_values& v)
  {
    py = v.py;
    return *this;
  }

  object
  content()
  const noexcept
  {
    return py;
  }

  bool
  operator==(const py_values& rhs)
  const
  {
    return call_method<bool>(py.ptr(), "__eq__", rhs.py);
  }

  bool
  operator<(const py_values& rhs)
  const
  {
    if (rhs.empty())
    {
      return false;
    }
    else if (this->empty())
    {
      return true;
    }
    else
    {
      return call_method<bool>(py.ptr(), "__lt__", rhs.py);
    }
  }

  std::size_t
  hash()
  const
  {
    return empty()
         ? std::hash<int>()(0)
         : static_cast<std::size_t>(call_method<long>(py.ptr() , "__hash__" ));
  }

  std::string
  name()
  const
  {
    return call_method<std::string>(py.ptr(), "__str__" );
  }

  bool
  empty()
  const
  {
    return size() == 0;
  }

  std::size_t
  size()
  const
  {
    return py.is_none() ? 0 : call_method<std::size_t>(py.ptr(), "__len__" );
  }
};

std::ostream&
operator<<(std::ostream& os, const py_values& v)
{
  return os << v.name();
}

py_values
sum(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__or__", rhs.py));
    }
    else
    {
      return lhs;
    }
  }
  else
  {
    return rhs;
  }
}

py_values
difference(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__sub__", rhs.py));
    }
    else
    {
      return lhs;
    }
  }
  else
  {
    return lhs;
  }
}

py_values
intersection(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__and__", rhs.py));
    }
    else
    {
      return rhs;
    }
  }
  else
  {
    return lhs;
  }
}

} // namespace python

namespace values {

  template <>
  struct values_traits<python::py_values>
  {
    static constexpr bool stateful = false;
    static constexpr bool fast_iterable = false;
    static constexpr bool has_value_type = false;
  };

} // namespace values

namespace python {

/*------------------------------------------------------------------------------------------------*/

struct pyconf
  : public sdd::conf1
{
  using Variable = int;
  using Identifier = std::string;
  using Values = py_values;
};

/*------------------------------------------------------------------------------------------------*/

double
count_combinations(SDD<pyconf> s)
{
  return sdd::count_combinations(s).template convert_to<double>();
}

/*------------------------------------------------------------------------------------------------*/

struct _manager
{
  std::shared_ptr<manager<pyconf>> ptr;

  _manager()
    : ptr(new manager<pyconf>(manager<pyconf>::init()))
  {}
};

/*------------------------------------------------------------------------------------------------*/

inline
object
pass_through(object const& o)
{
  return o;
}

struct paths
{
  path_generator<pyconf> gen;

  paths(const SDD<pyconf>& s)
  noexcept
    : gen(s.paths())
  {
    std::cout << "paths::paths()" << std::endl;
  }

  static
  path<pyconf>
  next(paths& p)
  {
    if (p.gen)
    {
      const path<pyconf> res = p.gen.get();
      p.gen(); // compute next path
      return res;
    }
    else
    {
      PyErr_SetString(PyExc_StopIteration, "No more paths.");
      boost::python::throw_error_already_set();
      const path<pyconf>* dummy = nullptr;
      return *dummy;
    }
  }
};

/*------------------------------------------------------------------------------------------------*/

struct py_visitor
{
  using result_type = object;

  object py;

  py_visitor(object p)
    : py(p)
  {}

  object
  operator()(const hierarchical_node<pyconf>& node)
  const
  {
    return py.attr("hierarchical")(boost::cref(node));
  }

  object
  operator()(const flat_node<pyconf>& node)
  const
  {
    return py.attr("flat")(boost::cref(node));
  }

  object
  operator()(const one_terminal<pyconf>&)
  const
  {
    return py.attr("one")();
  }

  object
  operator()(const zero_terminal<pyconf>&)
  const
  {
    return py.attr("zero")();
  }
};

object
py_visit(object visitor, const SDD<pyconf>& s)
{
  return visit(py_visitor {visitor}, s);
};

/*------------------------------------------------------------------------------------------------*/

BOOST_PYTHON_MODULE(_sdd)
{
  using sdd_type = SDD<pyconf>;
  using hierarchical = hierarchical_node<pyconf>;
  using flat = flat_node<pyconf>;

  class_<_manager, boost::noncopyable>("_manager");

  class_<arc<pyconf, sdd_type>, boost::noncopyable>("HierarchicalArc", no_init)
    .def("valuation", &arc<pyconf, sdd_type>::valuation, return_internal_reference<>())
    .def("successor", &arc<pyconf, sdd_type>::successor)
    ;

  class_<hierarchical, boost::noncopyable>("HierarchicalNode", no_init)
    .def("variable", &hierarchical::variable)
    .def("__iter__", range<return_internal_reference<>>(&hierarchical::begin, &hierarchical::end))
    ;

  class_<arc<pyconf, py_values>, boost::noncopyable>("FlatArc", no_init)
    .def("valuation", &arc<pyconf, py_values>::valuation, return_internal_reference<>())
    .def("successor", &arc<pyconf, py_values>::successor)
    ;

  class_<flat, boost::noncopyable>("FlatNode", no_init)
    .def("variable", &flat::variable)
    .def("__iter__", range<return_internal_reference<>>(&flat::begin, &flat::end))
    ;

  class_<sdd_type>("SDD", init<int, object, sdd_type>())
    .def(init<int, sdd_type, sdd_type>())
    .def(self_ns::str(self))
    .def(self + self)
    .def(self - self)
    .def(self & self)
    .def(self == self)
    .def(self < self)
    .def("__hash__", &sdd_type::hash)
    ;

  def("zero", &zero<pyconf>);
  def("one", &one<pyconf>);

  def("count_combinations", &count_combinations);

  def("visit", &py_visit);

  class_<path<pyconf>>("Path", no_init)
    .def(vector_indexing_suite<path<pyconf>>())
    ;

  class_<paths, boost::noncopyable>("Paths", init<SDD<pyconf>>())
    .def("__iter__", &pass_through)
    .def("next", &paths::next)
    ;

  class_<py_values>("PyValues", no_init)
    .def("content", &py_values::content)
    ;
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::python

namespace std {

/*------------------------------------------------------------------------------------------------*/

template <>
struct hash<sdd::python::py_values>
{
  std::size_t
  operator()(const sdd::python::py_values& val)
  const
  {
    return val.hash();
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace std
<commit_msg>Remove debug output...<commit_after>#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>

#include <boost/python.hpp>
#include <boost/python/suite/indexing/indexing_suite.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include "sdd/sdd.hh"

/*------------------------------------------------------------------------------------------------*/

namespace sdd { namespace python {

using namespace boost::python;

/*------------------------------------------------------------------------------------------------*/

struct py_values
{
  object py;

  py_values()
    : py() // default to None
  {}

  py_values(object p)
		: py(p)
  {}

  py_values(const py_values& v)
		: py(v.py)
  {}

  py_values&
  operator=(const py_values& v)
  {
    py = v.py;
    return *this;
  }

  object
  content()
  const noexcept
  {
    return py;
  }

  bool
  operator==(const py_values& rhs)
  const
  {
    return call_method<bool>(py.ptr(), "__eq__", rhs.py);
  }

  bool
  operator<(const py_values& rhs)
  const
  {
    if (rhs.empty())
    {
      return false;
    }
    else if (this->empty())
    {
      return true;
    }
    else
    {
      return call_method<bool>(py.ptr(), "__lt__", rhs.py);
    }
  }

  std::size_t
  hash()
  const
  {
    return empty()
         ? std::hash<int>()(0)
         : static_cast<std::size_t>(call_method<long>(py.ptr() , "__hash__" ));
  }

  std::string
  name()
  const
  {
    return call_method<std::string>(py.ptr(), "__str__" );
  }

  bool
  empty()
  const
  {
    return size() == 0;
  }

  std::size_t
  size()
  const
  {
    return py.is_none() ? 0 : call_method<std::size_t>(py.ptr(), "__len__" );
  }
};

std::ostream&
operator<<(std::ostream& os, const py_values& v)
{
  return os << v.name();
}

py_values
sum(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__or__", rhs.py));
    }
    else
    {
      return lhs;
    }
  }
  else
  {
    return rhs;
  }
}

py_values
difference(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__sub__", rhs.py));
    }
    else
    {
      return lhs;
    }
  }
  else
  {
    return lhs;
  }
}

py_values
intersection(const py_values& lhs, const py_values& rhs)
{
  if (not lhs.empty())
  {
    if (not rhs.empty())
    {
      return py_values(call_method<object>(lhs.py.ptr(), "__and__", rhs.py));
    }
    else
    {
      return rhs;
    }
  }
  else
  {
    return lhs;
  }
}

} // namespace python

namespace values {

  template <>
  struct values_traits<python::py_values>
  {
    static constexpr bool stateful = false;
    static constexpr bool fast_iterable = false;
    static constexpr bool has_value_type = false;
  };

} // namespace values

namespace python {

/*------------------------------------------------------------------------------------------------*/

struct pyconf
  : public sdd::conf1
{
  using Variable = int;
  using Identifier = std::string;
  using Values = py_values;
};

/*------------------------------------------------------------------------------------------------*/

double
count_combinations(SDD<pyconf> s)
{
  return sdd::count_combinations(s).template convert_to<double>();
}

/*------------------------------------------------------------------------------------------------*/

struct _manager
{
  std::shared_ptr<manager<pyconf>> ptr;

  _manager()
    : ptr(new manager<pyconf>(manager<pyconf>::init()))
  {}
};

/*------------------------------------------------------------------------------------------------*/

inline
object
pass_through(object const& o)
{
  return o;
}

struct paths
{
  path_generator<pyconf> gen;

  paths(const SDD<pyconf>& s)
  noexcept
    : gen(s.paths())
  {}

  static
  path<pyconf>
  next(paths& p)
  {
    if (p.gen)
    {
      const path<pyconf> res = p.gen.get();
      p.gen(); // compute next path
      return res;
    }
    else
    {
      PyErr_SetString(PyExc_StopIteration, "No more paths.");
      boost::python::throw_error_already_set();
      const path<pyconf>* dummy = nullptr;
      return *dummy;
    }
  }
};

/*------------------------------------------------------------------------------------------------*/

struct py_visitor
{
  using result_type = object;

  object py;

  py_visitor(object p)
    : py(p)
  {}

  object
  operator()(const hierarchical_node<pyconf>& node)
  const
  {
    return py.attr("hierarchical")(boost::cref(node));
  }

  object
  operator()(const flat_node<pyconf>& node)
  const
  {
    return py.attr("flat")(boost::cref(node));
  }

  object
  operator()(const one_terminal<pyconf>&)
  const
  {
    return py.attr("one")();
  }

  object
  operator()(const zero_terminal<pyconf>&)
  const
  {
    return py.attr("zero")();
  }
};

object
py_visit(object visitor, const SDD<pyconf>& s)
{
  return visit(py_visitor {visitor}, s);
};

/*------------------------------------------------------------------------------------------------*/

BOOST_PYTHON_MODULE(_sdd)
{
  using sdd_type = SDD<pyconf>;
  using hierarchical = hierarchical_node<pyconf>;
  using flat = flat_node<pyconf>;

  class_<_manager, boost::noncopyable>("_manager");

  class_<arc<pyconf, sdd_type>, boost::noncopyable>("HierarchicalArc", no_init)
    .def("valuation", &arc<pyconf, sdd_type>::valuation, return_internal_reference<>())
    .def("successor", &arc<pyconf, sdd_type>::successor)
    ;

  class_<hierarchical, boost::noncopyable>("HierarchicalNode", no_init)
    .def("variable", &hierarchical::variable)
    .def("__iter__", range<return_internal_reference<>>(&hierarchical::begin, &hierarchical::end))
    ;

  class_<arc<pyconf, py_values>, boost::noncopyable>("FlatArc", no_init)
    .def("valuation", &arc<pyconf, py_values>::valuation, return_internal_reference<>())
    .def("successor", &arc<pyconf, py_values>::successor)
    ;

  class_<flat, boost::noncopyable>("FlatNode", no_init)
    .def("variable", &flat::variable)
    .def("__iter__", range<return_internal_reference<>>(&flat::begin, &flat::end))
    ;

  class_<sdd_type>("SDD", init<int, object, sdd_type>())
    .def(init<int, sdd_type, sdd_type>())
    .def(self_ns::str(self))
    .def(self + self)
    .def(self - self)
    .def(self & self)
    .def(self == self)
    .def(self < self)
    .def("__hash__", &sdd_type::hash)
    ;

  def("zero", &zero<pyconf>);
  def("one", &one<pyconf>);

  def("count_combinations", &count_combinations);

  def("visit", &py_visit);

  class_<path<pyconf>>("Path", no_init)
    .def(vector_indexing_suite<path<pyconf>>())
    ;

  class_<paths, boost::noncopyable>("Paths", init<SDD<pyconf>>())
    .def("__iter__", &pass_through)
    .def("next", &paths::next)
    ;

  class_<py_values>("PyValues", no_init)
    .def("content", &py_values::content)
    ;
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::python

namespace std {

/*------------------------------------------------------------------------------------------------*/

template <>
struct hash<sdd::python::py_values>
{
  std::size_t
  operator()(const sdd::python::py_values& val)
  const
  {
    return val.hash();
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace std
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUNCTOR_GRADIENT_HPP
#define STAN_MATH_REV_FUNCTOR_GRADIENT_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stdexcept>

namespace stan {
namespace math {

/**
 * Calculate the value and the gradient of the specified function
 * at the specified argument.
 *
 *
The functor must implement
 *
 *
 * var
 * operator()(const
 * Eigen::Matrix<var, Eigen::Dynamic, 1>&)
 *
 *
 * using only operations that are defined for
 * var.  This latter constraint usually
 * requires the functions to be defined in terms of the libraries
 * defined in Stan or in terms of functions with appropriately
 * general namespace imports that eventually depend on functions
 * defined in Stan.
 *
 *
Time and memory usage is on the order of the size of the
 * fully unfolded expression for the function applied to the
 * argument, independently of dimension.
 *
 * @tparam F Type of function
 * @param[in] f Function
 * @param[in] x Argument to function
 * @param[out] fx Function applied to argument
 * @param[out] grad_fx Gradient of function at argument
 */
template <typename F>
void gradient(const F& f, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
              double& fx, Eigen::Matrix<double, Eigen::Dynamic, 1>& grad_fx) {
  start_nested();
  try {
    Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x);
    var fx_var = f(x_var);
    fx = fx_var.val();
    grad_fx.resize(x.size());
    grad(fx_var.vi_);
    grad_fx = x_var.adj();
  } catch (const std::exception& /*e*/) {
    recover_memory_nested();
    throw;
  }
  recover_memory_nested();
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>avoid putting un-needed vars on chain stack and place them on nochain stack to reduce chain calls<commit_after>#ifndef STAN_MATH_REV_FUNCTOR_GRADIENT_HPP
#define STAN_MATH_REV_FUNCTOR_GRADIENT_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stdexcept>

namespace stan {
namespace math {

/**
 * Calculate the value and the gradient of the specified function
 * at the specified argument.
 *
 *
The functor must implement
 *
 *
 * var
 * operator()(const
 * Eigen::Matrix<var, Eigen::Dynamic, 1>&)
 *
 *
 * using only operations that are defined for
 * var.  This latter constraint usually
 * requires the functions to be defined in terms of the libraries
 * defined in Stan or in terms of functions with appropriately
 * general namespace imports that eventually depend on functions
 * defined in Stan.
 *
 *
Time and memory usage is on the order of the size of the
 * fully unfolded expression for the function applied to the
 * argument, independently of dimension.
 *
 * @tparam F Type of function
 * @param[in] f Function
 * @param[in] x Argument to function
 * @param[out] fx Function applied to argument
 * @param[out] grad_fx Gradient of function at argument
 */
template <typename F>
void gradient(const F& f, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
              double& fx, Eigen::Matrix<double, Eigen::Dynamic, 1>& grad_fx) {
  start_nested();
  try {
    Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x.size());
    for (int i = 0; i < x.size(); ++i)
      x_var(i) = var(new vari(x(i), false));
    var fx_var = f(x_var);
    fx = fx_var.val();
    grad_fx.resize(x.size());
    grad(fx_var.vi_);
    grad_fx = x_var.adj();
  } catch (const std::exception& /*e*/) {
    recover_memory_nested();
    throw;
  }
  recover_memory_nested();
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/xwalk_content_browser_client.h"

#include <vector>

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/platform_file.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/xwalk_browser_main_parts.h"
#include "xwalk/runtime/browser/geolocation/xwalk_access_token_store.h"
#include "xwalk/runtime/browser/media/media_capture_devices_dispatcher.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/runtime_quota_permission_context.h"
#include "content/public/browser/browser_main_parts.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/main_function_params.h"
#include "net/url_request/url_request_context_getter.h"

#if defined(OS_ANDROID)
#include "base/android/path_utils.h"
#include "base/base_paths_android.h"
#include "xwalk/runtime/browser/runtime_resource_dispatcher_host_delegate.h"
#include "xwalk/runtime/common/android/xwalk_globals_android.h"
#endif

namespace xwalk {

namespace {

// The application-wide singleton of ContentBrowserClient impl.
XWalkContentBrowserClient* g_browser_client = NULL;

#if defined(OS_ANDROID)
// Android creates and holds its browser context by browser client.
RuntimeContext* g_runtime_context;
#endif

}  // namespace

// static
XWalkContentBrowserClient* XWalkContentBrowserClient::Get() {
  return g_browser_client;
}

#if defined(OS_ANDROID)
// static
RuntimeContext* XWalkContentBrowserClient::GetRuntimeContext() {
  return g_runtime_context;
}
#endif

XWalkContentBrowserClient::XWalkContentBrowserClient()
    : main_parts_(NULL) {
  DCHECK(!g_browser_client);
  g_browser_client = this;
#if defined(OS_ANDROID)
  g_runtime_context = new RuntimeContext();
#endif
}

XWalkContentBrowserClient::~XWalkContentBrowserClient() {
  DCHECK(g_browser_client);
  g_browser_client = NULL;
#if defined(OS_ANDROID)
  g_runtime_context = NULL;
#endif
}

content::BrowserMainParts* XWalkContentBrowserClient::CreateBrowserMainParts(
    const content::MainFunctionParams& parameters) {
  main_parts_ = new XWalkBrowserMainParts(parameters);

#if defined(OS_ANDROID)
  main_parts_->SetRuntimeContext(g_runtime_context);
#endif
  return main_parts_;
}

net::URLRequestContextGetter* XWalkContentBrowserClient::CreateRequestContext(
    content::BrowserContext* browser_context,
    content::ProtocolHandlerMap* protocol_handlers) {
  url_request_context_getter_ = static_cast<RuntimeContext*>(browser_context)->
      CreateRequestContext(protocol_handlers);
  return url_request_context_getter_;
}

net::URLRequestContextGetter*
XWalkContentBrowserClient::CreateRequestContextForStoragePartition(
    content::BrowserContext* browser_context,
    const base::FilePath& partition_path,
    bool in_memory,
    content::ProtocolHandlerMap* protocol_handlers) {
  return static_cast<RuntimeContext*>(browser_context)->
      CreateRequestContextForStoragePartition(
          partition_path, in_memory, protocol_handlers);
}

void XWalkContentBrowserClient::AppendExtraCommandLineSwitches(
    CommandLine* command_line, int child_process_id) {
  CommandLine* browser_process_cmd_line = CommandLine::ForCurrentProcess();
  if (browser_process_cmd_line->HasSwitch(
          switches::kXWalkDisableLoadingExtensionsOnDemand)) {
    command_line->AppendSwitch(
        switches::kXWalkDisableLoadingExtensionsOnDemand);
  }
}

content::QuotaPermissionContext*
XWalkContentBrowserClient::CreateQuotaPermissionContext() {
  return new RuntimeQuotaPermissionContext();
}

content::AccessTokenStore* XWalkContentBrowserClient::CreateAccessTokenStore() {
  return new XWalkAccessTokenStore(url_request_context_getter_);
}

content::WebContentsViewDelegate*
XWalkContentBrowserClient::GetWebContentsViewDelegate(
    content::WebContents* web_contents) {
  return NULL;
}

void XWalkContentBrowserClient::RenderProcessHostCreated(
    content::RenderProcessHost* host) {
  main_parts_->extension_service()->OnRenderProcessHostCreated(host);
}

content::MediaObserver* XWalkContentBrowserClient::GetMediaObserver() {
  return XWalkMediaCaptureDevicesDispatcher::GetInstance();
}

#if defined(OS_ANDROID)
void XWalkContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
    const CommandLine& command_line,
    int child_process_id,
    std::vector<content::FileDescriptorInfo>* mappings) {
  int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ;
  base::FilePath pak_file;
  bool r = PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_file);
  CHECK(r);
  pak_file = pak_file.Append(FILE_PATH_LITERAL("paks"));
  pak_file = pak_file.Append(FILE_PATH_LITERAL(kXWalkPakFilePath));

  base::PlatformFile f =
      base::CreatePlatformFile(pak_file, flags, NULL, NULL);
  if (f == base::kInvalidPlatformFileValue) {
    NOTREACHED() << "Failed to open file when creating renderer process: "
                 << "xwalk.pak";
  }
  mappings->push_back(
      content::FileDescriptorInfo(kXWalkPakDescriptor,
                                  base::FileDescriptor(f, true)));
}

void XWalkContentBrowserClient::ResourceDispatcherHostCreated() {
  RuntimeResourceDispatcherHostDelegate::ResourceDispatcherHostCreated();
}
#endif

}  // namespace xwalk
<commit_msg>[Extensions] Pass to RP whether we use or not use extension process<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/xwalk_content_browser_client.h"

#include <vector>

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/platform_file.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/xwalk_browser_main_parts.h"
#include "xwalk/runtime/browser/geolocation/xwalk_access_token_store.h"
#include "xwalk/runtime/browser/media/media_capture_devices_dispatcher.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/runtime_quota_permission_context.h"
#include "content/public/browser/browser_main_parts.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/main_function_params.h"
#include "net/url_request/url_request_context_getter.h"

#if defined(OS_ANDROID)
#include "base/android/path_utils.h"
#include "base/base_paths_android.h"
#include "xwalk/runtime/browser/runtime_resource_dispatcher_host_delegate.h"
#include "xwalk/runtime/common/android/xwalk_globals_android.h"
#endif

namespace xwalk {

namespace {

// The application-wide singleton of ContentBrowserClient impl.
XWalkContentBrowserClient* g_browser_client = NULL;

#if defined(OS_ANDROID)
// Android creates and holds its browser context by browser client.
RuntimeContext* g_runtime_context;
#endif

}  // namespace

// static
XWalkContentBrowserClient* XWalkContentBrowserClient::Get() {
  return g_browser_client;
}

#if defined(OS_ANDROID)
// static
RuntimeContext* XWalkContentBrowserClient::GetRuntimeContext() {
  return g_runtime_context;
}
#endif

XWalkContentBrowserClient::XWalkContentBrowserClient()
    : main_parts_(NULL) {
  DCHECK(!g_browser_client);
  g_browser_client = this;
#if defined(OS_ANDROID)
  g_runtime_context = new RuntimeContext();
#endif
}

XWalkContentBrowserClient::~XWalkContentBrowserClient() {
  DCHECK(g_browser_client);
  g_browser_client = NULL;
#if defined(OS_ANDROID)
  g_runtime_context = NULL;
#endif
}

content::BrowserMainParts* XWalkContentBrowserClient::CreateBrowserMainParts(
    const content::MainFunctionParams& parameters) {
  main_parts_ = new XWalkBrowserMainParts(parameters);

#if defined(OS_ANDROID)
  main_parts_->SetRuntimeContext(g_runtime_context);
#endif
  return main_parts_;
}

net::URLRequestContextGetter* XWalkContentBrowserClient::CreateRequestContext(
    content::BrowserContext* browser_context,
    content::ProtocolHandlerMap* protocol_handlers) {
  url_request_context_getter_ = static_cast<RuntimeContext*>(browser_context)->
      CreateRequestContext(protocol_handlers);
  return url_request_context_getter_;
}

net::URLRequestContextGetter*
XWalkContentBrowserClient::CreateRequestContextForStoragePartition(
    content::BrowserContext* browser_context,
    const base::FilePath& partition_path,
    bool in_memory,
    content::ProtocolHandlerMap* protocol_handlers) {
  return static_cast<RuntimeContext*>(browser_context)->
      CreateRequestContextForStoragePartition(
          partition_path, in_memory, protocol_handlers);
}

// This allow us to append extra command line switches to the child
// process we launch.
void XWalkContentBrowserClient::AppendExtraCommandLineSwitches(
    CommandLine* command_line, int child_process_id) {
  CommandLine* browser_process_cmd_line = CommandLine::ForCurrentProcess();
  const int extra_switches_count = 2;
  const char* extra_switches[extra_switches_count] = {
    switches::kXWalkDisableLoadingExtensionsOnDemand,
    switches::kXWalkDisableExtensionProcess
  };

  for (int i = 0; i < extra_switches_count; i++) {
    if (browser_process_cmd_line->HasSwitch(extra_switches[i]))
      command_line->AppendSwitch(extra_switches[i]);
  }
}

content::QuotaPermissionContext*
XWalkContentBrowserClient::CreateQuotaPermissionContext() {
  return new RuntimeQuotaPermissionContext();
}

content::AccessTokenStore* XWalkContentBrowserClient::CreateAccessTokenStore() {
  return new XWalkAccessTokenStore(url_request_context_getter_);
}

content::WebContentsViewDelegate*
XWalkContentBrowserClient::GetWebContentsViewDelegate(
    content::WebContents* web_contents) {
  return NULL;
}

void XWalkContentBrowserClient::RenderProcessHostCreated(
    content::RenderProcessHost* host) {
  main_parts_->extension_service()->OnRenderProcessHostCreated(host);
}

content::MediaObserver* XWalkContentBrowserClient::GetMediaObserver() {
  return XWalkMediaCaptureDevicesDispatcher::GetInstance();
}

#if defined(OS_ANDROID)
void XWalkContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
    const CommandLine& command_line,
    int child_process_id,
    std::vector<content::FileDescriptorInfo>* mappings) {
  int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ;
  base::FilePath pak_file;
  bool r = PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_file);
  CHECK(r);
  pak_file = pak_file.Append(FILE_PATH_LITERAL("paks"));
  pak_file = pak_file.Append(FILE_PATH_LITERAL(kXWalkPakFilePath));

  base::PlatformFile f =
      base::CreatePlatformFile(pak_file, flags, NULL, NULL);
  if (f == base::kInvalidPlatformFileValue) {
    NOTREACHED() << "Failed to open file when creating renderer process: "
                 << "xwalk.pak";
  }
  mappings->push_back(
      content::FileDescriptorInfo(kXWalkPakDescriptor,
                                  base::FileDescriptor(f, true)));
}

void XWalkContentBrowserClient::ResourceDispatcherHostCreated() {
  RuntimeResourceDispatcherHostDelegate::ResourceDispatcherHostCreated();
}
#endif

}  // namespace xwalk
<|endoftext|>