<commit_before>#include <iostream>
#include <algorithm>
#include <zita-convolver.h>

#include <string.h>
#include <assert.h>
#include "alloaudio/al_Convolver.hpp"

using namespace al;

Convolver::Convolver() :
    m_Convproc(NULL)
{
}

int Convolver::configure(al::AudioIO &io, vector<float *> IRs, vector<int> IRLengths,
                         int inputChannel, bool inputsAreBuses,
                         vector<int> disabledChannels, unsigned int maxsize,
                         unsigned int minpartition, unsigned int maxpartition, unsigned int options)
{
    int bufferSize = io.framesPerBuffer(), nActiveOutputs = io.channels(true) - disabledChannels.size(), nActiveInputs,configResult;
    assert((IRs.size() == IRLengths.size()) && IRs.size() == nActiveOutputs);
    assert(minpartition>=64);
    assert(maxpartition<=8192);
    //TODO check to make sure number of inputs matches buses/io inputs
    m_inputChannel = inputChannel;
    m_inputsAreBuses = inputsAreBuses;
    m_disabledChannels = disabledChannels;
    for (int i = 0; i < io.channels(true); i++) {
        if (std::find(disabledChannels.begin(), disabledChannels.end(), i)
                == disabledChannels.end()) {
            m_activeChannels.push_back(i);
        }
    }

    if(m_Convproc != NULL) {
        delete m_Convproc;
    }
    m_Convproc = new Convproc;
    m_Convproc->set_options(options);
    if(m_inputChannel < 0){//many to many
        nActiveInputs = io.channels(false);
        assert(nActiveInputs == nActiveOutputs);
        for(int i = 0; i < nActiveOutputs; i++){
            m_Convproc->impdata_create(i, i, minpartition, IRs[i], 0, IRLengths[i]);
        }
    }
    else{//one to many
        nActiveInputs = 1;
        for(int i = 0; i < nActiveOutputs; i++){
            m_Convproc->impdata_create(0, i, minpartition, IRs[i], 0, IRLengths[i]);
        }
    }
    configResult = m_Convproc->configure(nActiveInputs, nActiveOutputs, maxsize, bufferSize, minpartition, maxpartition);
    if(configResult != 0){
        std::cout << "Config failed" << std::endl;
    }
    m_Convproc->start_process(0, 0);
    return 0;
}

int Convolver::processBlock(al::AudioIO &io)
{
    int blockSize = io.framesPerBuffer();
    //fill the input buffers
    if(m_inputChannel < 0){
        // many to many
        int i = 0;
        for(vector<int>::iterator it = m_activeChannels.begin();
            it != m_activeChannels.end(); ++it, ++i) {
            const float *inbuf;
            float *dest = m_Convproc->inpdata(i);
            if (m_inputsAreBuses){
                inbuf = io.busBuffer(*it);
            }
            else{
                inbuf = io.inBuffer(*it);
            }
            memcpy(dest, inbuf, sizeof(float) * blockSize);
        }
    }
    else{
        //one to many
        const float *inbuf;
        if (m_inputsAreBuses){
            inbuf = io.busBuffer(m_inputChannel);
        }
        else{
            inbuf = io.inBuffer(m_inputChannel);
        }
        //TODO: figure out if passing a single input has the expected result
        /*for(vector<int>::iterator it = m_activeChannels.begin();
            it != m_activeChannels.end(); ++it) {
            memcpy(m_Convproc->inpdata(0), inbuf, sizeof(float) * blockSize);
        }*/
        memcpy(m_Convproc->inpdata(0), inbuf, sizeof(float) * blockSize);
    }

    //process
    int ret = m_Convproc->process(true);
    //fill the output buffers
    int i = 0;
    for(vector<int>::iterator it = m_activeChannels.begin();
        it != m_activeChannels.end(); ++it, ++i) {
        float *outbuf = io.outBuffer(*it);
        memcpy(outbuf, m_Convproc->outdata(i), sizeof(float) * blockSize);
    }

    //clear output for disabled channels
    m_Convproc->process(true);
    for(vector<int>::iterator it = m_disabledChannels.begin();
        it != m_disabledChannels.end(); ++it) {
        memset(io.outBuffer(*it), 0, sizeof(float) * blockSize);
    }

	return ret;
}
<commit_msg>looks like io object isn't allowing us to set the buffer<commit_after>#include <iostream>
#include <algorithm>
#include <zita-convolver.h>

#include <string.h>
#include <assert.h>
#include "alloaudio/al_Convolver.hpp"

using namespace al;

Convolver::Convolver() :
    m_Convproc(NULL)
{
}

int Convolver::configure(al::AudioIO &io, vector<float *> IRs, vector<int> IRLengths,
                         int inputChannel, bool inputsAreBuses,
                         vector<int> disabledChannels, unsigned int maxsize,
                         unsigned int minpartition, unsigned int maxpartition, unsigned int options)
{
    int bufferSize = io.framesPerBuffer(), nActiveOutputs = io.channels(true) - disabledChannels.size(), nActiveInputs,configResult;
    assert((IRs.size() == IRLengths.size()) && IRs.size() == nActiveOutputs);
    assert(minpartition>=64);
    assert(maxpartition<=8192);
    //TODO check to make sure number of inputs matches buses/io inputs
    m_inputChannel = inputChannel;
    m_inputsAreBuses = inputsAreBuses;
    m_disabledChannels = disabledChannels;
    for (int i = 0; i < io.channels(true); i++) {
        if (std::find(disabledChannels.begin(), disabledChannels.end(), i)
                == disabledChannels.end()) {
            m_activeChannels.push_back(i);
        }
    }

    if(m_Convproc != NULL) {
        delete m_Convproc;
    }
    m_Convproc = new Convproc;
    m_Convproc->set_options(options);
    if(m_inputChannel < 0){//many to many
        nActiveInputs = io.channels(false);
        assert(nActiveInputs == nActiveOutputs);
        for(int i = 0; i < nActiveOutputs; i++){
            cout << "alConfigure:" << io.busBuffer(0)[0] << endl;
            cout << "alConfigure:" << io.busBuffer(1)[0] << endl;
            m_Convproc->impdata_create(i, i, minpartition, IRs[i], 0, IRLengths[i]);
        }
    }
    else{//one to many
        nActiveInputs = 1;
        for(int i = 0; i < nActiveOutputs; i++){
            m_Convproc->impdata_create(0, i, minpartition, IRs[i], 0, IRLengths[i]);
        }
    }
    configResult = m_Convproc->configure(nActiveInputs, nActiveOutputs, maxsize, bufferSize, minpartition, maxpartition);
    if(configResult != 0){
        std::cout << "Config failed" << std::endl;
    }
    m_Convproc->start_process(0, 0);
    return 0;
}

int Convolver::processBlock(al::AudioIO &io)
{
    int blockSize = io.framesPerBuffer();
    //fill the input buffers
    if(m_inputChannel < 0){
        // many to many
        int i = 0;
        for(vector<int>::iterator it = m_activeChannels.begin();
            it != m_activeChannels.end(); ++it, ++i) {
            const float *inbuf;
            float *dest = m_Convproc->inpdata(i);
            if (m_inputsAreBuses){
                inbuf = io.busBuffer(*it);
            }
            else{
                inbuf = io.inBuffer(*it);
            }
            cout << "inbuf " << *it << ": " << inbuf[0] << endl;
            memcpy(dest, inbuf, sizeof(float) * blockSize);
        }
    }
    else{
        //one to many
        const float *inbuf;
        if (m_inputsAreBuses){
            inbuf = io.busBuffer(m_inputChannel);
        }
        else{
            inbuf = io.inBuffer(m_inputChannel);
        }
        //TODO: figure out if passing a single input has the expected result
        /*for(vector<int>::iterator it = m_activeChannels.begin();
            it != m_activeChannels.end(); ++it) {
            memcpy(m_Convproc->inpdata(0), inbuf, sizeof(float) * blockSize);
        }*/
        memcpy(m_Convproc->inpdata(0), inbuf, sizeof(float) * blockSize);
    }

    //process
    int ret = m_Convproc->process(true);
    //fill the output buffers
    int i = 0;
    for(vector<int>::iterator it = m_activeChannels.begin();
        it != m_activeChannels.end(); ++it, ++i) {
        float *outbuf = io.outBuffer(*it);
        memcpy(outbuf, m_Convproc->outdata(i), sizeof(float) * blockSize);
    }

    //clear output for disabled channels
    m_Convproc->process(true);
    for(vector<int>::iterator it = m_disabledChannels.begin();
        it != m_disabledChannels.end(); ++it) {
        memset(io.outBuffer(*it), 0, sizeof(float) * blockSize);
    }

	return ret;
}
<|endoftext|>


<commit_before>/*
 * Implementation file for the particle force generators.
 *
 * Part of the Cyclone physics system.
 *
 * Copyright (c) Icosagon 2003. All Rights Reserved.
 *
 * This software is distributed under licence. Use of this software
 * implies agreement with all terms and conditions of the accompanying
 * software licence.
 */

#include <cyclone/pfgen.h>

using namespace cyclone;

void ParticleForceRegistry::updateForces(real duration)
{
    Registry::iterator i = registrations.begin();
    for (; i != registrations.end(); i++)
    {
        i->fg->updateForce(i->particle, duration);
    }
}

void ParticleForceRegistry::add(Particle* particle, ParticleForceGenerator *fg)
{
    ParticleForceRegistry::ParticleForceRegistration registration;
    registration.particle = particle;
    registration.fg = fg;
    registrations.push_back(registration);
}

ParticleGravity::ParticleGravity(const Vector3& gravity)
: gravity(gravity)
{
}

void ParticleGravity::updateForce(Particle* particle, real duration)
{
    // Check that we do not have infinite mass
    if (!particle->hasFiniteMass()) return;

    // Apply the mass-scaled force to the particle
    particle->addForce(gravity * particle->getMass());
}

ParticleDrag::ParticleDrag(real k1, real k2)
: k1(k1), k2(k2)
{
}

void ParticleDrag::updateForce(Particle* particle, real duration)
{
    Vector3 force;
    particle->getVelocity(&force);

    // Calculate the total drag coefficient
    real dragCoeff = force.magnitude();
    dragCoeff = k1 * dragCoeff + k2 * dragCoeff * dragCoeff;

    // Calculate the final force and apply it
    force.normalise();
    force *= -dragCoeff;
    particle->addForce(force);
}

ParticleSpring::ParticleSpring(Particle *other, real sc, real rl)
: other(other), springConstant(sc), restLength(rl)
{
}

void ParticleSpring::updateForce(Particle* particle, real duration)
{
    // Calculate the vector of the spring
    Vector3 force;
    particle->getPosition(&force);
    force -= other->getPosition();

    // Calculate the magnitude of the force
    real magnitude = force.magnitude();
    magnitude = real_abs(magnitude - restLength);
    magnitude *= springConstant;

    // Calculate the final force and apply it
    force.normalise();
    force *= -magnitude;
    particle->addForce(force);
}

ParticleBuoyancy::ParticleBuoyancy(real maxDepth,
                                 real volume,
                                 real waterHeight,
                                 real liquidDensity)
:
maxDepth(maxDepth), volume(volume),
waterHeight(waterHeight), liquidDensity(liquidDensity)
{
}

void ParticleBuoyancy::updateForce(Particle* particle, real duration)
{
    // Calculate the submersion depth
    real depth = particle->getPosition().y;

    // Check if we're out of the water
    if (depth >= waterHeight + maxDepth) return;
    Vector3 force(0,0,0);

    // Check if we're at maximum depth
    if (depth <= waterHeight - maxDepth)
    {
        force.y = liquidDensity * volume;
        particle->addForce(force);
        return;
    }

    // Otherwise we are partly submerged
    force.y = liquidDensity * volume *
        (depth - maxDepth - waterHeight) / 2 * maxDepth;
    particle->addForce(force);
}

ParticleBungee::ParticleBungee(Particle *other, real sc, real rl)
: other(other), springConstant(sc), restLength(rl)
{
}

void ParticleBungee::updateForce(Particle* particle, real duration)
{
    // Calculate the vector of the spring
    Vector3 force;
    particle->getPosition(&force);
    force -= other->getPosition();

    // Check if the bungee is compressed
    real magnitude = force.magnitude();
    if (magnitude <= restLength) return;

    // Calculate the magnitude of the force
    magnitude = springConstant * (restLength - magnitude);

    // Calculate the final force and apply it
    force.normalise();
    force *= -magnitude;
    particle->addForce(force);
}

ParticleFakeSpring::ParticleFakeSpring(Vector3 *anchor, real sc, real d)
: anchor(anchor), springConstant(sc), damping(d)
{
}

void ParticleFakeSpring::updateForce(Particle* particle, real duration)
{
    // Check that we do not have infinite mass
    if (!particle->hasFiniteMass()) return;

    // Calculate the relative position of the particle to the anchor
    Vector3 position;
    particle->getPosition(&position);
    position -= *anchor;

    // Calculate the constants and check they are in bounds.
    real gamma = 0.5f * real_sqrt(4 * springConstant - damping*damping);
    if (gamma == 0.0f) return;
    Vector3 c = position * (damping / (2.0f * gamma)) +
        particle->getVelocity() * (1.0f / gamma);

    // Calculate the target position
    Vector3 target = position * real_cos(gamma * duration) +
        c * real_sin(gamma * duration);
    target *= real_exp(-0.5f * duration * damping);

    // Calculate the resulting acceleration and therefore the force
    Vector3 accel = (target - position) * (1.0f / duration*duration) -
        particle->getVelocity() * duration;
    particle->addForce(accel * particle->getMass());
}

ParticleAnchoredSpring::ParticleAnchoredSpring()
{
}

ParticleAnchoredSpring::ParticleAnchoredSpring(Vector3 *anchor,
                                               real sc, real rl)
: anchor(anchor), springConstant(sc), restLength(rl)
{
}

void ParticleAnchoredSpring::init(Vector3 *anchor, real springConstant,
                                  real restLength)
{
    ParticleAnchoredSpring::anchor = anchor;
    ParticleAnchoredSpring::springConstant = springConstant;
    ParticleAnchoredSpring::restLength = restLength;
}

void ParticleAnchoredBungee::updateForce(Particle* particle, real duration)
{
    // Calculate the vector of the spring
    Vector3 force;
    particle->getPosition(&force);
    force -= *anchor;

    // Calculate the magnitude of the force
    real magnitude = force.magnitude();
    if (magnitude < restLength) return;

    magnitude = magnitude - restLength;
    magnitude *= springConstant;

    // Calculate the final force and apply it
    force.normalise();
    force *= -magnitude;
    particle->addForce(force);
}

void ParticleAnchoredSpring::updateForce(Particle* particle, real duration)
{
    // Calculate the vector of the spring
    Vector3 force;
    particle->getPosition(&force);
    force -= *anchor;

    // Calculate the magnitude of the force
    real magnitude = force.magnitude();
    magnitude = (restLength - magnitude) * springConstant;

    // Calculate the final force and apply it
    force.normalise();
    force *= magnitude;
    particle->addForce(force);
}
<commit_msg>Corrected calculations src/pfgen.cpp<commit_after>/*
 * Implementation file for the particle force generators.
 *
 * Part of the Cyclone physics system.
 *
 * Copyright (c) Icosagon 2003. All Rights Reserved.
 *
 * This software is distributed under licence. Use of this software
 * implies agreement with all terms and conditions of the accompanying
 * software licence.
 */

#include <cyclone/pfgen.h>

using namespace cyclone;

void ParticleForceRegistry::updateForces(real duration)
{
    Registry::iterator i = registrations.begin();
    for (; i != registrations.end(); i++)
    {
        i->fg->updateForce(i->particle, duration);
    }
}

void ParticleForceRegistry::add(Particle* particle, ParticleForceGenerator *fg)
{
    ParticleForceRegistry::ParticleForceRegistration registration;
    registration.particle = particle;
    registration.fg = fg;
    registrations.push_back(registration);
}

ParticleGravity::ParticleGravity(const Vector3& gravity)
: gravity(gravity)
{
}

void ParticleGravity::updateForce(Particle* particle, real duration)
{
    // Check that we do not have infinite mass
    if (!particle->hasFiniteMass()) return;

    // Apply the mass-scaled force to the particle
    particle->addForce(gravity * particle->getMass());
}

ParticleDrag::ParticleDrag(real k1, real k2)
: k1(k1), k2(k2)
{
}

void ParticleDrag::updateForce(Particle* particle, real duration)
{
    Vector3 force;
    particle->getVelocity(&force);

    // Calculate the total drag coefficient
    real dragCoeff = force.magnitude();
    dragCoeff = k1 * dragCoeff + k2 * dragCoeff * dragCoeff;

    // Calculate the final force and apply it
    force.normalise();
    force *= -dragCoeff;
    particle->addForce(force);
}

ParticleSpring::ParticleSpring(Particle *other, real sc, real rl)
: other(other), springConstant(sc), restLength(rl)
{
}

void ParticleSpring::updateForce(Particle* particle, real duration)
{
    // Calculate the vector of the spring
    Vector3 force;
    particle->getPosition(&force);
    force -= other->getPosition();

    // Calculate the magnitude of the force
    real magnitude = force.magnitude();
    magnitude = real_abs(magnitude - restLength);
    magnitude *= springConstant;

    // Calculate the final force and apply it
    force.normalise();
    force *= -magnitude;
    particle->addForce(force);
}

ParticleBuoyancy::ParticleBuoyancy(real maxDepth,
                                 real volume,
                                 real waterHeight,
                                 real liquidDensity)
:
maxDepth(maxDepth), volume(volume),
waterHeight(waterHeight), liquidDensity(liquidDensity)
{
}

void ParticleBuoyancy::updateForce(Particle* particle, real duration)
{
    // Calculate the submersion depth
    real depth = particle->getPosition().y;

    // Check if we're out of the water
    if (depth >= waterHeight + maxDepth) return;
    Vector3 force(0,0,0);

    // Check if we're at maximum depth
    if (depth <= waterHeight - maxDepth)
    {
        force.y = liquidDensity * volume;
        particle->addForce(force);
        return;
    }

    // Otherwise we are partly submerged
    force.y = liquidDensity * volume *
        (depth - maxDepth - waterHeight) / 2 * maxDepth;
    particle->addForce(force);
}

ParticleBungee::ParticleBungee(Particle *other, real sc, real rl)
: other(other), springConstant(sc), restLength(rl)
{
}

void ParticleBungee::updateForce(Particle* particle, real duration)
{
    // Calculate the vector of the spring
    Vector3 force;
    particle->getPosition(&force);
    force -= other->getPosition();

    // Check if the bungee is compressed
    real magnitude = force.magnitude();
    if (magnitude <= restLength) return;

    // Calculate the magnitude of the force
    magnitude = springConstant * (restLength - magnitude);

    // Calculate the final force and apply it
    force.normalise();
    force *= -magnitude;
    particle->addForce(force);
}

ParticleFakeSpring::ParticleFakeSpring(Vector3 *anchor, real sc, real d)
: anchor(anchor), springConstant(sc), damping(d)
{
}

void ParticleFakeSpring::updateForce(Particle* particle, real duration)
{
    // Check that we do not have infinite mass
    if (!particle->hasFiniteMass()) return;

    // Calculate the relative position of the particle to the anchor
    Vector3 position;
    particle->getPosition(&position);
    position -= *anchor;

    // Calculate the constants and check they are in bounds.
    real gamma = 0.5f * real_sqrt(4 * springConstant - damping*damping);
    if (gamma == 0.0f) return;
    Vector3 c = position * (damping / (2.0f * gamma)) +
        particle->getVelocity() * (1.0f / gamma);

    // Calculate the target position
    Vector3 target = position * real_cos(gamma * duration) +
        c * real_sin(gamma * duration);
    target *= real_exp(-0.5f * duration * damping);

    // Calculate the resulting acceleration and therefore the force
    Vector3 accel = (target - position) * ((real)1.0 / (duration*duration)) -
        particle->getVelocity() * ((real)1.0/duration);
    particle->addForce(accel * particle->getMass());
}

ParticleAnchoredSpring::ParticleAnchoredSpring()
{
}

ParticleAnchoredSpring::ParticleAnchoredSpring(Vector3 *anchor,
                                               real sc, real rl)
: anchor(anchor), springConstant(sc), restLength(rl)
{
}

void ParticleAnchoredSpring::init(Vector3 *anchor, real springConstant,
                                  real restLength)
{
    ParticleAnchoredSpring::anchor = anchor;
    ParticleAnchoredSpring::springConstant = springConstant;
    ParticleAnchoredSpring::restLength = restLength;
}

void ParticleAnchoredBungee::updateForce(Particle* particle, real duration)
{
    // Calculate the vector of the spring
    Vector3 force;
    particle->getPosition(&force);
    force -= *anchor;

    // Calculate the magnitude of the force
    real magnitude = force.magnitude();
    if (magnitude < restLength) return;

    magnitude = magnitude - restLength;
    magnitude *= springConstant;

    // Calculate the final force and apply it
    force.normalise();
    force *= -magnitude;
    particle->addForce(force);
}

void ParticleAnchoredSpring::updateForce(Particle* particle, real duration)
{
    // Calculate the vector of the spring
    Vector3 force;
    particle->getPosition(&force);
    force -= *anchor;

    // Calculate the magnitude of the force
    real magnitude = force.magnitude();
    magnitude = (restLength - magnitude) * springConstant;

    // Calculate the final force and apply it
    force.normalise();
    force *= magnitude;
    particle->addForce(force);
}
<|endoftext|>


<commit_before>#ifndef SORTED__HPP__
#define SORTED__HPP__

#include <algorithm>
#include <vector>

namespace iter {

    template <typename Container>
    class Sorted;

    template <typename Container>
    Sorted<Container> sorted(Container &);

    template <typename Container>
    class Sorted {
        private:
            friend Sorted sorted<Container>(Container &);

            using contained_iter_type =
                decltype(std::declval<Container>().begin());

            std::vector<contained_iter_type> sorted_iters;

            Sorted() = delete;
            Sorted & operator=(const Sorted &) = delete;

            Sorted(Container & container) {
                for (auto iter = container.begin();
                        iter != container.end();
                        ++iter) {
                    sorted_iters.push_back(iter);
                }
                std::sort(sorted_iters.begin(), sorted_iters.end(),
                        [] (const contained_iter_type & it1,
                            const contained_iter_type & it2)
                        { return *it1 < *it2; });
            }

        public:
            Sorted(const Sorted &) = default;
            auto begin() const -> decltype(sorted_iters.begin()) {
                return sorted_iters.begin();
            }
            auto end() const -> decltype(sorted_iters.end()) {
                return sorted_iters.end();
            }

    };

    template <typename Container>
    Sorted<Container> sorted(Container & container) {
        return Sorted<Container>(container);
    }

}

#endif //#ifndef SORTED__HPP__
<commit_msg>Reworks sorted to yield from *iterator<commit_after>#ifndef SORTED__HPP__
#define SORTED__HPP__

#include <algorithm>
#include <vector>

namespace iter {
    template <typename Container>
    class Sorted;

    template <typename Container>
    Sorted<Container> sorted(Container &);

    template <typename Container>
    class Sorted {
        private:
            friend Sorted sorted<Container>(Container &);

            using contained_iter_type =
                decltype(std::declval<Container>().begin());

            std::vector<contained_iter_type> sorted_iters;

            using sorted_iter_type = decltype(sorted_iters.begin());
            using contained_iter_ret =
                decltype(sorted_iters.begin().operator*().operator*());

            Sorted() = delete;
            Sorted & operator=(const Sorted &) = delete;

            Sorted(Container & container) {
                // Fill the sorted_iters vector with an iterator to each
                // element in the container
                for (auto iter = container.begin();
                        iter != container.end();
                        ++iter) {
                    sorted_iters.push_back(iter);
                }

                // sort by comparing the elements that the iterators point to
                std::sort(sorted_iters.begin(), sorted_iters.end(),
                        [] (const contained_iter_type & it1,
                            const contained_iter_type & it2)
                        { return *it1 < *it2; });
            }

        public:

            // Iterates over a series of Iterators, automatically dereferencing
            // them when accessed with operator *
            class IteratorIterator : public sorted_iter_type {
                public:
                    IteratorIterator(sorted_iter_type iter) :
                        sorted_iter_type(iter)
                    { }
                    IteratorIterator(const IteratorIterator &) = default;

                    // Dereference the current iterator before returning
                    contained_iter_ret operator*() {
                        return *sorted_iter_type::operator*();
                    }
            };

            Sorted(const Sorted &) = default;

            IteratorIterator begin() {
                IteratorIterator iteriter(sorted_iters.begin());
                return iteriter;
            }

            IteratorIterator end() {
                IteratorIterator iteriter(sorted_iters.end());
                return iteriter;
            }
    };

    template <typename Container>
    Sorted<Container> sorted(Container & container) {
        return Sorted<Container>(container);
    }

}

#endif //#ifndef SORTED__HPP__
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>

using namespace std;

class XOREncryptor
{
public:
    XOREncryptor(){}
    void encrypt(string fileName,string key);
    void decrypt(string fileName,string key);
};

int main(int argc,char* argv[])
{
    XOREncryptor xorEncryptor;
    string fileName,key,choice;
    if(argc==4)
    {
        fileName=argv[2];
        key=argv[3];
        choice=argv[1];
        if(choice=="encrypt")
            xorEncryptor.encrypt(fileName,key);
        else if(choice=="decrypt")
            xorEncryptor.decrypt(fileName,key);
        else
            cout<<"Usage: "<<argv[0]<<" <encrypt/decrypt> <filename> <key>"<<endl;
    }
    else
        cout<<"Usage: "<<argv[0]<<" <encrypt/decrypt> <filename> <key>"<<endl;
    system("pause");
    return 0;
}

void XOREncryptor::encrypt(string fileName,string key)
{
    ifstream iFile;
    ofstream oFile;
    string outFile=fileName+".xre";
    int i=0;
    char temp;
    char *charptr=&temp;
    try
    {
        iFile.open(fileName,ios::binary|ios::in);
        oFile.open(outFile,ios::binary|ios::out|ios::trunc);
        if(!(oFile.is_open()||iFile.is_open()))
            throw 1;
        cout<<"Encrypting File... Please Wait!"<<endl;
        while(iFile.read(charptr,1))
        {
            temp=temp^key[(i++)%key.length()];
            oFile.put(temp);
        }
        iFile.close();
        oFile.close();
    }
    catch(int error)
    {
        cout<<"ERROR during opening file."<<endl;
        exit(1);
    }
    cout<<"File encrypted successfully!!!"<<endl;
}

void XOREncryptor::decrypt(string fileName,string key)
{
    ifstream iFile;
    ofstream oFile;
    string outFile;
    outFile=fileName.substr(0,fileName.length()-4);
    int i=0;
    char temp;
    char *charptr=&temp;
    try
    {
        iFile.open(fileName,ios::binary|ios::in);
        oFile.open(outFile,ios::binary|ios::out|ios::trunc);
        if(!(oFile.is_open()||iFile.is_open()))
            throw 1;
        cout<<"Decrypting File... Please Wait!"<<endl;
        while(iFile.read(charptr,1))
        {
            temp=temp^key[(i++)%key.length()];
            oFile.put(temp);
        }
        iFile.close();
        oFile.close();
    }
    catch(int error)
    {
        cout<<"ERROR during opening file."<<endl;
        exit(1);
    }
    cout<<"File decrypted successfully!!!"<<endl;
}
<commit_msg>Update source.cpp<commit_after>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>

using namespace std;

class XOREncryptor
{
public:
    XOREncryptor(){}
    void encrypt(string fileName,string key);
    void decrypt(string fileName,string key);
};

int main(int argc,char* argv[])
{
    XOREncryptor xorEncryptor;
    string fileName,key,choice;
    if(argc==4)
    {
        fileName=argv[2];
        key=argv[3];
        choice=argv[1];
        if(choice=="encrypt")
            xorEncryptor.encrypt(fileName,key);
        else if(choice=="decrypt")
            xorEncryptor.decrypt(fileName,key);
        else
            cout<<"Usage: "<<argv[0]<<" <encrypt/decrypt> <filename> <key>"<<endl;
    }
    else
        cout<<"Usage: "<<argv[0]<<" <encrypt/decrypt> <filename> <key>"<<endl;
    cout<<"Enter any key to continue..."<<endl;
    cin.ignore();
    cin.get();
    return 0;
}

void XOREncryptor::encrypt(string fileName,string key)
{
    ifstream iFile;
    ofstream oFile;
    string outFile=fileName+".xre";
    int i=0;
    char temp;
    char *charptr=&temp;
    try
    {
        iFile.open(fileName,ios::binary|ios::in);
        oFile.open(outFile,ios::binary|ios::out|ios::trunc);
        if(!(oFile.is_open()||iFile.is_open()))
            throw 1;
        cout<<"Encrypting File... Please Wait!"<<endl;
        while(iFile.read(charptr,1))
        {
            temp=temp^key[(i++)%key.length()];
            oFile.put(temp);
        }
        iFile.close();
        oFile.close();
    }
    catch(int error)
    {
        cout<<"ERROR during opening file."<<endl;
        exit(1);
    }
    cout<<"File encrypted successfully!!!"<<endl;
}

void XOREncryptor::decrypt(string fileName,string key)
{
    ifstream iFile;
    ofstream oFile;
    string outFile;
    outFile=fileName.substr(0,fileName.length()-4);
    int i=0;
    char temp;
    char *charptr=&temp;
    try
    {
        iFile.open(fileName,ios::binary|ios::in);
        oFile.open(outFile,ios::binary|ios::out|ios::trunc);
        if(!(oFile.is_open()||iFile.is_open()))
            throw 1;
        cout<<"Decrypting File... Please Wait!"<<endl;
        while(iFile.read(charptr,1))
        {
            temp=temp^key[(i++)%key.length()];
            oFile.put(temp);
        }
        iFile.close();
        oFile.close();
    }
    catch(int error)
    {
        cout<<"ERROR during opening file."<<endl;
        exit(1);
    }
    cout<<"File decrypted successfully!!!"<<endl;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>

bool samePrimeFactor(unsigned long long m, unsigned long long c);

int main() {
	unsigned long long 	i = 1,
						mersenne,
						candidate;

	std::cout << "\nFinds candidates using <<mersanne>> and checks if they"
			  << " are valid.\nProceeds to print out the <<perfect numbers>>"
			  << " until the amount of \ndigits overreaches its variable.\n";

	do {
		i++;
		mersenne = (pow(2, i) - 1);
		candidate = (pow(2, i-1)) * mersenne;

		if (samePrimeFactor(mersenne, candidate)){
			std::cout << "\nPerfect number: " << candidate;
			if (mersenne < 999) std::cout << '\t';
			if (mersenne < 999999) std::cout << '\t';
			std::cout << "\twith mersenne: " << mersenne;
		}

	} while (candidate != 0);

	return 0;
}

bool samePrimeFactor(unsigned long long m, unsigned long long c) {

	unsigned long long i = 2;

	while (i*i <= c) {
		if (c % i == 0)
			c /= i;
		else
			i++;
	}
	if (c == m)
		return 1;

	return 0;
}<commit_msg>fixed typo<commit_after>#include <iostream>
#include <cmath>

bool samePrimeFactor(unsigned long long m, unsigned long long c);

int main() {
	unsigned long long 	i = 1,
						mersenne,
						candidate;

	std::cout << "\nFinds candidates using <<mersenne>> and checks if they"
			  << " are valid.\nProceeds to print out the <<perfect numbers>>"
			  << " until the amount of \ndigits overreaches its variable.\n";

	do {
		i++;
		mersenne = (pow(2, i) - 1);
		candidate = (pow(2, i-1)) * mersenne;

		if (samePrimeFactor(mersenne, candidate)){
			std::cout << "\nPerfect number: " << candidate;
			if (mersenne < 999) std::cout << '\t';
			if (mersenne < 999999) std::cout << '\t';
			std::cout << "\twith mersenne: " << mersenne;
		}

	} while (candidate != 0);

	return 0;
}

bool samePrimeFactor(unsigned long long m, unsigned long long c) {

	unsigned long long i = 2;

	while (i*i <= c) {
		if (c % i == 0)
			c /= i;
		else
			i++;
	}
	if (c == m)
		return 1;

	return 0;
}
<|endoftext|>


<commit_before>#ifndef _PNMC_PN_NET_HH_
#define _PNMC_PN_NET_HH_

#include <deque>

#pragma GCC diagnostic push
#if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#pragma GCC diagnostic pop

#include "pn/module.hh"
#include "pn/place.hh"
#include "pn/transition.hh"

namespace pnmc { namespace pn {

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

using namespace boost::multi_index;

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

struct net
{
private:

  /// @brief A tag to identify the view ordered by insertion order for boost::multi_index.
  struct insertion_index{};

  /// @brief A tag to identify the view ordered by idendifiers for boost::multi_index.
  struct id_index{};

  /// @brief A tag to identify the view ordered by markings for boost::multi_index.
  struct marking_index{};

  /// @brief A tag to identify the view ordered by indices for boost::multi_index.
  struct index_index{};

public:

  /// @brief The type of the set of all places.
  typedef multi_index_container<
                place
  						, indexed_by<

                  // keep insertion order
                    sequenced<tag<insertion_index>>

                  // sort by id
                  ,  ordered_unique< tag<id_index>
                                   , member<place, const std::string, &place::id>>

                  // sort by marking
                  , ordered_non_unique< tag<marking_index>
                                      , member<place, unsigned int, &place::marking>>
              >
          > places_type;

  /// @brief The type of the set of all transitions.
  typedef multi_index_container<
                transition
              , indexed_by<

                   // sort by id
                     ordered_unique< tag<id_index>
                                   , member<transition, const std::string, &transition::id>>

                   // sort by index
                   , ordered_unique< tag<index_index>
                                   , member<transition, const std::size_t, &transition::index>>
              >
         > transitions_type;

  /// @brief The net's name.
  std::string name;

  /// @brief The set of places.
  places_type places_set;

  /// @brief The set of transitions.
  transitions_type transitions_set;

  /// @brief The hierarchical description, if any, of this Petri net.
  module modules;

  /// @brief BPN units.
  std::deque<std::deque<std::reference_wrapper<const place>>> units;
//  std::size_t nb_units;

  /// @brief Default constructor.
  net();

  /// @brief Add a place.
  ///
  /// If the place already exist, its marking is updated.
  const place&
  add_place(const std::string& id, unsigned int marking, unsigned int unit);

  /// @brief Add a transition.
  ///
  /// If the transition already exists, no operation is done.
  const transition&
  add_transition(const std::string& tid);

  /// @brief Add a post place to a transition.
  void
  add_post_place(const std::string& tid, const std::string& post, unsigned int marking);

  /// @brief Add a pre place to a transition.
  void
  add_pre_place(const std::string& tid, const std::string& pre, unsigned int marking);

  /// @brief Update a place.
  void
  update_place(const std::string pid, unsigned int marking);

  /// @brief Return all places by insertion order.
  const places_type::index<insertion_index>::type&
  places() const noexcept;

  /// @brief Return all places by identifier.
  const places_type::index<id_index>::type&
  places_by_id() const noexcept;

  /// @brief Return all transitions.
  const transitions_type::index<id_index>::type&
  transitions() const noexcept;

  /// @brief Get a transition using its index.
  const transition&
  get_transition_by_index(std::size_t index) const;
};

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

}} // namespace pnmc::pn

#endif // _PNMC_PN_NET_HH_
<commit_msg>Cleanup.<commit_after>#ifndef _PNMC_PN_NET_HH_
#define _PNMC_PN_NET_HH_

#include <deque>

#pragma GCC diagnostic push
#if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#pragma GCC diagnostic pop

#include "pn/module.hh"
#include "pn/place.hh"
#include "pn/transition.hh"

namespace pnmc { namespace pn {

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

using namespace boost::multi_index;

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

struct net
{
private:

  /// @brief A tag to identify the view ordered by insertion order for boost::multi_index.
  struct insertion_index{};

  /// @brief A tag to identify the view ordered by idendifiers for boost::multi_index.
  struct id_index{};

  /// @brief A tag to identify the view ordered by markings for boost::multi_index.
  struct marking_index{};

  /// @brief A tag to identify the view ordered by indices for boost::multi_index.
  struct index_index{};

public:

  /// @brief The type of the set of all places.
  typedef multi_index_container<
                place
  						, indexed_by<

                  // keep insertion order
                    sequenced<tag<insertion_index>>

                  // sort by id
                  ,  ordered_unique< tag<id_index>
                                   , member<place, const std::string, &place::id>>

                  // sort by marking
                  , ordered_non_unique< tag<marking_index>
                                      , member<place, unsigned int, &place::marking>>
              >
          > places_type;

  /// @brief The type of the set of all transitions.
  typedef multi_index_container<
                transition
              , indexed_by<

                   // sort by id
                     ordered_unique< tag<id_index>
                                   , member<transition, const std::string, &transition::id>>

                   // sort by index
                   , ordered_unique< tag<index_index>
                                   , member<transition, const std::size_t, &transition::index>>
              >
         > transitions_type;

  /// @brief The net's name.
  std::string name;

  /// @brief The set of places.
  places_type places_set;

  /// @brief The set of transitions.
  transitions_type transitions_set;

  /// @brief The hierarchical description, if any, of this Petri net.
  module modules;

  /// @brief BPN units.
  std::deque<std::deque<std::reference_wrapper<const place>>> units;

  /// @brief Default constructor.
  net();

  /// @brief Add a place.
  const place&
  add_place(const std::string& id, unsigned int marking, unsigned int unit);

  /// @brief Add a transition.
  ///
  /// If the transition already exists, no operation is done.
  const transition&
  add_transition(const std::string& tid);

  /// @brief Add a post place to a transition.
  void
  add_post_place(const std::string& tid, const std::string& post, unsigned int marking);

  /// @brief Add a pre place to a transition.
  void
  add_pre_place(const std::string& tid, const std::string& pre, unsigned int marking);

  /// @brief Update a place.
  void
  update_place(const std::string pid, unsigned int marking);

  /// @brief Return all places by insertion order.
  const places_type::index<insertion_index>::type&
  places() const noexcept;

  /// @brief Return all places by identifier.
  const places_type::index<id_index>::type&
  places_by_id() const noexcept;

  /// @brief Return all transitions.
  const transitions_type::index<id_index>::type&
  transitions() const noexcept;

  /// @brief Get a transition using its index.
  const transition&
  get_transition_by_index(std::size_t index) const;
};

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

}} // namespace pnmc::pn

#endif // _PNMC_PN_NET_HH_
<|endoftext|>


<commit_before>/*
  This file is part of Ingen.
  Copyright 2007-2015 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef INGEN_WORLD_HPP
#define INGEN_WORLD_HPP

#include <string>

#include "ingen/ingen.h"
#include "ingen/types.hpp"
#include "lv2/lv2plug.in/ns/ext/log/log.h"
#include "lv2/lv2plug.in/ns/ext/urid/urid.h"
#include "raul/Noncopyable.hpp"
#include "raul/URI.hpp"

typedef struct LilvWorldImpl LilvWorld;

namespace Sord { class World; }

namespace Ingen {

class Configuration;
class EngineBase;
class Forge;
class Interface;
class LV2Features;
class Log;
class Parser;
class Serialiser;
class Store;
class URIMap;
class URIs;

/** The "world" all Ingen modules share.
 *
 * This is the root to which all components of Ingen are connected.  It
 * contains all necessary shared data (including the world for libraries like
 * Sord and Lilv) and holds references to components.
 *
 * Some functionality in Ingen is implemented in dynamically loaded modules,
 * which are loaded using this interface.  When loaded, those modules add
 * facilities to the World which can then be used throughout the code.
 *
 * The world is used in any process which uses the Ingen as a library, both
 * client and server (e.g. the world may not actually contain an Engine, since
 * it maybe running in another process or even on a different machine).
 *
 * @ingroup IngenShared
 */
class INGEN_API World : public Raul::Noncopyable {
public:
	/** Construct a new Ingen world.
	 * @param argc Argument count (as in C main())
	 * @param argv Argument vector (as in C main())
	 * @param map LV2 URID map implementation, or NULL to use internal.
	 * @param unmap LV2 URID unmap implementation, or NULL to use internal.
	 * @param log LV2 log implementation, or NULL to use internal.
	 */
	World(int&            argc,
	      char**&         argv,
	      LV2_URID_Map*   map,
	      LV2_URID_Unmap* unmap,
	      LV2_Log_Log*    log);

	virtual ~World();

	/** Load an Ingen module by name (e.g. "server", "gui", etc.)
	 * @return True on success.
	 */
	virtual bool load_module(const char* name);

	/** Run a loaded module (modules that "run" only, e.g. gui).
	 * @return True on success.
	 */
	virtual bool run_module(const char* name);

	/** A function to create a new remote Interface. */
	typedef SPtr<Interface> (*InterfaceFactory)(
		World*           world,
		const Raul::URI& engine_uri,
		SPtr<Interface>  respondee);

	/** Register an InterfaceFactory (for module implementations). */
	virtual void add_interface_factory(const std::string& scheme,
	                                   InterfaceFactory   factory);

	/** Return a new Interface to control a server.
	 * @param engine_uri The URI of the possibly remote server to control.
	 * @param respondee The Interface that will receive responses to commands
	 *                  and broadcasts, if applicable.
	 */
	virtual SPtr<Interface> new_interface(const Raul::URI& engine_uri,
	                                      SPtr<Interface>  respondee);

	/** Run a script. */
	virtual bool run(const std::string& mime_type,
	                 const std::string& filename);

	virtual void set_engine(SPtr<EngineBase> e);
	virtual void set_interface(SPtr<Interface> e);
	virtual void set_store(SPtr<Store> s);

	virtual SPtr<EngineBase> engine();
	virtual SPtr<Interface>  interface();
	virtual SPtr<Parser>     parser();
	virtual SPtr<Serialiser> serialiser();
	virtual SPtr<Store>      store();

	virtual int&           argc();
	virtual char**&        argv();
	virtual Configuration& conf();

	virtual Sord::World* rdf_world();
	virtual LilvWorld*   lilv_world();

	virtual LV2Features&  lv2_features();
	virtual Ingen::Forge& forge();
	virtual URIMap&       uri_map();
	virtual URIs&         uris();

	virtual void        set_jack_uuid(const std::string& uuid);
	virtual std::string jack_uuid();

	virtual Log& log();

private:
	class Impl;

	Impl* _impl;
};

}  // namespace Ingen

#endif  // INGEN_WORLD_HPP
<commit_msg>Fix partial commit.<commit_after>/*
  This file is part of Ingen.
  Copyright 2007-2015 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef INGEN_WORLD_HPP
#define INGEN_WORLD_HPP

#include <mutex>
#include <string>

#include "ingen/ingen.h"
#include "ingen/types.hpp"
#include "lv2/lv2plug.in/ns/ext/log/log.h"
#include "lv2/lv2plug.in/ns/ext/urid/urid.h"
#include "raul/Noncopyable.hpp"
#include "raul/URI.hpp"

typedef struct LilvWorldImpl LilvWorld;

namespace Sord { class World; }

namespace Ingen {

class Configuration;
class EngineBase;
class Forge;
class Interface;
class LV2Features;
class Log;
class Parser;
class Serialiser;
class Store;
class URIMap;
class URIs;

/** The "world" all Ingen modules share.
 *
 * This is the root to which all components of Ingen are connected.  It
 * contains all necessary shared data (including the world for libraries like
 * Sord and Lilv) and holds references to components.
 *
 * Some functionality in Ingen is implemented in dynamically loaded modules,
 * which are loaded using this interface.  When loaded, those modules add
 * facilities to the World which can then be used throughout the code.
 *
 * The world is used in any process which uses the Ingen as a library, both
 * client and server (e.g. the world may not actually contain an Engine, since
 * it maybe running in another process or even on a different machine).
 *
 * @ingroup IngenShared
 */
class INGEN_API World : public Raul::Noncopyable {
public:
	/** Construct a new Ingen world.
	 * @param argc Argument count (as in C main())
	 * @param argv Argument vector (as in C main())
	 * @param map LV2 URID map implementation, or NULL to use internal.
	 * @param unmap LV2 URID unmap implementation, or NULL to use internal.
	 * @param log LV2 log implementation, or NULL to use internal.
	 */
	World(int&            argc,
	      char**&         argv,
	      LV2_URID_Map*   map,
	      LV2_URID_Unmap* unmap,
	      LV2_Log_Log*    log);

	virtual ~World();

	/** Load an Ingen module by name (e.g. "server", "gui", etc.)
	 * @return True on success.
	 */
	virtual bool load_module(const char* name);

	/** Run a loaded module (modules that "run" only, e.g. gui).
	 * @return True on success.
	 */
	virtual bool run_module(const char* name);

	/** A function to create a new remote Interface. */
	typedef SPtr<Interface> (*InterfaceFactory)(
		World*           world,
		const Raul::URI& engine_uri,
		SPtr<Interface>  respondee);

	/** Register an InterfaceFactory (for module implementations). */
	virtual void add_interface_factory(const std::string& scheme,
	                                   InterfaceFactory   factory);

	/** Return a new Interface to control a server.
	 * @param engine_uri The URI of the possibly remote server to control.
	 * @param respondee The Interface that will receive responses to commands
	 *                  and broadcasts, if applicable.
	 */
	virtual SPtr<Interface> new_interface(const Raul::URI& engine_uri,
	                                      SPtr<Interface>  respondee);

	/** Run a script. */
	virtual bool run(const std::string& mime_type,
	                 const std::string& filename);

	virtual void set_engine(SPtr<EngineBase> e);
	virtual void set_interface(SPtr<Interface> e);
	virtual void set_store(SPtr<Store> s);

	virtual SPtr<EngineBase> engine();
	virtual SPtr<Interface>  interface();
	virtual SPtr<Parser>     parser();
	virtual SPtr<Serialiser> serialiser();
	virtual SPtr<Store>      store();

	virtual int&           argc();
	virtual char**&        argv();
	virtual Configuration& conf();

	/** Lock for rdf_world() or lilv_world(). */
	virtual std::mutex& rdf_mutex();

	virtual Sord::World* rdf_world();
	virtual LilvWorld*   lilv_world();

	virtual LV2Features&  lv2_features();
	virtual Ingen::Forge& forge();
	virtual URIMap&       uri_map();
	virtual URIs&         uris();

	virtual void        set_jack_uuid(const std::string& uuid);
	virtual std::string jack_uuid();

	virtual Log& log();

private:
	class Impl;

	Impl* _impl;
};

}  // namespace Ingen

#endif  // INGEN_WORLD_HPP
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmlenginedebug_p.h"
#include <QtCore/qdebug.h>
#include <QtCore/qmetaobject.h>
#include <QtDeclarative/qmlengine.h>
#include <QtDeclarative/qmlmetatype.h>
#include <qmlmetaproperty.h>
#include <qmlbinding.h>
#include "qmlcontext_p.h"

QT_BEGIN_NAMESPACE

QList<QmlEngine *> QmlEngineDebugServer::m_engines;
QmlEngineDebugServer::QmlEngineDebugServer(QObject *parent)
: QmlDebugService(QLatin1String("QmlEngine"), parent)
{
}

QDataStream &operator<<(QDataStream &ds,
                        const QmlEngineDebugServer::QmlObjectData &data)
{
    ds << data.url << data.lineNumber << data.columnNumber << data.objectName
       << data.objectType << data.objectId;
    return ds;
}

QDataStream &operator>>(QDataStream &ds,
                        QmlEngineDebugServer::QmlObjectData &data)
{
    ds >> data.url >> data.lineNumber >> data.columnNumber >> data.objectName
       >> data.objectType >> data.objectId;
    return ds;
}

QDataStream &operator<<(QDataStream &ds,
                        const QmlEngineDebugServer::QmlObjectProperty &data)
{
    ds << (int)data.type << data.name << data.value << data.binding;
    return ds;
}

QDataStream &operator>>(QDataStream &ds,
                        QmlEngineDebugServer::QmlObjectProperty &data)
{
    int type;
    ds >> type >> data.name >> data.value >> data.binding;
    data.type = (QmlEngineDebugServer::QmlObjectProperty::Type)type;
    return ds;
}

QmlEngineDebugServer::QmlObjectProperty
QmlEngineDebugServer::propertyData(QObject *obj, int propIdx)
{
    QmlObjectProperty rv;

    QMetaProperty prop = obj->metaObject()->property(propIdx);

    rv.type = QmlObjectProperty::Unknown;
    rv.name = prop.name();
    QmlAbstractBinding *binding = QmlMetaProperty(obj, rv.name).binding();
    if (binding)
        rv.binding = binding->expression();

    if (prop.type() < QVariant::UserType) {
        rv.type = QmlObjectProperty::Basic;
        rv.value = prop.read(obj);
    } else if (QmlMetaType::isObject(prop.userType()))  {
        rv.type = QmlObjectProperty::Object;
    } else if (QmlMetaType::isList(prop.userType()) ||
               QmlMetaType::isQmlList(prop.userType())) {
        rv.type = QmlObjectProperty::List;
    }
    return rv;
}

void QmlEngineDebugServer::buildObjectDump(QDataStream &message,
                                           QObject *object, bool recur)
{
    message << objectData(object);
    message << object->metaObject()->propertyCount();

    for (int ii = 0; ii < object->metaObject()->propertyCount(); ++ii)
        message << propertyData(object, ii);

    QObjectList children = object->children();
    message << children.count() << recur;

    for (int ii = 0; ii < children.count(); ++ii) {
        QObject *child = children.at(ii);
        if (recur)
            buildObjectDump(message, child, recur);
        else
            message << objectData(child);
    }
}

void QmlEngineDebugServer::buildObjectList(QDataStream &message,
                                           QmlContext *ctxt)
{
    QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(ctxt);

    QString ctxtName = ctxt->objectName();
    int ctxtId = QmlDebugService::idForObject(ctxt);

    message << ctxtName << ctxtId;

    int count = 0;

    for (QSet<QmlContext *>::ConstIterator iter = p->childContexts.begin();
            iter != p->childContexts.end(); ++iter) {
        QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(*iter);
        if (p->isInternal)
            continue;
        ++count;
    }

    message << count;

    for (QSet<QmlContext *>::ConstIterator iter = p->childContexts.begin();
            iter != p->childContexts.end(); ++iter) {
        QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(*iter);
        if (p->isInternal)
            continue;
        buildObjectList(message, *iter);
    }

    // Clean deleted objects
    for (int ii = 0; ii < p->instances.count(); ++ii) {
        if (!p->instances.at(ii)) {
            p->instances.removeAt(ii);
            --ii;
        }
    }

    message << p->instances.count();
    for (int ii = 0; ii < p->instances.count(); ++ii) {
        message << objectData(p->instances.at(ii));
    }
}

QmlEngineDebugServer::QmlObjectData
QmlEngineDebugServer::objectData(QObject *object)
{
    QmlDeclarativeData *ddata = QmlDeclarativeData::get(object);
    QmlObjectData rv;
    if (ddata) {
        rv.url = ddata->outerContext->baseUrl();
        rv.lineNumber = ddata->lineNumber;
        rv.columnNumber = ddata->columnNumber;
    } else {
        rv.lineNumber = -1;
        rv.columnNumber = -1;
    }

    rv.objectName = object->objectName();
    rv.objectType = object->metaObject()->className();
    rv.objectId = QmlDebugService::idForObject(object);

    return rv;
}

void QmlEngineDebugServer::messageReceived(const QByteArray &message)
{
    QDataStream ds(message);

    QByteArray type;
    ds >> type;

    if (type == "LIST_ENGINES") {
        int queryId;
        ds >> queryId;

        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("LIST_ENGINES_R");
        rs << queryId << m_engines.count();

        for (int ii = 0; ii < m_engines.count(); ++ii) {
            QmlEngine *engine = m_engines.at(ii);

            QString engineName = engine->objectName();
            int engineId = QmlDebugService::idForObject(engine);

            rs << engineName << engineId;
        }

        sendMessage(reply);
    } else if (type == "LIST_OBJECTS") {
        int queryId;
        int engineId = -1;
        ds >> queryId >> engineId;

        QmlEngine *engine =
            qobject_cast<QmlEngine *>(QmlDebugService::objectForId(engineId));

        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("LIST_OBJECTS_R") << queryId;

        if (engine)
            buildObjectList(rs, engine->rootContext());

        sendMessage(reply);
    } else if (type == "FETCH_OBJECT") {
        int queryId;
        int objectId;
        bool recurse;

        ds >> queryId >> objectId >> recurse;

        QObject *object = QmlDebugService::objectForId(objectId);

        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("FETCH_OBJECT_R") << queryId;

        if (object)
            buildObjectDump(rs, object, recurse);

        sendMessage(reply);
    }
}

void QmlEngineDebugServer::addEngine(QmlEngine *engine)
{
    Q_ASSERT(engine);
    Q_ASSERT(!m_engines.contains(engine));

    m_engines.append(engine);
}

void QmlEngineDebugServer::remEngine(QmlEngine *engine)
{
    Q_ASSERT(engine);
    Q_ASSERT(m_engines.contains(engine));

    m_engines.removeAll(engine);
}

QT_END_NAMESPACE
<commit_msg>Don't crash. The engine tree shouldn't have all these objects in it, but for now, just prevent crash when there are signals with parameters.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmlenginedebug_p.h"
#include "qmlboundsignal_p.h"
#include <QtCore/qdebug.h>
#include <QtCore/qmetaobject.h>
#include <QtDeclarative/qmlengine.h>
#include <QtDeclarative/qmlmetatype.h>
#include <qmlmetaproperty.h>
#include <qmlbinding.h>
#include "qmlcontext_p.h"

QT_BEGIN_NAMESPACE

QList<QmlEngine *> QmlEngineDebugServer::m_engines;
QmlEngineDebugServer::QmlEngineDebugServer(QObject *parent)
: QmlDebugService(QLatin1String("QmlEngine"), parent)
{
}

QDataStream &operator<<(QDataStream &ds,
                        const QmlEngineDebugServer::QmlObjectData &data)
{
    ds << data.url << data.lineNumber << data.columnNumber << data.objectName
       << data.objectType << data.objectId;
    return ds;
}

QDataStream &operator>>(QDataStream &ds,
                        QmlEngineDebugServer::QmlObjectData &data)
{
    ds >> data.url >> data.lineNumber >> data.columnNumber >> data.objectName
       >> data.objectType >> data.objectId;
    return ds;
}

QDataStream &operator<<(QDataStream &ds,
                        const QmlEngineDebugServer::QmlObjectProperty &data)
{
    ds << (int)data.type << data.name << data.value << data.binding;
    return ds;
}

QDataStream &operator>>(QDataStream &ds,
                        QmlEngineDebugServer::QmlObjectProperty &data)
{
    int type;
    ds >> type >> data.name >> data.value >> data.binding;
    data.type = (QmlEngineDebugServer::QmlObjectProperty::Type)type;
    return ds;
}

QmlEngineDebugServer::QmlObjectProperty
QmlEngineDebugServer::propertyData(QObject *obj, int propIdx)
{
    QmlObjectProperty rv;

    QMetaProperty prop = obj->metaObject()->property(propIdx);

    rv.type = QmlObjectProperty::Unknown;
    rv.name = prop.name();
    QmlAbstractBinding *binding = QmlMetaProperty(obj, rv.name).binding();
    if (binding)
        rv.binding = binding->expression();

    if (prop.type() < QVariant::UserType) {
        rv.type = QmlObjectProperty::Basic;
        if (qobject_cast<QmlBoundSignalParameters*>(obj) && prop.name() != QByteArray("objectName"))
            // these "properties" only have meaning during signal emission
            rv.value = tr("(signal parameter)");
        else
            rv.value = prop.read(obj);
    } else if (QmlMetaType::isObject(prop.userType()))  {
        rv.type = QmlObjectProperty::Object;
    } else if (QmlMetaType::isList(prop.userType()) ||
               QmlMetaType::isQmlList(prop.userType())) {
        rv.type = QmlObjectProperty::List;
    }
    return rv;
}

void QmlEngineDebugServer::buildObjectDump(QDataStream &message,
                                           QObject *object, bool recur)
{
    message << objectData(object);
    message << object->metaObject()->propertyCount();

    for (int ii = 0; ii < object->metaObject()->propertyCount(); ++ii)
        message << propertyData(object, ii);

    QObjectList children = object->children();
    message << children.count() << recur;

    for (int ii = 0; ii < children.count(); ++ii) {
        QObject *child = children.at(ii);
        if (recur)
            buildObjectDump(message, child, recur);
        else
            message << objectData(child);
    }
}

void QmlEngineDebugServer::buildObjectList(QDataStream &message,
                                           QmlContext *ctxt)
{
    QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(ctxt);

    QString ctxtName = ctxt->objectName();
    int ctxtId = QmlDebugService::idForObject(ctxt);

    message << ctxtName << ctxtId;

    int count = 0;

    for (QSet<QmlContext *>::ConstIterator iter = p->childContexts.begin();
            iter != p->childContexts.end(); ++iter) {
        QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(*iter);
        if (p->isInternal)
            continue;
        ++count;
    }

    message << count;

    for (QSet<QmlContext *>::ConstIterator iter = p->childContexts.begin();
            iter != p->childContexts.end(); ++iter) {
        QmlContextPrivate *p = (QmlContextPrivate *)QObjectPrivate::get(*iter);
        if (p->isInternal)
            continue;
        buildObjectList(message, *iter);
    }

    // Clean deleted objects
    for (int ii = 0; ii < p->instances.count(); ++ii) {
        if (!p->instances.at(ii)) {
            p->instances.removeAt(ii);
            --ii;
        }
    }

    message << p->instances.count();
    for (int ii = 0; ii < p->instances.count(); ++ii) {
        message << objectData(p->instances.at(ii));
    }
}

QmlEngineDebugServer::QmlObjectData
QmlEngineDebugServer::objectData(QObject *object)
{
    QmlDeclarativeData *ddata = QmlDeclarativeData::get(object);
    QmlObjectData rv;
    if (ddata) {
        rv.url = ddata->outerContext->baseUrl();
        rv.lineNumber = ddata->lineNumber;
        rv.columnNumber = ddata->columnNumber;
    } else {
        rv.lineNumber = -1;
        rv.columnNumber = -1;
    }

    rv.objectName = object->objectName();
    rv.objectType = object->metaObject()->className();
    rv.objectId = QmlDebugService::idForObject(object);

    return rv;
}

void QmlEngineDebugServer::messageReceived(const QByteArray &message)
{
    QDataStream ds(message);

    QByteArray type;
    ds >> type;

    if (type == "LIST_ENGINES") {
        int queryId;
        ds >> queryId;

        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("LIST_ENGINES_R");
        rs << queryId << m_engines.count();

        for (int ii = 0; ii < m_engines.count(); ++ii) {
            QmlEngine *engine = m_engines.at(ii);

            QString engineName = engine->objectName();
            int engineId = QmlDebugService::idForObject(engine);

            rs << engineName << engineId;
        }

        sendMessage(reply);
    } else if (type == "LIST_OBJECTS") {
        int queryId;
        int engineId = -1;
        ds >> queryId >> engineId;

        QmlEngine *engine =
            qobject_cast<QmlEngine *>(QmlDebugService::objectForId(engineId));

        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("LIST_OBJECTS_R") << queryId;

        if (engine)
            buildObjectList(rs, engine->rootContext());

        sendMessage(reply);
    } else if (type == "FETCH_OBJECT") {
        int queryId;
        int objectId;
        bool recurse;

        ds >> queryId >> objectId >> recurse;

        QObject *object = QmlDebugService::objectForId(objectId);

        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("FETCH_OBJECT_R") << queryId;

        if (object)
            buildObjectDump(rs, object, recurse);

        sendMessage(reply);
    }
}

void QmlEngineDebugServer::addEngine(QmlEngine *engine)
{
    Q_ASSERT(engine);
    Q_ASSERT(!m_engines.contains(engine));

    m_engines.append(engine);
}

void QmlEngineDebugServer::remEngine(QmlEngine *engine)
{
    Q_ASSERT(engine);
    Q_ASSERT(m_engines.contains(engine));

    m_engines.removeAll(engine);
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/*
 * Reference: http://www.indiana.edu/~iulg/trm/
 *
 * Instruction set
 * ===============
 * Add 1 to Rn   : 1^n#
 *   Rn.push(1)
 *
 * Add # to Rn   : 1^n##
 *   Rn.push(#)
 *
 * Go forward n  : 1^n###
 *   pc += n
 * Go backward n : 1^n####
 *   pc -= n
 *
 * Cases on Rn   : 1^n#####
 *   if Rn.empty(), pc += 1
 *   if Rn.pop() == 1, pc += 2
 *   if Rn.pop() == #, pc += 3
 */

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <queue>

using namespace std;

enum Code {
    O,
    H
};

enum Op {
    Add1 = 1,
    Add0 = 2,
    Inc = 3,
    Dec = 4,
    Case = 5
};

struct Instr {
    Op o;
    int n;
};

vector< Instr > program;
map< int, queue<Code> > mem;

void push(int i, Code c) {
    mem[i].push(c);
}

int cases(int i) {
    queue<Code>& Rn = mem[i];
    if (Rn.empty()) {
        return 1;
    } else if (Rn.front() == O) {
        Rn.pop();
        return 2;
    } else if (Rn.front() == H) {
        Rn.pop();
        return 3;
    }
}

void print_registers() {
    for (map< int, queue<Code> >::iterator it=mem.begin(); it != mem.end(); it++) {
        cout << "R" << it->first << ":";
        queue<Code> content = it->second;
        while (content.empty() == false) {
            Code c = content.front();
            content.pop();
            if (c == O) {
                cout << "1";
            } else {
                cout << "#";
            }
        }
        cout << endl;
    }
}

string op2string(Op o) {
    switch (o) {
        case Add1: return "Add1";
        case Add0: return "Add#";
        case Inc:  return "Inc";
        case Dec:  return "Dec";
        case Case: return "Case";
    }
}

string instr2string(Instr in) {
     return op2string(in.o) + " " + to_string(in.n);
}

void print_program() {
    for ( auto &p : program) {
        cout << instr2string(p) << endl;
    }
}

void eval(int pc) {
    while (pc < program.size()) {
        Instr in = program[pc];
        //cout << "pc:" + to_string(pc) + " " + "instr: " + instr2string(in) << endl;
        switch (in.o) {
            case Add1:
                push(in.n, O);
                pc++;
                break;

            case Add0:
                push(in.n, H);
                pc++;
                break;

            case Inc:
                pc += in.n;
                break;

            case Dec:
                pc -= in.n;
                break;

            case Case:
                pc += cases(in.n);
                break;
        }
    }
}

void load_program() {
    cin.sync_with_stdio(false);

    char curr;

    int n = 0;
    int c = 0;

    while (cin >> curr) {
        if (curr == '1') {
            if (c > 0) {
                program.push_back({(Op)c, n});
                n = 0;
                c = 0;
            }
            n++;
        } else if (curr == '#') {
            c++;
        }
    }
    program.push_back({(Op)c, n});
}

int main() {
    load_program();
    //print_program();
    eval(0);
    print_registers();
    return 0;
}
<commit_msg>remove extra call to push_back<commit_after>/*
 * Reference: http://www.indiana.edu/~iulg/trm/
 *
 * Instruction set
 * ===============
 * Add 1 to Rn   : 1^n#
 *   Rn.push(1)
 *
 * Add # to Rn   : 1^n##
 *   Rn.push(#)
 *
 * Go forward n  : 1^n###
 *   pc += n
 * Go backward n : 1^n####
 *   pc -= n
 *
 * Cases on Rn   : 1^n#####
 *   if Rn.empty(), pc += 1
 *   if Rn.pop() == 1, pc += 2
 *   if Rn.pop() == #, pc += 3
 */

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <queue>

using namespace std;

enum Code {
    O,
    H
};

enum Op {
    Add1 = 1,
    Add0 = 2,
    Inc = 3,
    Dec = 4,
    Case = 5
};

struct Instr {
    Op o;
    int n;
};

vector< Instr > program;
map< int, queue<Code> > mem;

void push(int i, Code c) {
    mem[i].push(c);
}

int cases(int i) {
    queue<Code>& Rn = mem[i];
    if (Rn.empty()) {
        return 1;
    } else if (Rn.front() == O) {
        Rn.pop();
        return 2;
    } else if (Rn.front() == H) {
        Rn.pop();
        return 3;
    }
}

void print_registers() {
    for (map< int, queue<Code> >::iterator it=mem.begin(); it != mem.end(); it++) {
        cout << "R" << it->first << ":";
        queue<Code> content = it->second;
        while (content.empty() == false) {
            Code c = content.front();
            content.pop();
            if (c == O) {
                cout << "1";
            } else {
                cout << "#";
            }
        }
        cout << endl;
    }
}

string op2string(Op o) {
    switch (o) {
        case Add1: return "Add1";
        case Add0: return "Add#";
        case Inc:  return "Inc";
        case Dec:  return "Dec";
        case Case: return "Case";
    }
}

string instr2string(Instr in) {
     return op2string(in.o) + " " + to_string(in.n);
}

void print_program() {
    for ( auto &p : program) {
        cout << instr2string(p) << endl;
    }
}

void eval(int pc) {
    while (pc < program.size()) {
        Instr in = program[pc];
        //cout << "pc:" + to_string(pc) + " " + "instr: " + instr2string(in) << endl;
        switch (in.o) {
            case Add1:
                push(in.n, O);
                pc++;
                break;

            case Add0:
                push(in.n, H);
                pc++;
                break;

            case Inc:
                pc += in.n;
                break;

            case Dec:
                pc -= in.n;
                break;

            case Case:
                pc += cases(in.n);
                break;
        }
    }
}

void load_program() {
    cin.sync_with_stdio(false);

    char curr;

    int n = 0;
    int c = 0;

    while (cin >> curr) {
        if (curr == '1') {
            if (c > 0) {
                n = 0;
                c = 0;
            }
            n++;
        } else if (curr == '#') {
            c++;
            if (c == 1) {
                program.push_back({Add1, n});
            } else {
                program.back().o = (Op)c;
            }
        }
    }
}

int main() {
    load_program();
    //print_program();
    eval(0);
    print_registers();
    return 0;
}
<|endoftext|>


<commit_before>//
//  Shape.hpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 10/28/12.
//
//

#ifndef __G3MiOSSDK__Shape__
#define __G3MiOSSDK__Shape__

#include "Geodetic3D.hpp"
#include "Context.hpp"
#include "Vector3D.hpp"

class MutableMatrix44D;

#include "Effects.hpp"
#include <vector>

#include "GLState.hpp"

#include "SurfaceElevationProvider.hpp"

#include "Geodetic3D.hpp"

class ShapePendingEffect;
class GPUProgramState;

class Shape : public SurfaceElevationListener, EffectTarget{
private:
  Geodetic3D* _position;
  AltitudeMode _altitudeMode;

  Angle*      _heading;
  Angle*      _pitch;

  double      _scaleX;
  double      _scaleY;
  double      _scaleZ;

//  const Planet* _planet;

  mutable MutableMatrix44D* _transformMatrix;
  MutableMatrix44D* createTransformMatrix(const Planet* planet) const;
  MutableMatrix44D* getTransformMatrix(const Planet* planet) const;

  std::vector<ShapePendingEffect*> _pendingEffects;

  bool _enable;

  mutable GLState* _glState;

  SurfaceElevationProvider* _surfaceElevationProvider;
  double _surfaceElevation;

protected:
  virtual void cleanTransformMatrix();

public:
  Shape(Geodetic3D* position, AltitudeMode altitudeMode) :
  _position( position ),
  _altitudeMode(altitudeMode),
  _heading( new Angle(Angle::zero()) ),
  _pitch( new Angle(Angle::zero()) ),
  _scaleX(1),
  _scaleY(1),
  _scaleZ(1),
  _transformMatrix(NULL),
  _enable(true),
  _surfaceElevation(0),
  _glState(new GLState())
  {

  }

  virtual ~Shape();

  const Geodetic3D getPosition() const {
    return *_position;
  }

  const Angle getHeading() const {
    return *_heading;
  }

  const Angle getPitch() const {
    return *_pitch;
  }

  void setPosition(Geodetic3D* position) {
    delete _position;
    _position = position;
    cleanTransformMatrix();
  }

  void addShapeEffect(Effect* effect);

  void setAnimatedPosition(const TimeInterval& duration,
                           const Geodetic3D& position,
                           bool linearInterpolation=false);

  void setAnimatedPosition(const TimeInterval& duration,
                           const Geodetic3D& position,
                           const Angle& pitch,
                           const Angle& heading,
                           bool linearInterpolation=false);

  void setAnimatedPosition(const Geodetic3D& position,
                           bool linearInterpolation=false) {
    setAnimatedPosition(TimeInterval::fromSeconds(3),
                        position,
                        linearInterpolation);
  }

  void setHeading(const Angle& heading) {
    delete _heading;
    _heading = new Angle(heading);
    cleanTransformMatrix();
  }

  void setPitch(const Angle& pitch) {
    delete _pitch;
    _pitch = new Angle(pitch);
    cleanTransformMatrix();
  }

  void setScale(double scale) {
    setScale(scale, scale, scale);
  }

  void setScale(double scaleX,
                double scaleY,
                double scaleZ) {
    _scaleX = scaleX;
    _scaleY = scaleY;
    _scaleZ = scaleZ;
    cleanTransformMatrix();
  }

  void setScale(const Vector3D& scale) {
    setScale(scale._x,
             scale._y,
             scale._z);
  }

  Vector3D getScale() const {
    return Vector3D(_scaleX,
                    _scaleY,
                    _scaleZ);
  }

  void setAnimatedScale(const TimeInterval& duration,
                        double scaleX,
                        double scaleY,
                        double scaleZ);

  void setAnimatedScale(double scaleX,
                        double scaleY,
                        double scaleZ) {
    setAnimatedScale(TimeInterval::fromSeconds(1),
                     scaleX, scaleY, scaleZ);
  }

  void setAnimatedScale(const Vector3D& scale) {
    setAnimatedScale(scale._x,
                     scale._y,
                     scale._z);
  }

  void setAnimatedScale(const TimeInterval& duration,
                        const Vector3D& scale) {
    setAnimatedScale(duration,
                     scale._x,
                     scale._y,
                     scale._z);
  }

  void orbitCamera(const TimeInterval& duration,
                   double fromDistance,       double toDistance,
                   const Angle& fromAzimuth,  const Angle& toAzimuth,
                   const Angle& fromAltitude, const Angle& toAltitude);

  bool isEnable() const {
    return _enable;
  }

  void setEnable(bool enable) {
    _enable = enable;
  }

  void render(const G3MRenderContext* rc,
              GLState* parentState,
              bool renderNotReadyShapes);

  virtual void initialize(const G3MContext* context) {

    _surfaceElevationProvider = context->getSurfaceElevationProvider();
    if (_surfaceElevationProvider != NULL) {
      _surfaceElevationProvider->addListener(_position->_latitude,
                                             _position->_longitude,
                                             this);
    }

  }

  virtual bool isReadyToRender(const G3MRenderContext* rc) = 0;

  virtual void rawRender(const G3MRenderContext* rc,
                         GLState* parentGLState,
                         bool renderNotReadyShapes) = 0;

  virtual bool isTransparent(const G3MRenderContext* rc) = 0;

  void elevationChanged(const Geodetic2D& position,
                        double rawElevation,            //Without considering vertical exaggeration
                        double verticalExaggeration);

  void elevationChanged(const Sector& position,
                   const ElevationData* rawElevationData, //Without considering vertical exaggeration
                        double verticalExaggeration){}

};

#endif
<commit_msg>Advances in CartoCSS parsing, not usable yet<commit_after>//
//  Shape.hpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 10/28/12.
//
//

#ifndef __G3MiOSSDK__Shape__
#define __G3MiOSSDK__Shape__

#include "Geodetic3D.hpp"
#include "Context.hpp"
#include "Vector3D.hpp"

class MutableMatrix44D;

#include "Effects.hpp"
#include <vector>

#include "GLState.hpp"

#include "SurfaceElevationProvider.hpp"

#include "Geodetic3D.hpp"

class ShapePendingEffect;
class GPUProgramState;

class Shape : public SurfaceElevationListener, EffectTarget{
private:
  Geodetic3D* _position;
  AltitudeMode _altitudeMode;

  Angle*      _heading;
  Angle*      _pitch;

  double      _scaleX;
  double      _scaleY;
  double      _scaleZ;

//  const Planet* _planet;

  mutable MutableMatrix44D* _transformMatrix;
  MutableMatrix44D* createTransformMatrix(const Planet* planet) const;
  MutableMatrix44D* getTransformMatrix(const Planet* planet) const;

  std::vector<ShapePendingEffect*> _pendingEffects;

  bool _enable;

  mutable GLState* _glState;

  SurfaceElevationProvider* _surfaceElevationProvider;
  double _surfaceElevation;

protected:
  virtual void cleanTransformMatrix();

public:
  Shape(Geodetic3D* position,
        AltitudeMode altitudeMode) :
  _position( position ),
  _altitudeMode(altitudeMode),
  _heading( new Angle(Angle::zero()) ),
  _pitch( new Angle(Angle::zero()) ),
  _scaleX(1),
  _scaleY(1),
  _scaleZ(1),
  _transformMatrix(NULL),
  _enable(true),
  _surfaceElevation(0),
  _glState(new GLState())
  {

  }

  virtual ~Shape();

  const Geodetic3D getPosition() const {
    return *_position;
  }

  const Angle getHeading() const {
    return *_heading;
  }

  const Angle getPitch() const {
    return *_pitch;
  }

  void setPosition(Geodetic3D* position,
                   AltitudeMode altitudeMode) {
    delete _position;
    _position = position;
    _altitudeMode = altitudeMode;
    cleanTransformMatrix();
  }

  void setPosition(Geodetic3D* position) {
    delete _position;
    _position = position;
    cleanTransformMatrix();
  }

  void addShapeEffect(Effect* effect);

  void setAnimatedPosition(const TimeInterval& duration,
                           const Geodetic3D& position,
                           bool linearInterpolation=false);

  void setAnimatedPosition(const TimeInterval& duration,
                           const Geodetic3D& position,
                           const Angle& pitch,
                           const Angle& heading,
                           bool linearInterpolation=false);

  void setAnimatedPosition(const Geodetic3D& position,
                           bool linearInterpolation=false) {
    setAnimatedPosition(TimeInterval::fromSeconds(3),
                        position,
                        linearInterpolation);
  }

  void setHeading(const Angle& heading) {
    delete _heading;
    _heading = new Angle(heading);
    cleanTransformMatrix();
  }

  void setPitch(const Angle& pitch) {
    delete _pitch;
    _pitch = new Angle(pitch);
    cleanTransformMatrix();
  }

  void setScale(double scale) {
    setScale(scale, scale, scale);
  }

  void setScale(double scaleX,
                double scaleY,
                double scaleZ) {
    _scaleX = scaleX;
    _scaleY = scaleY;
    _scaleZ = scaleZ;
    cleanTransformMatrix();
  }

  void setScale(const Vector3D& scale) {
    setScale(scale._x,
             scale._y,
             scale._z);
  }

  Vector3D getScale() const {
    return Vector3D(_scaleX,
                    _scaleY,
                    _scaleZ);
  }

  void setAnimatedScale(const TimeInterval& duration,
                        double scaleX,
                        double scaleY,
                        double scaleZ);

  void setAnimatedScale(double scaleX,
                        double scaleY,
                        double scaleZ) {
    setAnimatedScale(TimeInterval::fromSeconds(1),
                     scaleX, scaleY, scaleZ);
  }

  void setAnimatedScale(const Vector3D& scale) {
    setAnimatedScale(scale._x,
                     scale._y,
                     scale._z);
  }

  void setAnimatedScale(const TimeInterval& duration,
                        const Vector3D& scale) {
    setAnimatedScale(duration,
                     scale._x,
                     scale._y,
                     scale._z);
  }

  void orbitCamera(const TimeInterval& duration,
                   double fromDistance,       double toDistance,
                   const Angle& fromAzimuth,  const Angle& toAzimuth,
                   const Angle& fromAltitude, const Angle& toAltitude);

  bool isEnable() const {
    return _enable;
  }

  void setEnable(bool enable) {
    _enable = enable;
  }

  void render(const G3MRenderContext* rc,
              GLState* parentState,
              bool renderNotReadyShapes);

  virtual void initialize(const G3MContext* context) {

    _surfaceElevationProvider = context->getSurfaceElevationProvider();
    if (_surfaceElevationProvider != NULL) {
      _surfaceElevationProvider->addListener(_position->_latitude,
                                             _position->_longitude,
                                             this);
    }

  }

  virtual bool isReadyToRender(const G3MRenderContext* rc) = 0;

  virtual void rawRender(const G3MRenderContext* rc,
                         GLState* parentGLState,
                         bool renderNotReadyShapes) = 0;

  virtual bool isTransparent(const G3MRenderContext* rc) = 0;

  void elevationChanged(const Geodetic2D& position,
                        double rawElevation,            //Without considering vertical exaggeration
                        double verticalExaggeration);

  void elevationChanged(const Sector& position,
                   const ElevationData* rawElevationData, //Without considering vertical exaggeration
                        double verticalExaggeration){}

};

#endif
<|endoftext|>