<commit_before>#include <sndfile.h>
#include <iostream>
#include <string>
#include <cmath>
#include <vector>

float calculateRMS(float *data, long long samples) {
    float mean = 0.0;
    for (long long i = 0; i<samples; i++) {
        float square = pow(data[i], 2.0);
        mean += square;
    }
    mean = pow(mean / (float)samples, 0.5);
    return mean;
}

float VtoDB(float v) {
    return 20.0f * log10(v);
}

float DBtoV(float db) {
    return pow(10.0, db / 20.0);
}

struct gainPoint {
    float gain;
    sf_count_t position;
};

int main(void) {
    std::string filename = "input.wav";
    int blockSize = 1024;
    float minDb = -45;
    float targetDb = -20;
    int windowSize = 20;
    bool limiter = true;
    float limiterRelease = 0.0006; // dB per sample
    float limiterAttack = 1024; // number of samples

    SF_INFO info;
    info.format = 0;
    SNDFILE* infile = sf_open(filename.c_str(), SFM_READ, &info);

    if (!infile) {
        std::cout << "Error opening file: " << sf_strerror(NULL) << std::endl;
        return 1;
    }

    // the file was opened, let's calculate some RMS!
    std::cout << "Calculating RMS values..." << std::endl;
    std::vector<float> rmsBlocks;
    sf_count_t frames;
    float *data = new float[blockSize * info.channels];
    do {
        frames = sf_readf_float(infile, data, blockSize);
        //std::cout << samples << std::endl;
        float rms = calculateRMS(data, frames * info.channels);
        float rmsDb = VtoDB(rms);
        rmsBlocks.push_back(rmsDb);
    } while (frames == blockSize);
    std::cout << rmsBlocks.size() << " RMS blocks calculated." << std::endl;
    delete[] data;

    // use a ring buffer to calculate a moving average over the RMS blocks
    int ringBufferSize = windowSize * 2 + 1;
    float ringBuffer[ringBufferSize];
    for (int i=0; i<ringBufferSize; i++) {
        ringBuffer[i] = -1000.0;
    }
    int ringBufferPos = 0;
    std::vector<float>::size_type currentBlock = 0;
    // start filling the ring buffer
    for (int i=0; i<windowSize; i++) {
        if (currentBlock < rmsBlocks.size()) {
            ringBuffer[ringBufferPos] = rmsBlocks[currentBlock];
        } else {
            ringBuffer[ringBufferPos] = -1000.0;
        }
        currentBlock++;
        ringBufferPos++;
    }
    // go through all of our blocks
    std::cout << "Calculating gain points..." << std::endl;
    std::vector<gainPoint> gainPoints;
    int minAverageBlocks = windowSize * 1.5;
    for (std::vector<float>::size_type i=0; i<rmsBlocks.size(); i++) {
        if (currentBlock < rmsBlocks.size()) {
            ringBuffer[ringBufferPos] = rmsBlocks[currentBlock];
        } else {
            ringBuffer[ringBufferPos] = -1000.0;
        }
        currentBlock++;
        ringBufferPos++;
        if (ringBufferPos >= ringBufferSize) ringBufferPos = 0;
        // calculate the average RMS if we have enough blocks that aren't silent
        int numBlocks = 0;
        float rms = 0;
        for (int j=0; j<ringBufferSize; j++) {
            if (ringBuffer[j] > minDb) {
                numBlocks++;
                rms += ringBuffer[j];
            }
        }
        if (numBlocks > minAverageBlocks) {
            rms = rms / (float)numBlocks;
            float gain = targetDb - rms;
            gainPoint gp;
            gp.gain = gain;
            gp.position = (i * blockSize) + (blockSize / 2);
            gainPoints.push_back(gp);
        }
    }
    std::cout << gainPoints.size() << " gain points calculated." << std::endl;
    if (gainPoints.size() == 0) {
        std::cout << "Error: no gain points found, nothing to do." << std::endl;
        sf_close(infile);
        return 1;
    }

    SF_INFO outinfo;
    outinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
    outinfo.samplerate = info.samplerate;
    outinfo.channels = info.channels;
    SNDFILE *outfile = sf_open("output.wav", SFM_WRITE, &outinfo);

    if (!outfile) {
        std::cout << "Error opening file: " << sf_strerror(NULL) << std::endl;
        sf_close(infile);
        return 1;
    }

    // now we go through the file and apply the gain!
    float limiterGain = 0.0;
    std::cout << "Applying gain..." << std::endl;
    int processSize = 1024;
    if (limiter && limiterAttack > processSize) processSize = limiterAttack;
    data = new float[processSize * info.channels];
    float *oldData = new float[processSize * info.channels];
    sf_count_t oldFrames;
    sf_seek(infile, 0, SEEK_SET);
    sf_count_t currentFrame = 0;
    sf_count_t clipped = 0;
    int currentPerc = 0;
    int blockNum = 0;
    int totalBlocks = info.frames / processSize;
    gainPoint firstGainPoint = gainPoints[0];
    gainPoint lastGainPoint = gainPoints[gainPoints.size() - 1];
    int currentGainPointNumber = 0;
    gainPoint currentGainPoint = firstGainPoint;
    gainPoint nextGainPoint;
    if (gainPoints.size() > 1) nextGainPoint = gainPoints[1];
    do {
        // flip the buffers and read new data
        float *temp = oldData;
        data = oldData;
        oldData = temp;
        oldFrames = frames;
        frames = sf_readf_float(infile, data, processSize);
        for (sf_count_t i=0; i<frames; i++) {
            // calculate the gain
            float gain = 0.0;
            if (currentFrame <= firstGainPoint.position) {
                gain = firstGainPoint.gain;
            } else if (currentFrame >= lastGainPoint.position) {
                gain = lastGainPoint.gain;
            } else {
                // interpolate between gain points
                if (currentFrame >= nextGainPoint.position) {
                    currentGainPointNumber++;
                    currentGainPoint = gainPoints[currentGainPointNumber];
                    nextGainPoint = gainPoints[currentGainPointNumber + 1];
                }
                float pos = (float)(currentFrame - currentGainPoint.position) / (float)(nextGainPoint.position - currentGainPoint.position);
                gain = ((1.0f - pos) * currentGainPoint.gain) + (pos * nextGainPoint.gain);
            }
            //float gain = interpolateGain(gainPoints, currentFrame);
            if (limiter) gain += limiterGain;
            float gainMult = DBtoV(gain);
            // apply the gain
            float highestValue = 0.0;
            for (int j=0; j<info.channels; j++) {
                float sample = data[i * info.channels + j];
                sample = sample * gainMult;
                if (!limiter && sample > 1.0) clipped++;
                if (sample > highestValue) highestValue = sample;
                data[i * info.channels + j] = sample;
            }
            if (highestValue > 1.0 && limiter) {
                // kick the limiter in
                highestValue += .001;
                float additionalLimiterGain = -VtoDB(highestValue);
                limiterGain += additionalLimiterGain;
                // and drop the attack frames down
                for (int attack=0; attack<limiterAttack; attack++) {
                    int frame = i - attack;
                    float gain = additionalLimiterGain * ((float)(limiterAttack - attack) / (float)limiterAttack);
                    float mult = DBtoV(gain);
                    if (frame >= 0) {
                        for (int j=0; j<info.channels; j++) {
                            data[frame * info.channels + j] *= mult;
                        }
                    } else {
                        int oldFrame = frame + oldFrames;
                        for (int j=0; j<info.channels; j++) {
                            oldData[oldFrame * info.channels + j] *= mult;
                        }
                    }
                }
                // and drop our current frame down
                for (int j=0; j<info.channels; j++) {
                    data[i * info.channels + j] /= highestValue;
                }

            }
            currentFrame++;
            limiterGain += limiterRelease;
            if (limiterGain > 0) limiterGain = 0;
        }
        // write the frames to the new file
        if (blockNum > 0) sf_writef_float(outfile, oldData, oldFrames);
        blockNum++;
        if (totalBlocks > 0) {
            int thisPerc = (blockNum * 100) / totalBlocks;
            if (thisPerc > currentPerc) {
                currentPerc = thisPerc;
                std::cout << currentPerc << "% done" << std::endl;
            }
        }
    } while (frames == processSize);
    sf_writef_float(outfile, data, frames);
    if (clipped) std::cout << "WARNING: " << clipped << " samples clipped and limiter disabled" << std::endl;

    sf_close(infile);
    sf_close(outfile);

    return 0;
}
<commit_msg>added command line options<commit_after>#include <sndfile.h>
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

float calculateRMS(float *data, long long samples) {
    float mean = 0.0;
    for (long long i = 0; i<samples; i++) {
        float square = pow(data[i], 2.0);
        mean += square;
    }
    mean = pow(mean / (float)samples, 0.5);
    return mean;
}

float VtoDB(float v) {
    return 20.0f * log10(v);
}

float DBtoV(float db) {
    return pow(10.0, db / 20.0);
}

struct gainPoint {
    float gain;
    sf_count_t position;
};

int main(int argc, char **argv) {
    std::string inputFilename = "";
    std::string outputFilename = "";
    int blockSize = 1024;
    float minDb = -45;
    float targetDb = -20;
    int windowSize = 20;
    bool limiter = true;
    float limiterRelease = 0.0006;
    int limiterAttack = 1024;

    po::options_description prettyDesc("Options"); // this version doesn't include the positional arguments
    prettyDesc.add_options()
        ("help", "Show this help information")
        ("target,t", po::value<float>(&targetDb)->required(), "Set target dB level")
        ("silence,s", po::value<float>(&minDb)->default_value(-45.0), "Minimum dB value for audio content, anything below this is considered silence.")
        ("window,w", po::value<int>(&windowSize)->default_value(20), "Window size for smoothing volume changes.")
        ("block-size", po::value<int>(&blockSize)->default_value(1024), "Block size for calculating RMS values.")
        ("limiter-attack", po::value<int>(&limiterAttack)->default_value(1024), "Limiter attack time in samples.")
        ("limiter-release", po::value<float>(&limiterRelease)->default_value(0.0006), "Limiter release time in dB/sample.")
        ("limiter-disable", "Disable the limiter completely - may cause clipping.")
    ;
    po::options_description desc("Options"); // this one is actually used to parse, don't use required()
    desc.add_options()
        ("help", "Show this help information")
        ("input-file", po::value<std::string>(&inputFilename))
        ("output-file", po::value<std::string>(&outputFilename))
        ("target,t", po::value<float>(&targetDb), "Set target dB level")
        ("silence,s", po::value<float>(&minDb)->default_value(-45.0), "Minimum dB value for audio content, anything below this is considered silence.")
        ("window,w", po::value<int>(&windowSize)->default_value(20), "Window size for smoothing volume changes.")
        ("block-size", po::value<int>(&blockSize)->default_value(1024), "Block size for calculating RMS values.")
        ("limiter-attack", po::value<int>(&limiterAttack)->default_value(1024), "Limiter attack time in samples.")
        ("limiter-release", po::value<float>(&limiterRelease)->default_value(0.0006), "Limiter release time in dB/sample.")
        ("disable-limiter", "Disable the limiter completely - may cause clipping.")
    ;
    po::positional_options_description p;
    p.add("input-file", 1).add("output-file", 1);

    po::variables_map vm;
    try {
        po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
        po::notify(vm);
    } catch(std::exception& e) {
        std::cout << "Error: " << e.what() << std::endl;
        return 1;
    }

    if (vm.count("help")) {
        std::cout << "Usage: " << argv[0] << " input.wav output.wav OPTIONS" << std::endl << std::endl;
        std::cout << prettyDesc << std::endl;
        return 1;
    }

    // do we have the required values?
    if (!vm.count("input-file") || !vm.count("output-file")) {
        std::cout << "The input and output filenames are required." << std::endl;
        return 1;
    }
    if (!vm.count("target")) {
        std::cout << "The target dB level (-t, --target)is required." << std::endl;
        return 1;
    }
    if (vm.count("disable-limiter")) {
        limiter = false;
    }
    // check that everything's within a valid range
    if (blockSize < 32) {
        std::cout << "Block size must be >= 32." << std::endl;
        return 1;
    }
    if (minDb >= 0) {
        std::cout << "Silence level must be < 0 dB." << std::endl;
        return 1;
    }
    if (targetDb >= 0) {
        std::cout << "Target level must be < 0 dB." << std::endl;
        return 1;
    }
    if (windowSize < 1) {
        std::cout << "Window size must be >= 1." << std::endl;
        return 1;
    }
    if (limiterRelease <= 0) {
        std::cout << "Limiter release must be > 0." << std::endl;
        return 1;
    }
    if (limiterAttack < 1) {
        std::cout << "Limiter attack must be > 0." << std::endl;
        return 1;
    }

    SF_INFO info;
    info.format = 0;
    SNDFILE* infile = sf_open(inputFilename.c_str(), SFM_READ, &info);

    if (!infile) {
        std::cout << "Error opening file: " << sf_strerror(NULL) << std::endl;
        return 1;
    }

    // the file was opened, let's calculate some RMS!
    std::cout << "Calculating RMS values..." << std::endl;
    std::vector<float> rmsBlocks;
    sf_count_t frames;
    float *data = new float[blockSize * info.channels];
    do {
        frames = sf_readf_float(infile, data, blockSize);
        //std::cout << samples << std::endl;
        float rms = calculateRMS(data, frames * info.channels);
        float rmsDb = VtoDB(rms);
        rmsBlocks.push_back(rmsDb);
    } while (frames == blockSize);
    std::cout << rmsBlocks.size() << " RMS blocks calculated." << std::endl;
    delete[] data;

    // use a ring buffer to calculate a moving average over the RMS blocks
    int ringBufferSize = windowSize * 2 + 1;
    float ringBuffer[ringBufferSize];
    for (int i=0; i<ringBufferSize; i++) {
        ringBuffer[i] = -1000.0;
    }
    int ringBufferPos = 0;
    std::vector<float>::size_type currentBlock = 0;
    // start filling the ring buffer
    for (int i=0; i<windowSize; i++) {
        if (currentBlock < rmsBlocks.size()) {
            ringBuffer[ringBufferPos] = rmsBlocks[currentBlock];
        } else {
            ringBuffer[ringBufferPos] = -1000.0;
        }
        currentBlock++;
        ringBufferPos++;
    }
    // go through all of our blocks
    std::cout << "Calculating gain points..." << std::endl;
    std::vector<gainPoint> gainPoints;
    int minAverageBlocks = windowSize * 1.5;
    for (std::vector<float>::size_type i=0; i<rmsBlocks.size(); i++) {
        if (currentBlock < rmsBlocks.size()) {
            ringBuffer[ringBufferPos] = rmsBlocks[currentBlock];
        } else {
            ringBuffer[ringBufferPos] = -1000.0;
        }
        currentBlock++;
        ringBufferPos++;
        if (ringBufferPos >= ringBufferSize) ringBufferPos = 0;
        // calculate the average RMS if we have enough blocks that aren't silent
        int numBlocks = 0;
        float rms = 0;
        for (int j=0; j<ringBufferSize; j++) {
            if (ringBuffer[j] > minDb) {
                numBlocks++;
                rms += ringBuffer[j];
            }
        }
        if (numBlocks > minAverageBlocks) {
            rms = rms / (float)numBlocks;
            float gain = targetDb - rms;
            gainPoint gp;
            gp.gain = gain;
            gp.position = (i * blockSize) + (blockSize / 2);
            gainPoints.push_back(gp);
        }
    }
    std::cout << gainPoints.size() << " gain points calculated." << std::endl;
    if (gainPoints.size() == 0) {
        std::cout << "Error: no gain points found, nothing to do." << std::endl;
        sf_close(infile);
        return 1;
    }

    SF_INFO outinfo;
    outinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
    outinfo.samplerate = info.samplerate;
    outinfo.channels = info.channels;
    SNDFILE *outfile = sf_open(outputFilename.c_str(), SFM_WRITE, &outinfo);

    if (!outfile) {
        std::cout << "Error opening file: " << sf_strerror(NULL) << std::endl;
        sf_close(infile);
        return 1;
    }

    // now we go through the file and apply the gain!
    float limiterGain = 0.0;
    std::cout << "Applying gain..." << std::endl;
    int processSize = 1024;
    if (limiter && limiterAttack > processSize) processSize = limiterAttack;
    data = new float[processSize * info.channels];
    float *oldData = new float[processSize * info.channels];
    sf_count_t oldFrames;
    sf_seek(infile, 0, SEEK_SET);
    sf_count_t currentFrame = 0;
    sf_count_t clipped = 0;
    int currentPerc = 0;
    int blockNum = 0;
    int totalBlocks = info.frames / processSize;
    gainPoint firstGainPoint = gainPoints[0];
    gainPoint lastGainPoint = gainPoints[gainPoints.size() - 1];
    int currentGainPointNumber = 0;
    gainPoint currentGainPoint = firstGainPoint;
    gainPoint nextGainPoint;
    if (gainPoints.size() > 1) nextGainPoint = gainPoints[1];
    do {
        // flip the buffers and read new data
        float *temp = oldData;
        data = oldData;
        oldData = temp;
        oldFrames = frames;
        frames = sf_readf_float(infile, data, processSize);
        for (sf_count_t i=0; i<frames; i++) {
            // calculate the gain
            float gain = 0.0;
            if (currentFrame <= firstGainPoint.position) {
                gain = firstGainPoint.gain;
            } else if (currentFrame >= lastGainPoint.position) {
                gain = lastGainPoint.gain;
            } else {
                // interpolate between gain points
                if (currentFrame >= nextGainPoint.position) {
                    currentGainPointNumber++;
                    currentGainPoint = gainPoints[currentGainPointNumber];
                    nextGainPoint = gainPoints[currentGainPointNumber + 1];
                }
                float pos = (float)(currentFrame - currentGainPoint.position) / (float)(nextGainPoint.position - currentGainPoint.position);
                gain = ((1.0f - pos) * currentGainPoint.gain) + (pos * nextGainPoint.gain);
            }
            //float gain = interpolateGain(gainPoints, currentFrame);
            if (limiter) gain += limiterGain;
            float gainMult = DBtoV(gain);
            // apply the gain
            float highestValue = 0.0;
            for (int j=0; j<info.channels; j++) {
                float sample = data[i * info.channels + j];
                sample = sample * gainMult;
                if (!limiter && sample > 1.0) clipped++;
                if (sample > highestValue) highestValue = sample;
                data[i * info.channels + j] = sample;
            }
            if (highestValue > 1.0 && limiter) {
                // kick the limiter in
                highestValue += .001;
                float additionalLimiterGain = -VtoDB(highestValue);
                limiterGain += additionalLimiterGain;
                // and drop the attack frames down
                for (int attack=0; attack<limiterAttack; attack++) {
                    int frame = i - attack;
                    float gain = additionalLimiterGain * ((float)(limiterAttack - attack) / (float)limiterAttack);
                    float mult = DBtoV(gain);
                    if (frame >= 0) {
                        for (int j=0; j<info.channels; j++) {
                            data[frame * info.channels + j] *= mult;
                        }
                    } else {
                        int oldFrame = frame + oldFrames;
                        for (int j=0; j<info.channels; j++) {
                            oldData[oldFrame * info.channels + j] *= mult;
                        }
                    }
                }
                // and drop our current frame down
                for (int j=0; j<info.channels; j++) {
                    data[i * info.channels + j] /= highestValue;
                }

            }
            currentFrame++;
            limiterGain += limiterRelease;
            if (limiterGain > 0) limiterGain = 0;
        }
        // write the frames to the new file
        if (blockNum > 0) sf_writef_float(outfile, oldData, oldFrames);
        blockNum++;
        if (totalBlocks > 0) {
            int thisPerc = (blockNum * 100) / totalBlocks;
            if (thisPerc > currentPerc) {
                currentPerc = thisPerc;
                std::cout << currentPerc << "% done" << std::endl;
            }
        }
    } while (frames == processSize);
    sf_writef_float(outfile, data, frames);
    if (clipped) std::cout << "WARNING: " << clipped << " samples clipped and limiter disabled" << std::endl;

    sf_close(infile);
    sf_close(outfile);

    return 0;
}
<|endoftext|>


<commit_before>#include "stdafx.h"

/**
\mainpage
This is the documentation for this ESIEA student projet : Gite repository on github
*/

//Includes
#include <Annwvyn.h>

#include "LeapIntegration.hpp"
#include "LeapVisualizer.hpp"
#include "DebugGUI.hpp"
#include <string>

#include "GrabableObject.hpp"
#include "ObjectSpawner.hpp"
#include "HandObject.hpp"

#include "LevelManager.hpp"
#include "Demo0.hpp"
#include "Demo1.hpp"
#include "Demo2.hpp"

//Namespaces
using namespace std;
using namespace Annwvyn; //All Annwvyn components are here

///Debuging tool
class LevelManagerListener : LISTENER
{
public:
	LevelManagerListener(AnnPlayer* p, LevelManager* levelManager) : constructListener(p),
		lm(levelManager)
	{}

	void KeyEvent(AnnKeyEvent e)
	{
		if(e.isPressed())
		{
			if(e.getKey() == Annwvyn::KeyCode::enter)
				lm->unloadCurrentLevel();
			if(e.getKey() == Annwvyn::KeyCode::back)
				lm->jumpToFirstLevel();
			if(e.getKey() == Annwvyn::KeyCode::one)
				lm->jump(level_id(0));
			if(e.getKey() == Annwvyn::KeyCode::two)
				lm->jump(level_id(1));
			if(e.getKey() == Annwvyn::KeyCode::three)
				lm->jump(level_id(2));
		}
	}

	void MouseEvent(AnnMouseEvent e){}
	void StickEvent(AnnStickEvent e){}

private:
	LevelManager* lm;
};

AnnMain()
{
	AnnEngine::openConsole();
	new AnnEngine("My Game", false);

	AnnEngine::Instance()->loadDir("GUI");
	AnnEngine::Instance()->loadDir("media/sky");
	AnnEngine::Instance()->loadDir("media/example");
	AnnEngine::Instance()->loadDir("media/bureau");
	AnnEngine::Instance()->initResources();

	AnnEngine::Instance()->oculusInit();

	AnnEngine::Instance()->initPlayerPhysics();

	AnnLeapInterface leap;
	LeapLoggerListener* l = new LeapLoggerListener();
	HandObject* leftHand = (HandObject*) AnnEngine::Instance()->createGameObject("hand.left.mesh", new HandObject);
	leftHand->setType("left");
	leftHand->registerListener(l);
	HandObject* rightHand = (HandObject*) AnnEngine::Instance()->createGameObject("hand.right.mesh", new HandObject);
	rightHand->setType("right");
	rightHand->registerListener(l);
	LeapVisualizer visualizer;
	visualizer.setInterfarce(leap.getPointer());
	visualizer.setHandsObjects(leftHand, rightHand);

	//for midrendering
	leftHand->setVisualizerAddress(visualizer.getPointer());

	LevelManager* lm = new LevelManager;

	lm->addLevel(new Demo0);
	lm->addLevel(new Demo1);
	lm->addLevel(new Demo2);

	lm->jumpToFirstLevel();

	AnnEngine::Instance()->useDefaultEventListener();
	AnnEngine::Instance()->getEventManager()->addListener(new LevelManagerListener(AnnEngine::Instance()->getPlayer(), lm));

	AnnEngine::Instance()->resetOculusOrientation();
	AnnEngine::Instance()->openDebugWindow();
	do
	{
		lm->step();
	}while(AnnEngine::Instance()->refresh());

	delete lm;
	delete AnnEngine::Instance();
	return 0;
}
<commit_msg>switch engine to fullscreen at startup<commit_after>#include "stdafx.h"

/**
\mainpage
This is the documentation for this ESIEA student projet : Gite repository on github
*/

//Includes
#include <Annwvyn.h>

#include "LeapIntegration.hpp"
#include "LeapVisualizer.hpp"
#include "DebugGUI.hpp"
#include <string>

#include "GrabableObject.hpp"
#include "ObjectSpawner.hpp"
#include "HandObject.hpp"

#include "LevelManager.hpp"
#include "Demo0.hpp"
#include "Demo1.hpp"
#include "Demo2.hpp"

//Namespaces
using namespace std;
using namespace Annwvyn; //All Annwvyn components are here

///Debuging tool
class LevelManagerListener : LISTENER
{
public:
	LevelManagerListener(AnnPlayer* p, LevelManager* levelManager) : constructListener(p),
		lm(levelManager)
	{}

	void KeyEvent(AnnKeyEvent e)
	{
		if(e.isPressed())
		{
			if(e.getKey() == Annwvyn::KeyCode::enter)
				lm->unloadCurrentLevel();
			if(e.getKey() == Annwvyn::KeyCode::back)
				lm->jumpToFirstLevel();
			if(e.getKey() == Annwvyn::KeyCode::one)
				lm->jump(level_id(0));
			if(e.getKey() == Annwvyn::KeyCode::two)
				lm->jump(level_id(1));
			if(e.getKey() == Annwvyn::KeyCode::three)
				lm->jump(level_id(2));
		}
	}

	void MouseEvent(AnnMouseEvent e){}
	void StickEvent(AnnStickEvent e){}

private:
	LevelManager* lm;
};

AnnMain()
{
	AnnEngine::openConsole();
	new AnnEngine("My Game");

	AnnEngine::Instance()->loadDir("GUI");
	AnnEngine::Instance()->loadDir("media/sky");
	AnnEngine::Instance()->loadDir("media/example");
	AnnEngine::Instance()->loadDir("media/bureau");
	AnnEngine::Instance()->initResources();

	AnnEngine::Instance()->oculusInit();

	AnnEngine::Instance()->initPlayerPhysics();

	AnnLeapInterface leap;
	LeapLoggerListener* l = new LeapLoggerListener();
	HandObject* leftHand = (HandObject*) AnnEngine::Instance()->createGameObject("hand.left.mesh", new HandObject);
	leftHand->setType("left");
	leftHand->registerListener(l);
	HandObject* rightHand = (HandObject*) AnnEngine::Instance()->createGameObject("hand.right.mesh", new HandObject);
	rightHand->setType("right");
	rightHand->registerListener(l);
	LeapVisualizer visualizer;
	visualizer.setInterfarce(leap.getPointer());
	visualizer.setHandsObjects(leftHand, rightHand);

	//for midrendering
	leftHand->setVisualizerAddress(visualizer.getPointer());

	LevelManager* lm = new LevelManager;

	lm->addLevel(new Demo0);
	lm->addLevel(new Demo1);
	lm->addLevel(new Demo2);

	lm->jumpToFirstLevel();

	AnnEngine::Instance()->useDefaultEventListener();
	AnnEngine::Instance()->getEventManager()->addListener(new LevelManagerListener(AnnEngine::Instance()->getPlayer(), lm));

	AnnEngine::Instance()->resetOculusOrientation();
	AnnEngine::Instance()->openDebugWindow();
	do
	{
		lm->step();
	}while(AnnEngine::Instance()->refresh());

	delete lm;
	delete AnnEngine::Instance();
	return 0;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2010, Pieter Beyens
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Text_Editor.H>
#include <FL/Fl_Text_Buffer.H>
#include <FL/Fl_Button.H>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <signal.h>
#include <argp.h>

#include "flgoban.h"
#include "sgf.h"
#include "goban.h"

using namespace std;

static Fl_Double_Window *win = NULL;
static Fl_Goban *flgoban = NULL;
//static Fl_Text_Buffer *textbuffer = NULL;
//static Fl_Text_Editor *comment = NULL;
static list<int> fds;
static struct goban *g = NULL;
static char cx_prev = -1, cy_prev = -1;
static char broadcast_msg[10000];

struct settings
{
	int width, height, port, nogui, repeat;
};
static struct settings setts;

static void handler_sigpipe(int)
{
	return;
}

static void broadcast(const char *cmd)
{
	list<int>::const_iterator cit = fds.begin();
	while(cit!=fds.end()) {
		send(*cit, cmd, strlen(cmd),0);
		++cit;
	}
	printf("%s",cmd);
}

static void read_cb(int fd, void *data)
{
	int n;
	char rd_cmd[10000];
	memset(rd_cmd, '\0', sizeof(rd_cmd));
	memset(broadcast_msg, '\0', sizeof(rd_cmd));
	n = read(fd, rd_cmd, sizeof(rd_cmd));
	if(n <= 0) {
		Fl::remove_fd(fd);
		fds.remove(fd);
		/* if not a gui and not listening then exit */
		if(setts.nogui && !setts.port && !fds.size())
			exit(0);
		return;
	}
	//printf("Received: %s\n",rd_cmd);
	sgf_parse_fast(rd_cmd);
	broadcast(broadcast_msg);
	flgoban->redraw();
}

static void listen_cb(int fd, void *s)
{
	int a = accept(*(int*)s, NULL, 0);
	if(0 > a)
		perror("accept()");
	else {
		Fl::add_fd(a, read_cb, NULL);
		fds.push_back(a);
	}
}

/* GOBAN */
static void goban_ab(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,black);
	if(!setts.repeat) {
		sprintf(msg, "AB[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static void goban_aw(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,white);
	if(!setts.repeat) {
		sprintf(msg, "AW[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static void goban_ae(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,empty);
	if(!setts.repeat) {
		sprintf(msg, "AE[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static const struct goban_cb gcb = { goban_ab, goban_aw, goban_ae };

/* SGF */
static void sgf_node(void)
{
	strcat(broadcast_msg, ";\n");
}

static void sgf_sz(int s)
{
	char msg[10];
	goban_free(g);
	g = goban_alloc(s, &gcb);
	flgoban->flresize(s);
	cx_prev = -1, cy_prev = -1;
	sprintf(msg, "SZ[%d]", s);
	strcat(broadcast_msg, msg);
}

static void sgf_b(char cx, char cy)
{
	char msg[20];
	if(cx_prev!=-1) {
		flgoban->set_mark(sgf2int(cx_prev),sgf2int(cy_prev),empty);
		if(!setts.repeat) {
			sprintf(msg, "ME[%c%c]", cx_prev,cy_prev);
			strcat(broadcast_msg, msg);
		}
	}
	goban_play(g, sgf2int(cx), sgf2int(cy), black);
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),circle);

	if(setts.repeat) {
		sprintf(msg, "B[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
	else {
		sprintf(msg, "CR[%c%c]", cx, cy);
		strcat(broadcast_msg, msg);
	}

	cx_prev = cx;
	cy_prev = cy;
}

static void sgf_w(char cx, char cy)
{
	char msg[20];
	if(cx_prev!=-1) {
		flgoban->set_mark(sgf2int(cx_prev),sgf2int(cy_prev),empty);
		if(!setts.repeat) {
			sprintf(msg, "ME[%c%c]", cx_prev,cy_prev);
			strcat(broadcast_msg, msg);
		}
	}

	goban_play(g, sgf2int(cx), sgf2int(cy), white);
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),circle);

	if(setts.repeat) {
		sprintf(msg, "W[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
	else {
		sprintf(msg, "CR[%c%c]", cx, cy);
		strcat(broadcast_msg, msg);
	}

	cx_prev = cx;
	cy_prev = cy;
}

static void sgf_ab(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), black);
	if(setts.repeat) {
		sprintf(msg, "AB[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_aw(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), white);
	if(setts.repeat) {
		sprintf(msg, "AW[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_ae(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), empty);
	if(setts.repeat) {
		sprintf(msg, "AE[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static const struct sgf_cb scb = { sgf_node, sgf_sz, sgf_b, sgf_w, sgf_ab, sgf_aw, sgf_ae };

/* EVENTS */

static void ev_key(char k)
{
	char e[100];
	sprintf(e, "KEY[%c];\n", k);
	broadcast(e);
}

/* ARGP */
const char *argp_program_version = "flgoban 0.1";
const char *argp_program_bug_address = "<pieter.beyens@gmail.com>";
static char doc[] = "flgoban -- reads, displays and broadcasts sgf";
static char args_doc[] = "";
static struct argp_option options[] = {
	{"width", 'w', "WIDTH", 0, "window width (defaults to 800)" },
	{"height", 'h', "HEIGHT", 0, "window height (defaults to 800)" },
	{"port", 'p', "PORT", 0, "listening port (if set to zero then only read from stdin - defaults to 5000)" },
	{"nogui",'g', 0, 0, "text-only interface (reads and broadcasts sgf)"},
	{"repeat",'r', 0, 0, "do not expand sgf, just repeat it"},
	{ 0 }
};
static error_t parse_opt (int key, char *arg, struct argp_state *state)
{
	switch (key)
	{
		case 'w':
			if(!arg || 1!=sscanf(arg, "%d", &setts.width)) {
				perror("width must be an integer");
				exit(1);
			}
			break;
		case 'h':
			if(!arg || 1!=sscanf(arg, "%d", &setts.height)) {
				perror("height must be an integer");
				exit(1);
			}
			break;
		case 'p':
			if(!arg || 1!=sscanf(arg, "%d", &setts.port)) {
				perror("port must be an integer");
				exit(1);
			}
			break;
		case 'g':
			setts.nogui = 1;
			break;
		case 'r':
			setts.repeat = 1;
			break;
		default:
			return ARGP_ERR_UNKNOWN;
	}
	return 0;
}
static struct argp argp = { options, parse_opt, args_doc, doc };

int main(int argc, char **argv) {
	int s;
	struct sockaddr_in addr;

	memset(&setts,'\0', sizeof(setts));
	setts.width = 600;
	setts.height = 600;
	setts.port = 5000;

	argp_parse (&argp, argc, argv, 0, 0, 0);

	if(setts.port) {
		s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(s < 0) {
			perror("socket()");
			return -1;
		}

		bzero(&addr, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = htonl(INADDR_ANY);
		addr.sin_port = htons(setts.port);

		int tr=1;
		if (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int)) == -1) {
			perror("setsockopt");
			exit(1);
		}

		if(0 > bind(s,(struct sockaddr*)&addr,sizeof(addr))) {
			perror("bind()");
			return -1;
		}

		if(0 > listen(s,1)) {
			perror("listen()");
			return -1;
		}
		Fl::add_fd(s, listen_cb, &s);
	}

	Fl::add_fd(STDIN_FILENO, read_cb, NULL);

	win = new Fl_Double_Window(setts.width,setts.height);
	win->begin();
	flgoban = new Fl_Goban(0,0,setts.width,setts.height, ev_key);
	//textbuffer = new Fl_Text_Buffer();
	//comment = new Fl_Text_Editor(10,650,WINDOW_WIDTH-20,90,0);
	//comment->buffer(textbuffer);
	win->end();
	win->resizable(flgoban);
	if(!setts.nogui)
		win->show(argc, argv);

	g = goban_alloc(19, &gcb);
	sgf_init(&scb);

	signal(SIGPIPE,handler_sigpipe);

	if(setts.nogui)
		while(1)
			Fl::check();
	else
		Fl::run();

	if(setts.port)
		close(s);
	goban_free(g);
}
<commit_msg>bug fix: fltk window is shown without argc/argv<commit_after>/*
Copyright (c) 2010, Pieter Beyens
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Text_Editor.H>
#include <FL/Fl_Text_Buffer.H>
#include <FL/Fl_Button.H>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <signal.h>
#include <argp.h>

#include "flgoban.h"
#include "sgf.h"
#include "goban.h"

using namespace std;

static Fl_Double_Window *win = NULL;
static Fl_Goban *flgoban = NULL;
//static Fl_Text_Buffer *textbuffer = NULL;
//static Fl_Text_Editor *comment = NULL;
static list<int> fds;
static struct goban *g = NULL;
static char cx_prev = -1, cy_prev = -1;
static char broadcast_msg[10000];

struct settings
{
	int width, height, port, nogui, repeat;
};
static struct settings setts;

static void handler_sigpipe(int)
{
	return;
}

static void broadcast(const char *cmd)
{
	list<int>::const_iterator cit = fds.begin();
	while(cit!=fds.end()) {
		send(*cit, cmd, strlen(cmd),0);
		++cit;
	}
	printf("%s",cmd);
}

static void read_cb(int fd, void *data)
{
	int n;
	char rd_cmd[10000];
	memset(rd_cmd, '\0', sizeof(rd_cmd));
	memset(broadcast_msg, '\0', sizeof(rd_cmd));
	n = read(fd, rd_cmd, sizeof(rd_cmd));
	if(n <= 0) {
		Fl::remove_fd(fd);
		fds.remove(fd);
		/* if not a gui and not listening then exit */
		if(setts.nogui && !setts.port && !fds.size())
			exit(0);
		return;
	}
	//printf("Received: %s\n",rd_cmd);
	sgf_parse_fast(rd_cmd);
	broadcast(broadcast_msg);
	flgoban->redraw();
}

static void listen_cb(int fd, void *s)
{
	int a = accept(*(int*)s, NULL, 0);
	if(0 > a)
		perror("accept()");
	else {
		Fl::add_fd(a, read_cb, NULL);
		fds.push_back(a);
	}
}

/* GOBAN */
static void goban_ab(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,black);
	if(!setts.repeat) {
		sprintf(msg, "AB[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static void goban_aw(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,white);
	if(!setts.repeat) {
		sprintf(msg, "AW[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static void goban_ae(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,empty);
	if(!setts.repeat) {
		sprintf(msg, "AE[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static const struct goban_cb gcb = { goban_ab, goban_aw, goban_ae };

/* SGF */
static void sgf_node(void)
{
	strcat(broadcast_msg, ";\n");
}

static void sgf_sz(int s)
{
	char msg[10];
	goban_free(g);
	g = goban_alloc(s, &gcb);
	flgoban->flresize(s);
	cx_prev = -1, cy_prev = -1;
	sprintf(msg, "SZ[%d]", s);
	strcat(broadcast_msg, msg);
}

static void sgf_b(char cx, char cy)
{
	char msg[20];
	if(cx_prev!=-1) {
		flgoban->set_mark(sgf2int(cx_prev),sgf2int(cy_prev),empty);
		if(!setts.repeat) {
			sprintf(msg, "ME[%c%c]", cx_prev,cy_prev);
			strcat(broadcast_msg, msg);
		}
	}
	goban_play(g, sgf2int(cx), sgf2int(cy), black);
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),circle);

	if(setts.repeat) {
		sprintf(msg, "B[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
	else {
		sprintf(msg, "CR[%c%c]", cx, cy);
		strcat(broadcast_msg, msg);
	}

	cx_prev = cx;
	cy_prev = cy;
}

static void sgf_w(char cx, char cy)
{
	char msg[20];
	if(cx_prev!=-1) {
		flgoban->set_mark(sgf2int(cx_prev),sgf2int(cy_prev),empty);
		if(!setts.repeat) {
			sprintf(msg, "ME[%c%c]", cx_prev,cy_prev);
			strcat(broadcast_msg, msg);
		}
	}

	goban_play(g, sgf2int(cx), sgf2int(cy), white);
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),circle);

	if(setts.repeat) {
		sprintf(msg, "W[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
	else {
		sprintf(msg, "CR[%c%c]", cx, cy);
		strcat(broadcast_msg, msg);
	}

	cx_prev = cx;
	cy_prev = cy;
}

static void sgf_ab(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), black);
	if(setts.repeat) {
		sprintf(msg, "AB[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_aw(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), white);
	if(setts.repeat) {
		sprintf(msg, "AW[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_ae(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), empty);
	if(setts.repeat) {
		sprintf(msg, "AE[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static const struct sgf_cb scb = { sgf_node, sgf_sz, sgf_b, sgf_w, sgf_ab, sgf_aw, sgf_ae };

/* EVENTS */

static void ev_key(char k)
{
	char e[100];
	sprintf(e, "KEY[%c];\n", k);
	broadcast(e);
}

/* ARGP */
const char *argp_program_version = "flgoban 0.1";
const char *argp_program_bug_address = "<pieter.beyens@gmail.com>";
static char doc[] = "flgoban -- reads, displays and broadcasts sgf";
static char args_doc[] = "";
static struct argp_option options[] = {
	{"width", 'w', "WIDTH", 0, "window width (defaults to 600)" },
	{"height", 'h', "HEIGHT", 0, "window height (defaults to 600)" },
	{"port", 'p', "PORT", 0, "listening port (if set to zero then only read from stdin - defaults to 5000)" },
	{"nogui",'g', 0, 0, "text-only interface (reads and broadcasts sgf)"},
	{"repeat",'r', 0, 0, "do not expand sgf, just repeat it"},
	{ 0 }
};
static error_t parse_opt (int key, char *arg, struct argp_state *state)
{
	switch (key)
	{
		case 'w':
			if(!arg || 1!=sscanf(arg, "%d", &setts.width)) {
				perror("width must be an integer");
				exit(1);
			}
			break;
		case 'h':
			if(!arg || 1!=sscanf(arg, "%d", &setts.height)) {
				perror("height must be an integer");
				exit(1);
			}
			break;
		case 'p':
			if(!arg || 1!=sscanf(arg, "%d", &setts.port)) {
				perror("port must be an integer");
				exit(1);
			}
			break;
		case 'g':
			setts.nogui = 1;
			break;
		case 'r':
			setts.repeat = 1;
			break;
		default:
			return ARGP_ERR_UNKNOWN;
	}
	return 0;
}
static struct argp argp = { options, parse_opt, args_doc, doc };

int main(int argc, char **argv) {
	int s;
	struct sockaddr_in addr;

	memset(&setts,'\0', sizeof(setts));
	setts.width = 600;
	setts.height = 600;
	setts.port = 5000;

	argp_parse (&argp, argc, argv, 0, 0, 0);

	if(setts.port) {
		s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(s < 0) {
			perror("socket()");
			return -1;
		}

		bzero(&addr, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = htonl(INADDR_ANY);
		addr.sin_port = htons(setts.port);

		int tr=1;
		if (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int)) == -1) {
			perror("setsockopt");
			exit(1);
		}

		if(0 > bind(s,(struct sockaddr*)&addr,sizeof(addr))) {
			perror("bind()");
			return -1;
		}

		if(0 > listen(s,1)) {
			perror("listen()");
			return -1;
		}
		Fl::add_fd(s, listen_cb, &s);
	}

	Fl::add_fd(STDIN_FILENO, read_cb, NULL);

	win = new Fl_Double_Window(setts.width,setts.height);
	win->begin();
	flgoban = new Fl_Goban(0,0,setts.width,setts.height, ev_key);
	//textbuffer = new Fl_Text_Buffer();
	//comment = new Fl_Text_Editor(10,650,WINDOW_WIDTH-20,90,0);
	//comment->buffer(textbuffer);
	win->end();
	win->resizable(flgoban);
	if(!setts.nogui)
		win->show();

	g = goban_alloc(19, &gcb);
	sgf_init(&scb);

	signal(SIGPIPE,handler_sigpipe);

	if(setts.nogui)
		while(1)
			Fl::check();
	else
		Fl::run();

	if(setts.port)
		close(s);
	goban_free(g);
}
<|endoftext|>


<commit_before>struct index {
	long long start;
	long long end;
	unsigned long long index;
	short segment;
	short t : 2;
	unsigned long long seq : (64 - 18);  // pack with segment and t to stay in 32 bytes
};

void checkdisk(struct reader *r, int nreader);

extern int geometry_scale;
extern int quiet;

extern int CPUS;
extern int TEMP_FILES;
<commit_msg>Fix structure packing to fix polygon dropping<commit_after>struct index {
	long long start;
	long long end;
	unsigned long long index;
	short segment;
	unsigned short t : 2;
	unsigned long long seq : (64 - 18);  // pack with segment and t to stay in 32 bytes
};

void checkdisk(struct reader *r, int nreader);

extern int geometry_scale;
extern int quiet;

extern int CPUS;
extern int TEMP_FILES;
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * @author David N. Bertoni
 */
#include "XSLTProcessorEnvSupportDefault.hpp"

#include <algorithm>

#include <util/XMLURL.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/STLHelper.hpp>

#include <XPath/ElementPrefixResolverProxy.hpp>
#include <XPath/XPathExecutionContext.hpp>

#include <XMLSupport/XMLParserLiaison.hpp>

#include "KeyTable.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTProcessor.hpp"
#include "XSLTInputSource.hpp"

XSLTProcessorEnvSupportDefault::XSLTProcessorEnvSupportDefault(XSLTProcessor*	theProcessor) :
	XSLTProcessorEnvSupport(),
	m_defaultSupport(),
	m_processor(theProcessor),
	m_keyTables(),
	m_xlocatorTable()
{
}

XSLTProcessorEnvSupportDefault::~XSLTProcessorEnvSupportDefault()
{
	reset();
}

void
XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName,
			const Function&			function)
{
	XPathEnvSupportDefault::installExternalFunctionGlobal(theNamespace, extensionName, function);
}

void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionGlobal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName)
{
	XPathEnvSupportDefault::uninstallExternalFunctionGlobal(theNamespace, extensionName);
}

void
XSLTProcessorEnvSupportDefault::installExternalFunctionLocal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName,
			const Function&			function)
{
	m_defaultSupport.installExternalFunctionLocal(theNamespace, extensionName, function);
}

void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionLocal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName)
{
	m_defaultSupport.uninstallExternalFunctionLocal(theNamespace, extensionName);
}

void
XSLTProcessorEnvSupportDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::for_each;
#endif

	// Clean up the key table vector
	for_each(m_keyTables.begin(),
			 m_keyTables.end(),
			 makeMapValueDeleteFunctor(m_keyTables));

	m_keyTables.clear();

	m_xlocatorTable.clear();
}

KeyTable*
XSLTProcessorEnvSupportDefault::getKeyTable(const XalanNode*	doc) const
{
	const KeyTablesTableType::const_iterator		i =
					m_keyTables.find(doc);

	if (i == m_keyTables.end())
	{
		return 0;
	}
	else
	{
		return i->second;
	}
}

void
XSLTProcessorEnvSupportDefault::setKeyTable(
			KeyTable*			keytable,
			const XalanNode*	doc)
{
	// Get rid of any existing keytable
	delete m_keyTables[doc];

	m_keyTables[doc] = keytable;
}

const NodeRefListBase*
XSLTProcessorEnvSupportDefault::getNodeSetByKey(
			const XalanNode&		doc,
			const XalanDOMString&	name,
			const XalanDOMString&	ref,
			const PrefixResolver&	resolver,
			XPathExecutionContext&	executionContext) const
{
	if (m_processor == 0)
	{
		return m_defaultSupport.getNodeSetByKey(doc,
											    name,
												ref,
												resolver,
												executionContext);
	}
	else
	{
		const NodeRefListBase*	nl = 0;

		const Stylesheet* const		theStylesheet =
			m_processor->getStylesheetRoot();

		if (theStylesheet != 0)
		{
			// $$$ ToDo: Figure out this const stuff!!!
			nl = theStylesheet->getNodeSetByKey(&const_cast<XalanNode&>(doc),
												name,
												ref,
												resolver,
												executionContext,
#if defined(XALAN_NO_MUTABLE)
												(KeysTableType&)m_keyTables);
#else
												m_keyTables);
#endif
		}

		if(0 == nl)
		{
			m_processor->error(XalanDOMString("There is no xsl:key declaration for '") + name + XalanDOMString("'!"));
		}

		return nl;
	}
}

XObject*
XSLTProcessorEnvSupportDefault::getVariable(
			XObjectFactory&		factory,
			const QName&		name) const
{
	if (m_processor == 0)
	{
		return m_defaultSupport.getVariable(factory,
											name);
	}
	else
	{
		return m_processor->getVariable(name);
	}
}

XalanDocument*
XSLTProcessorEnvSupportDefault::parseXML(
		const XalanDOMString&	urlString,
		const XalanDOMString&	base)
{
	if (m_processor == 0)
	{
		return m_defaultSupport.parseXML(urlString, base);
	}
	else
	{
		XMLParserLiaison& parserLiaison = m_processor->getXMLParserLiaison();

		const XMLURL		xslURL(c_wstr(base), c_wstr(urlString));

		const XMLCh* const	urlText = xslURL.getURLText();

		XSLTInputSource		inputSource(urlText);

		XalanDocument*		theDocument =
			parserLiaison.parseXMLStream(inputSource);

		setSourceDocument(urlText, theDocument);

		return theDocument;
	}
}

XalanDocument*
XSLTProcessorEnvSupportDefault::getSourceDocument(const XalanDOMString&		theURI) const
{
	return m_defaultSupport.getSourceDocument(theURI);
}

void
XSLTProcessorEnvSupportDefault::setSourceDocument(
			const XalanDOMString&	theURI,
			XalanDocument*			theDocument)
{
	m_defaultSupport.setSourceDocument(theURI, theDocument);
}

XalanDOMString
XSLTProcessorEnvSupportDefault::findURIFromDoc(const XalanDocument*		owner) const
{
	return m_defaultSupport.findURIFromDoc(owner);
}

XalanDocument*
XSLTProcessorEnvSupportDefault::getDOMFactory() const
{
	if (m_processor == 0)
	{
		return m_defaultSupport.getDOMFactory();
	}
	else
	{
		return m_processor->getDOMFactory();
	}
}

bool
XSLTProcessorEnvSupportDefault::elementAvailable(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName) const
{
	return m_defaultSupport.elementAvailable(theNamespace,
											 extensionName);
}

bool
XSLTProcessorEnvSupportDefault::functionAvailable(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName) const
{
	return m_defaultSupport.functionAvailable(theNamespace,
											  extensionName);
}

XObject*
XSLTProcessorEnvSupportDefault::extFunction(
			XPathExecutionContext&			executionContext,
			const XalanDOMString&			theNamespace,
			const XalanDOMString&			extensionName,
			XalanNode*						context,
			const XObjectArgVectorType&		argVec) const
{
	return m_defaultSupport.extFunction(executionContext,
										theNamespace,
										extensionName,
										context,
										argVec);
}

XLocator*
XSLTProcessorEnvSupportDefault::getXLocatorFromNode(const XalanNode*	node) const
{
	const XLocatorTableType::const_iterator		i =
					m_xlocatorTable.find(node);

	if (i == m_xlocatorTable.end())
	{
		return 0;
	}
	else
	{
		return i->second;
	}
}

void
XSLTProcessorEnvSupportDefault::associateXLocatorToNode(
			const XalanNode*	node,
			XLocator*			xlocator)
{
	m_xlocatorTable[node] = xlocator;
}

bool
XSLTProcessorEnvSupportDefault::shouldStripSourceNode(const XalanNode&	node) const
{
	if (m_processor == 0)
	{
		return m_defaultSupport.shouldStripSourceNode(node);
	}
	else
	{
		return m_processor->shouldStripSourceNode(node);
	}
}

bool
XSLTProcessorEnvSupportDefault::problem(
			eSource					where,
			eClassification			classification,
			const XalanNode*		styleNode,
			const XalanNode*		sourceNode,
			const XalanDOMString&	msg,
			int						lineNo,
			int						charOffset) const
{
	return m_defaultSupport.problem(where,
									classification,
									styleNode,
									sourceNode,
									msg,
									lineNo,
									charOffset);
}

bool
XSLTProcessorEnvSupportDefault::problem(
			eSource					where,
			eClassification			classification,
			const PrefixResolver*	resolver,
			const XalanNode*		sourceNode,
			const XalanDOMString&	msg,
			int						lineNo,
			int						charOffset) const
{
	return m_defaultSupport.problem(where,
									classification,
									resolver,
									sourceNode,
									msg,
									lineNo,
									charOffset);
}
<commit_msg>Added some special-case code for URL handling.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * @author David N. Bertoni
 */
#include "XSLTProcessorEnvSupportDefault.hpp"

#include <algorithm>

#include <util/XMLURL.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/STLHelper.hpp>

#include <XPath/ElementPrefixResolverProxy.hpp>
#include <XPath/XPathExecutionContext.hpp>

#include <XMLSupport/XMLParserLiaison.hpp>

#include "KeyTable.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTProcessor.hpp"
#include "XSLTInputSource.hpp"

XSLTProcessorEnvSupportDefault::XSLTProcessorEnvSupportDefault(XSLTProcessor*	theProcessor) :
	XSLTProcessorEnvSupport(),
	m_defaultSupport(),
	m_processor(theProcessor),
	m_keyTables(),
	m_xlocatorTable()
{
}

XSLTProcessorEnvSupportDefault::~XSLTProcessorEnvSupportDefault()
{
	reset();
}

void
XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName,
			const Function&			function)
{
	XPathEnvSupportDefault::installExternalFunctionGlobal(theNamespace, extensionName, function);
}

void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionGlobal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName)
{
	XPathEnvSupportDefault::uninstallExternalFunctionGlobal(theNamespace, extensionName);
}

void
XSLTProcessorEnvSupportDefault::installExternalFunctionLocal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName,
			const Function&			function)
{
	m_defaultSupport.installExternalFunctionLocal(theNamespace, extensionName, function);
}

void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionLocal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName)
{
	m_defaultSupport.uninstallExternalFunctionLocal(theNamespace, extensionName);
}

void
XSLTProcessorEnvSupportDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::for_each;
#endif

	// Clean up the key table vector
	for_each(m_keyTables.begin(),
			 m_keyTables.end(),
			 makeMapValueDeleteFunctor(m_keyTables));

	m_keyTables.clear();

	m_xlocatorTable.clear();
}

KeyTable*
XSLTProcessorEnvSupportDefault::getKeyTable(const XalanNode*	doc) const
{
	const KeyTablesTableType::const_iterator		i =
					m_keyTables.find(doc);

	if (i == m_keyTables.end())
	{
		return 0;
	}
	else
	{
		return i->second;
	}
}

void
XSLTProcessorEnvSupportDefault::setKeyTable(
			KeyTable*			keytable,
			const XalanNode*	doc)
{
	// Get rid of any existing keytable
	delete m_keyTables[doc];

	m_keyTables[doc] = keytable;
}

const NodeRefListBase*
XSLTProcessorEnvSupportDefault::getNodeSetByKey(
			const XalanNode&		doc,
			const XalanDOMString&	name,
			const XalanDOMString&	ref,
			const PrefixResolver&	resolver,
			XPathExecutionContext&	executionContext) const
{
	if (m_processor == 0)
	{
		return m_defaultSupport.getNodeSetByKey(doc,
											    name,
												ref,
												resolver,
												executionContext);
	}
	else
	{
		const NodeRefListBase*	nl = 0;

		const Stylesheet* const		theStylesheet =
			m_processor->getStylesheetRoot();

		if (theStylesheet != 0)
		{
			// $$$ ToDo: Figure out this const stuff!!!
			nl = theStylesheet->getNodeSetByKey(&const_cast<XalanNode&>(doc),
												name,
												ref,
												resolver,
												executionContext,
#if defined(XALAN_NO_MUTABLE)
												(KeysTableType&)m_keyTables);
#else
												m_keyTables);
#endif
		}

		if(0 == nl)
		{
			m_processor->error(XalanDOMString("There is no xsl:key declaration for '") + name + XalanDOMString("'!"));
		}

		return nl;
	}
}

XObject*
XSLTProcessorEnvSupportDefault::getVariable(
			XObjectFactory&		factory,
			const QName&		name) const
{
	if (m_processor == 0)
	{
		return m_defaultSupport.getVariable(factory,
											name);
	}
	else
	{
		return m_processor->getVariable(name);
	}
}

XalanDocument*
XSLTProcessorEnvSupportDefault::parseXML(
		const XalanDOMString&	urlString,
		const XalanDOMString&	base)
{
	if (m_processor == 0)
	{
		return m_defaultSupport.parseXML(urlString, base);
	}
	else
	{
		XMLParserLiaison&	parserLiaison =
			m_processor->getXMLParserLiaison();

		// $$$ ToDo: we should re-work this code to only use
		// XMLRUL when necessary.
		XMLURL	xslURL;

		// This is a work-around for what I believe is a bug in the
		// Xerces URL code.  If a base identifier ends in a slash,
		// they chop of characters back to the _previous_ slash.
		// So, for instance, a base of "/foo/foo/foo/" and a
		// urlString of file.xml would become /foo/foo/file.xml,
		// instead of /foo/foo/foo/file.xml.
		const unsigned int	indexOfSlash = lastIndexOf(base, '/');

		if (indexOfSlash == length(base) - 1)
		{
			xslURL.setURL(c_wstr(base + urlString));
		}
		else
		{
			xslURL.setURL(c_wstr(base), c_wstr(urlString));
		}

		const XMLCh* const	urlText = xslURL.getURLText();

		XSLTInputSource		inputSource(urlText);

		XalanDocument*		theDocument =
			parserLiaison.parseXMLStream(inputSource);

		setSourceDocument(urlText, theDocument);

		return theDocument;
	}
}

XalanDocument*
XSLTProcessorEnvSupportDefault::getSourceDocument(const XalanDOMString&		theURI) const
{
	return m_defaultSupport.getSourceDocument(theURI);
}

void
XSLTProcessorEnvSupportDefault::setSourceDocument(
			const XalanDOMString&	theURI,
			XalanDocument*			theDocument)
{
	m_defaultSupport.setSourceDocument(theURI, theDocument);
}

XalanDOMString
XSLTProcessorEnvSupportDefault::findURIFromDoc(const XalanDocument*		owner) const
{
	return m_defaultSupport.findURIFromDoc(owner);
}

XalanDocument*
XSLTProcessorEnvSupportDefault::getDOMFactory() const
{
	if (m_processor == 0)
	{
		return m_defaultSupport.getDOMFactory();
	}
	else
	{
		return m_processor->getDOMFactory();
	}
}

bool
XSLTProcessorEnvSupportDefault::elementAvailable(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName) const
{
	return m_defaultSupport.elementAvailable(theNamespace,
											 extensionName);
}

bool
XSLTProcessorEnvSupportDefault::functionAvailable(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	extensionName) const
{
	return m_defaultSupport.functionAvailable(theNamespace,
											  extensionName);
}

XObject*
XSLTProcessorEnvSupportDefault::extFunction(
			XPathExecutionContext&			executionContext,
			const XalanDOMString&			theNamespace,
			const XalanDOMString&			extensionName,
			XalanNode*						context,
			const XObjectArgVectorType&		argVec) const
{
	return m_defaultSupport.extFunction(executionContext,
										theNamespace,
										extensionName,
										context,
										argVec);
}

XLocator*
XSLTProcessorEnvSupportDefault::getXLocatorFromNode(const XalanNode*	node) const
{
	const XLocatorTableType::const_iterator		i =
					m_xlocatorTable.find(node);

	if (i == m_xlocatorTable.end())
	{
		return 0;
	}
	else
	{
		return i->second;
	}
}

void
XSLTProcessorEnvSupportDefault::associateXLocatorToNode(
			const XalanNode*	node,
			XLocator*			xlocator)
{
	m_xlocatorTable[node] = xlocator;
}

bool
XSLTProcessorEnvSupportDefault::shouldStripSourceNode(const XalanNode&	node) const
{
	if (m_processor == 0)
	{
		return m_defaultSupport.shouldStripSourceNode(node);
	}
	else
	{
		return m_processor->shouldStripSourceNode(node);
	}
}

bool
XSLTProcessorEnvSupportDefault::problem(
			eSource					where,
			eClassification			classification,
			const XalanNode*		styleNode,
			const XalanNode*		sourceNode,
			const XalanDOMString&	msg,
			int						lineNo,
			int						charOffset) const
{
	return m_defaultSupport.problem(where,
									classification,
									styleNode,
									sourceNode,
									msg,
									lineNo,
									charOffset);
}

bool
XSLTProcessorEnvSupportDefault::problem(
			eSource					where,
			eClassification			classification,
			const PrefixResolver*	resolver,
			const XalanNode*		sourceNode,
			const XalanDOMString&	msg,
			int						lineNo,
			int						charOffset) const
{
	return m_defaultSupport.problem(where,
									classification,
									resolver,
									sourceNode,
									msg,
									lineNo,
									charOffset);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006-2013  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia 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 (FSF), either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include "tonalextractor.h"
#include "algorithmfactory.h"
#include "poolstorage.h"

using namespace std;

namespace essentia {
namespace streaming {

const char* TonalExtractor::name = "TonalExtractor";
const char* TonalExtractor::description = DOC("This algorithm extracts tonal features");

TonalExtractor::TonalExtractor(): _frameCutter(0), _windowing(0), _spectrum(0), _spectralPeaks(0),
                                  _hpcpKey(0), _hpcpChord(0), _hpcpTuning(0), _key(0),
                                  _chordsDescriptors(0), _chordsDetection(0) {

  declareInput(_signal, "signal", "the input audio signal");

  declareOutput(_chordsChangesRate, "chords_changes_rate", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsHistogram, "chords_histogram", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsKey, "chords_key", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsNumberRate, "chords_number_rate", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsProgression, "chords_progression", "See ChordsDetection algorithm documentation");
  declareOutput(_chordsScale, "chords_scale", "See ChordsDetection algorithm documentation");
  declareOutput(_chordsStrength, "chords_strength", "See ChordsDetection algorithm documentation");
  declareOutput(_hpcps, "hpcp", "See HPCP algorithm documentation");
  declareOutput(_hpcpsTuning, "hpcp_highres", "See HPCP algorithm documentation");
  declareOutput(_keyKey, "key_key", "See Key algorithm documentation");
  declareOutput(_keyScale, "key_scale", "See Key algorithm documentation");
  declareOutput(_keyStrength, "key_strength", "See Key algorithm documentation");

  createInnerNetwork();
}

void TonalExtractor::createInnerNetwork() {
  AlgorithmFactory& factory = AlgorithmFactory::instance();

  _chordsDescriptors = factory.create("ChordsDescriptors");
  _chordsDetection   = factory.create("ChordsDetection");
  _key               = factory.create("Key");
  _spectralPeaks     = factory.create("SpectralPeaks",
                                      "orderBy", "magnitude", "magnitudeThreshold", 1e-05,
                                      "minFrequency", 40, "maxFrequency", 5000, "maxPeaks", 10000);

  _frameCutter       = factory.create("FrameCutter");
  _spectrum          = factory.create("Spectrum");
  _windowing         = factory.create("Windowing", "type", "blackmanharris62");
  _hpcpKey           = factory.create("HPCP");
  _hpcpChord         = factory.create("HPCP");
  _hpcpTuning        = factory.create("HPCP");

  _signal                                >>  _frameCutter->input("signal");

  _frameCutter->output("frame")          >>  _windowing->input("frame");
  _hpcpKey->output("hpcp")               >>  _key->input("pcp");
  _hpcpChord->output("hpcp")             >>  _chordsDetection->input("pcp");
  _chordsDetection->output("chords")     >>  _chordsDescriptors->input("chords");
  _key->output("key")                    >>  _chordsDescriptors->input("key");
  _key->output("scale")                  >>  _chordsDescriptors->input("scale");
  _spectralPeaks->output("magnitudes")   >>  _hpcpKey->input("magnitudes");
  _spectralPeaks->output("magnitudes")   >>  _hpcpChord->input("magnitudes");
  _spectralPeaks->output("magnitudes")   >>  _hpcpTuning->input("magnitudes");
  _spectralPeaks->output("frequencies")  >>  _hpcpKey->input("frequencies");
  _spectralPeaks->output("frequencies")  >>  _hpcpChord->input("frequencies");
  _spectralPeaks->output("frequencies")  >>  _hpcpTuning->input("frequencies");
  _spectrum->output("spectrum")          >>  _spectralPeaks->input("spectrum");
  _windowing->output("frame")            >>  _spectrum->input("frame");

  _chordsDescriptors->output("chordsChangesRate")  >>  _chordsChangesRate;
  _chordsDescriptors->output("chordsHistogram")    >>  _chordsHistogram;
  _chordsDescriptors->output("chordsKey")          >>  _chordsKey;
  _chordsDescriptors->output("chordsNumberRate")   >>  _chordsNumberRate;
  _chordsDetection->output("chords")               >>  _chordsProgression ;
  _chordsDescriptors->output("chordsScale")        >>  _chordsScale;
  _chordsDetection->output("strength")             >>  _chordsStrength;
  _hpcpKey->output("hpcp")                         >>  _hpcps;
  _hpcpTuning->output("hpcp")                      >>  _hpcpsTuning;
  _key->output("key")                              >>  _keyKey ;
  _key->output("scale")                            >>  _keyScale;
  _key->output("strength")                         >>  _keyStrength;

  _network = new scheduler::Network(_frameCutter);
}

void TonalExtractor::configure() {
  int frameSize = parameter("frameSize").toInt();
  int hopSize = parameter("hopSize").toInt();
  Real tuningFrequency = parameter("tuningFrequency").toReal();

  _frameCutter->configure("frameSize", frameSize,
                          "hopSize", hopSize,
                          "silentFrames", "noise");

  _hpcpKey->configure("referenceFrequency", tuningFrequency,
                      "minFrequency", 40.0,
                      "nonLinear", false,
                      "maxFrequency", 5000.0,
                      "bandPreset", false,
                      "windowSize", 1.33333333333,
                      "weightType", "squaredCosine",
                      "size", 36);

  _hpcpChord->configure("referenceFrequency", tuningFrequency,
                        "minFrequency", 40.0,
                        "nonLinear", true,
                        "splitFrequency", 500.0,
                        "maxFrequency", 5000.0,
                        "bandPreset", true,
                        "windowSize", 0.5,
                        "weightType", "cosine",
                        "harmonics", 8,
                        "size", 36);

  _hpcpTuning->configure("referenceFrequency", tuningFrequency,
                         "minFrequency", 40.0,
                         "nonLinear", true,
                         "splitFrequency", 500.0,
                         "maxFrequency", 5000.0,
                         "bandPreset", true,
                         "windowSize", 0.5,
                         "weightType", "cosine",
                         "harmonics", 8,
                         "size", 120);
}

TonalExtractor::~TonalExtractor() {
  delete _network;
}

} // namespace streaming
} // namespace essentia

namespace essentia {
namespace standard {

const char* TonalExtractor::name = "TonalExtractor";
const char* TonalExtractor::description = DOC("this algorithm extracts tonal features");

TonalExtractor::TonalExtractor() {
  declareInput(_signal, "signal", "the audio input signal");

  declareOutput(_chordsChangesRate, "chords_changes_rate", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsHistogram, "chords_histogram", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsKey, "chords_key", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsNumberRate, "chords_number_rate", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chords, "chords_progression", "See ChordsDetection algorithm documentation");
  declareOutput(_chordsScale, "chords_scale", "See ChordsDetection algorithm documentation");
  declareOutput(_chordsStrength, "chords_strength", "See ChordsDetection algorithm documentation");
  declareOutput(_hpcp, "hpcp", "See HPCP algorithm documentation");
  declareOutput(_hpcpHighRes, "hpcp_highres", "See HPCP algorithm documentation");
  declareOutput(_key, "key_key", "See Key algorithm documentation");
  declareOutput(_scale, "key_scale", "See Key algorithm documentation");
  declareOutput(_keyStrength, "key_strength", "See Key algorithm documentation");

  createInnerNetwork();
}

TonalExtractor::~TonalExtractor() {
  delete _network;
}

void TonalExtractor::reset() {
  _network->reset();
}

void TonalExtractor::configure() {
  _tonalExtractor->configure(INHERIT("frameSize"), INHERIT("hopSize"), INHERIT("tuningFrequency"));
}

void TonalExtractor::createInnerNetwork() {
  _tonalExtractor = streaming::AlgorithmFactory::create("TonalExtractor");
  _vectorInput = new streaming::VectorInput<Real>();

  *_vectorInput  >>  _tonalExtractor->input("signal");

  _tonalExtractor->output("chords_changes_rate")  >>  PC(_pool, "chordsChangesRate");
  _tonalExtractor->output("chords_histogram")     >>  PC(_pool, "chordsHistogram");
  _tonalExtractor->output("chords_key")           >>  PC(_pool, "chordsKey");
  _tonalExtractor->output("chords_number_rate")   >>  PC(_pool, "chordsNumberRate");
  _tonalExtractor->output("chords_progression")   >>  PC(_pool, "chords");
  _tonalExtractor->output("chords_scale")         >>  PC(_pool, "chordsScale");
  _tonalExtractor->output("chords_strength")      >>  PC(_pool, "chordsStrength");
  _tonalExtractor->output("hpcp")                 >>  PC(_pool, "hpcp");
  _tonalExtractor->output("hpcp_highres")         >>  PC(_pool, "hpcpHighRes");
  _tonalExtractor->output("key_key")              >>  PC(_pool, "key");
  _tonalExtractor->output("key_scale")            >>  PC(_pool, "scale");
  _tonalExtractor->output("key_strength")         >>  PC(_pool, "keyStrength");

  _network = new scheduler::Network(_vectorInput);
}

void TonalExtractor::compute() {
  const vector<Real>& signal = _signal.get();
  _vectorInput->setVector(&signal);

  _network->run();

  vector<Real> &            chordsHistogram   = _chordsHistogram.get();
  Real &                    chordsChangesRate = _chordsChangesRate.get();
  string &                  chordsKey         = _chordsKey.get();
  Real &                    chordsNumberRate  = _chordsNumberRate.get();
  vector<string> &          chords            = _chords.get();
  string &                  chordsScale       = _chordsScale.get();
  vector<Real> &            chordsStrength    = _chordsStrength.get();
  vector<vector<Real> > &   hpcp              = _hpcp.get();
  vector<vector<Real> > &   hpcpHighRes       = _hpcpHighRes.get();
  string &                  key               = _key.get();
  string &                  scale             = _scale.get();
  Real &                    keyStrength       = _keyStrength.get();

  chordsHistogram   = _pool.value<vector<Real> > ("chordsHistogram");
  chordsChangesRate = _pool.value<Real> ("chordsChangesRate");
  chordsKey         = _pool.value<string> ("chordsKey");
  chordsNumberRate  = _pool.value<Real> ("chordsNumberRate");
  chords            = _pool.value<vector<string> > ("chords");
  chordsScale       = _pool.value<string> ("chordsScale");
  chordsStrength    = _pool.value<vector<Real> > ("chordsStrength");
  hpcp              = _pool.value<vector<vector<Real> > > ("hpcp");
  hpcpHighRes       = _pool.value<vector<vector<Real> > > ("hpcpHighRes");
  key               = _pool.value<string> ("key");
  scale             = _pool.value<string> ("scale");
  keyStrength       = _pool.value<Real> ("keyStrength");
}

} // namespace standard
} // namespace essentia
<commit_msg>Improve code readability<commit_after>/*
 * Copyright (C) 2006-2013  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia 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 (FSF), either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include "tonalextractor.h"
#include "algorithmfactory.h"
#include "poolstorage.h"

using namespace std;

namespace essentia {
namespace streaming {

const char* TonalExtractor::name = "TonalExtractor";
const char* TonalExtractor::description = DOC("This algorithm extracts tonal features");

TonalExtractor::TonalExtractor(): _frameCutter(0), _windowing(0), _spectrum(0), _spectralPeaks(0),
                                  _hpcpKey(0), _hpcpChord(0), _hpcpTuning(0), _key(0),
                                  _chordsDescriptors(0), _chordsDetection(0) {

  declareInput(_signal, "signal", "the input audio signal");

  declareOutput(_chordsChangesRate, "chords_changes_rate", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsHistogram, "chords_histogram", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsKey, "chords_key", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsNumberRate, "chords_number_rate", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsProgression, "chords_progression", "See ChordsDetection algorithm documentation");
  declareOutput(_chordsScale, "chords_scale", "See ChordsDetection algorithm documentation");
  declareOutput(_chordsStrength, "chords_strength", "See ChordsDetection algorithm documentation");
  declareOutput(_hpcps, "hpcp", "See HPCP algorithm documentation");
  declareOutput(_hpcpsTuning, "hpcp_highres", "See HPCP algorithm documentation");
  declareOutput(_keyKey, "key_key", "See Key algorithm documentation");
  declareOutput(_keyScale, "key_scale", "See Key algorithm documentation");
  declareOutput(_keyStrength, "key_strength", "See Key algorithm documentation");

  createInnerNetwork();
}

void TonalExtractor::createInnerNetwork() {
  AlgorithmFactory& factory = AlgorithmFactory::instance();

  _chordsDescriptors = factory.create("ChordsDescriptors");
  _chordsDetection   = factory.create("ChordsDetection");
  _key               = factory.create("Key");
  _spectralPeaks     = factory.create("SpectralPeaks",
                                      "orderBy", "magnitude", "magnitudeThreshold", 1e-05,
                                      "minFrequency", 40, "maxFrequency", 5000, "maxPeaks", 10000);

  _frameCutter       = factory.create("FrameCutter");
  _spectrum          = factory.create("Spectrum");
  _windowing         = factory.create("Windowing", "type", "blackmanharris62");
  _hpcpKey           = factory.create("HPCP");
  _hpcpChord         = factory.create("HPCP");
  _hpcpTuning        = factory.create("HPCP");

  _signal                                >>  _frameCutter->input("signal");
  _frameCutter->output("frame")          >>  _windowing->input("frame");
  _windowing->output("frame")            >>  _spectrum->input("frame");
  _spectrum->output("spectrum")          >>  _spectralPeaks->input("spectrum");

  _spectralPeaks->output("magnitudes")   >>  _hpcpKey->input("magnitudes");
  _spectralPeaks->output("magnitudes")   >>  _hpcpChord->input("magnitudes");
  _spectralPeaks->output("magnitudes")   >>  _hpcpTuning->input("magnitudes");
  _spectralPeaks->output("frequencies")  >>  _hpcpKey->input("frequencies");
  _spectralPeaks->output("frequencies")  >>  _hpcpChord->input("frequencies");
  _spectralPeaks->output("frequencies")  >>  _hpcpTuning->input("frequencies");

  _hpcpTuning->output("hpcp")            >>  _hpcpsTuning;

  _hpcpKey->output("hpcp")               >>  _hpcps;
  _hpcpKey->output("hpcp")               >>  _key->input("pcp");
  _key->output("key")                    >>  _keyKey ;
  _key->output("scale")                  >>  _keyScale;
  _key->output("strength")               >>  _keyStrength;

  _key->output("key")                    >>  _chordsDescriptors->input("key");
  _key->output("scale")                  >>  _chordsDescriptors->input("scale");

  _hpcpChord->output("hpcp")             >>  _chordsDetection->input("pcp");

  _chordsDetection->output("chords")     >>  _chordsProgression;
  _chordsDetection->output("strength")   >>  _chordsStrength;
  _chordsDetection->output("chords")     >>  _chordsDescriptors->input("chords");

  _chordsDescriptors->output("chordsChangesRate")  >>  _chordsChangesRate;
  _chordsDescriptors->output("chordsHistogram")    >>  _chordsHistogram;
  _chordsDescriptors->output("chordsKey")          >>  _chordsKey;
  _chordsDescriptors->output("chordsNumberRate")   >>  _chordsNumberRate;
  _chordsDescriptors->output("chordsScale")        >>  _chordsScale;

  _network = new scheduler::Network(_frameCutter);
}

void TonalExtractor::configure() {
  int frameSize = parameter("frameSize").toInt();
  int hopSize = parameter("hopSize").toInt();
  Real tuningFrequency = parameter("tuningFrequency").toReal();

  _frameCutter->configure("frameSize", frameSize,
                          "hopSize", hopSize,
                          "silentFrames", "noise");

  _hpcpKey->configure("referenceFrequency", tuningFrequency,
                      "minFrequency", 40.0,
                      "nonLinear", false,
                      "maxFrequency", 5000.0,
                      "bandPreset", false,
                      "windowSize", 1.33333333333,
                      "weightType", "squaredCosine",
                      "size", 36);

  _hpcpChord->configure("referenceFrequency", tuningFrequency,
                        "minFrequency", 40.0,
                        "nonLinear", true,
                        "splitFrequency", 500.0,
                        "maxFrequency", 5000.0,
                        "bandPreset", true,
                        "windowSize", 0.5,
                        "weightType", "cosine",
                        "harmonics", 8,
                        "size", 36);

  _hpcpTuning->configure("referenceFrequency", tuningFrequency,
                         "minFrequency", 40.0,
                         "nonLinear", true,
                         "splitFrequency", 500.0,
                         "maxFrequency", 5000.0,
                         "bandPreset", true,
                         "windowSize", 0.5,
                         "weightType", "cosine",
                         "harmonics", 8,
                         "size", 120);
}

TonalExtractor::~TonalExtractor() {
  delete _network;
}

} // namespace streaming
} // namespace essentia

namespace essentia {
namespace standard {

const char* TonalExtractor::name = "TonalExtractor";
const char* TonalExtractor::description = DOC("this algorithm extracts tonal features");

TonalExtractor::TonalExtractor() {
  declareInput(_signal, "signal", "the audio input signal");

  declareOutput(_chordsChangesRate, "chords_changes_rate", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsHistogram, "chords_histogram", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsKey, "chords_key", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chordsNumberRate, "chords_number_rate", "See ChordsDescriptors algorithm documentation");
  declareOutput(_chords, "chords_progression", "See ChordsDetection algorithm documentation");
  declareOutput(_chordsScale, "chords_scale", "See ChordsDetection algorithm documentation");
  declareOutput(_chordsStrength, "chords_strength", "See ChordsDetection algorithm documentation");
  declareOutput(_hpcp, "hpcp", "See HPCP algorithm documentation");
  declareOutput(_hpcpHighRes, "hpcp_highres", "See HPCP algorithm documentation");
  declareOutput(_key, "key_key", "See Key algorithm documentation");
  declareOutput(_scale, "key_scale", "See Key algorithm documentation");
  declareOutput(_keyStrength, "key_strength", "See Key algorithm documentation");

  createInnerNetwork();
}

TonalExtractor::~TonalExtractor() {
  delete _network;
}

void TonalExtractor::reset() {
  _network->reset();
}

void TonalExtractor::configure() {
  _tonalExtractor->configure(INHERIT("frameSize"), INHERIT("hopSize"), INHERIT("tuningFrequency"));
}

void TonalExtractor::createInnerNetwork() {
  _tonalExtractor = streaming::AlgorithmFactory::create("TonalExtractor");
  _vectorInput = new streaming::VectorInput<Real>();

  *_vectorInput  >>  _tonalExtractor->input("signal");

  _tonalExtractor->output("chords_changes_rate")  >>  PC(_pool, "chordsChangesRate");
  _tonalExtractor->output("chords_histogram")     >>  PC(_pool, "chordsHistogram");
  _tonalExtractor->output("chords_key")           >>  PC(_pool, "chordsKey");
  _tonalExtractor->output("chords_number_rate")   >>  PC(_pool, "chordsNumberRate");
  _tonalExtractor->output("chords_progression")   >>  PC(_pool, "chords");
  _tonalExtractor->output("chords_scale")         >>  PC(_pool, "chordsScale");
  _tonalExtractor->output("chords_strength")      >>  PC(_pool, "chordsStrength");
  _tonalExtractor->output("hpcp")                 >>  PC(_pool, "hpcp");
  _tonalExtractor->output("hpcp_highres")         >>  PC(_pool, "hpcpHighRes");
  _tonalExtractor->output("key_key")              >>  PC(_pool, "key");
  _tonalExtractor->output("key_scale")            >>  PC(_pool, "scale");
  _tonalExtractor->output("key_strength")         >>  PC(_pool, "keyStrength");

  _network = new scheduler::Network(_vectorInput);
}

void TonalExtractor::compute() {
  const vector<Real>& signal = _signal.get();
  _vectorInput->setVector(&signal);

  _network->run();

  vector<Real> &            chordsHistogram   = _chordsHistogram.get();
  Real &                    chordsChangesRate = _chordsChangesRate.get();
  string &                  chordsKey         = _chordsKey.get();
  Real &                    chordsNumberRate  = _chordsNumberRate.get();
  vector<string> &          chords            = _chords.get();
  string &                  chordsScale       = _chordsScale.get();
  vector<Real> &            chordsStrength    = _chordsStrength.get();
  vector<vector<Real> > &   hpcp              = _hpcp.get();
  vector<vector<Real> > &   hpcpHighRes       = _hpcpHighRes.get();
  string &                  key               = _key.get();
  string &                  scale             = _scale.get();
  Real &                    keyStrength       = _keyStrength.get();

  chordsHistogram   = _pool.value<vector<Real> > ("chordsHistogram");
  chordsChangesRate = _pool.value<Real> ("chordsChangesRate");
  chordsKey         = _pool.value<string> ("chordsKey");
  chordsNumberRate  = _pool.value<Real> ("chordsNumberRate");
  chords            = _pool.value<vector<string> > ("chords");
  chordsScale       = _pool.value<string> ("chordsScale");
  chordsStrength    = _pool.value<vector<Real> > ("chordsStrength");
  hpcp              = _pool.value<vector<vector<Real> > > ("hpcp");
  hpcpHighRes       = _pool.value<vector<vector<Real> > > ("hpcpHighRes");
  key               = _pool.value<string> ("key");
  scale             = _pool.value<string> ("scale");
  keyStrength       = _pool.value<Real> ("keyStrength");
}

} // namespace standard
} // namespace essentia
<|endoftext|>


<commit_before>/*
 * LayerOutputComponent.hpp
 *
 *  Created on: Dec 3, 2018
 *      Author: peteschultz
 */

#ifndef LAYEROUTPUTCOMPONENT_HPP_
#define LAYEROUTPUTCOMPONENT_HPP_

#include "columns/BaseObject.hpp"

#include "checkpointing/CheckpointableFileStream.hpp"
#include "components/BasePublisherComponent.hpp"
#include "utils/Timer.hpp"

namespace PV {

/**
 * A component to output a layer's activity. It creates a .pvp file whose name is the
 * component's name followed by the suffix ".pvp" in the output directory.
 * It then responds to the LayerOutputStateMessage by appending a frame to the .pvp file
 * with the current activity state (retrieved from the publisher).
 * The boolean parameter sparseLayer controls whether the layer is sparse or dense.
 */
class LayerOutputComponent : public BaseObject {
  protected:
   /**
    * List of parameters needed from the LayerOutputComponent class
    * @name HyPerLayer Parameters
    * @{
    */

   /**
    * @brief writeStep: Specifies how often to output a pvp file for this layer
    * @details Defaults to every timestep. -1 specifies not to write at all.
    */
   virtual void ioParam_writeStep(enum ParamsIOFlag ioFlag);

   /**
    * @brief initialWriteTime: Specifies the first timestep to start outputing pvp files
    */
   virtual void ioParam_initialWriteTime(enum ParamsIOFlag ioFlag);

   /** @} */ // end of LayerOutputComponent parameters

  public:
   LayerOutputComponent(char const *name, PVParams *params, Communicator const *comm);
   virtual ~LayerOutputComponent();

  protected:
   LayerOutputComponent();

   void initialize(char const *name, PVParams *params, Communicator const *comm);

   virtual void setObjectType() override;

   virtual void initMessageActionMap() override;

   virtual int ioParamsFillGroup(enum ParamsIOFlag ioFlag) override;

   virtual Response::Status
   communicateInitInfo(std::shared_ptr<CommunicateInitInfoMessage const> message) override;

   virtual void setDefaultWriteStep(std::shared_ptr<CommunicateInitInfoMessage const> message);

   virtual Response::Status
   registerData(std::shared_ptr<RegisterDataMessage<Checkpointer> const> message) override;

   Response::Status respondLayerOutputState(std::shared_ptr<LayerOutputStateMessage const> message);

   int openOutputStateFile(std::shared_ptr<RegisterDataMessage<Checkpointer> const> message);

   virtual Response::Status outputState(double simTime, double deltaTime);

   /**
    * Appends the current activity to the OutputStateStream if SparseLayer is false.
    * Called by outputState.
    */
   virtual void writeActivity(double simTime, PVLayerCube &cube);

   /**
    * Appends the current activity to the OutputStateStream if SparseLayer is true.
    * Called by outputState.
    */
   virtual void writeActivitySparse(double simTime, PVLayerCube &cube);

   void updateNBands(int numCalls);

  protected:
   double mInitialWriteTime = 0.0; // time of first output
   double mWriteTime        = 0.0; // time of next output
   double mWriteStep        = 0.0; // output time interval

   BasePublisherComponent *mPublisher           = nullptr;
   CheckpointableFileStream *mOutputStateStream = nullptr; // file stream for the pvp file
   int mWriteActivityCalls; // Number of calls to writeActivity (written to nbands in the pvp file)
   int mWriteActivitySparseCalls; // Number of calls to writeActivitySparse (written to nbands in
   // the pvp file)

   Timer *mIOTimer = nullptr;
}; // class LayerOutputComponent

} // namespace PV

#endif // LAYEROUTPUTCOMPONENT_HPP_
<commit_msg>Hotfix: some data members were not init'ed<commit_after>/*
 * LayerOutputComponent.hpp
 *
 *  Created on: Dec 3, 2018
 *      Author: peteschultz
 */

#ifndef LAYEROUTPUTCOMPONENT_HPP_
#define LAYEROUTPUTCOMPONENT_HPP_

#include "columns/BaseObject.hpp"

#include "checkpointing/CheckpointableFileStream.hpp"
#include "components/BasePublisherComponent.hpp"
#include "utils/Timer.hpp"

namespace PV {

/**
 * A component to output a layer's activity. It creates a .pvp file whose name is the
 * component's name followed by the suffix ".pvp" in the output directory.
 * It then responds to the LayerOutputStateMessage by appending a frame to the .pvp file
 * with the current activity state (retrieved from the publisher).
 * The boolean parameter sparseLayer controls whether the layer is sparse or dense.
 */
class LayerOutputComponent : public BaseObject {
  protected:
   /**
    * List of parameters needed from the LayerOutputComponent class
    * @name HyPerLayer Parameters
    * @{
    */

   /**
    * @brief writeStep: Specifies how often to output a pvp file for this layer
    * @details Defaults to every timestep. -1 specifies not to write at all.
    */
   virtual void ioParam_writeStep(enum ParamsIOFlag ioFlag);

   /**
    * @brief initialWriteTime: Specifies the first timestep to start outputing pvp files
    */
   virtual void ioParam_initialWriteTime(enum ParamsIOFlag ioFlag);

   /** @} */ // end of LayerOutputComponent parameters

  public:
   LayerOutputComponent(char const *name, PVParams *params, Communicator const *comm);
   virtual ~LayerOutputComponent();

  protected:
   LayerOutputComponent();

   void initialize(char const *name, PVParams *params, Communicator const *comm);

   virtual void setObjectType() override;

   virtual void initMessageActionMap() override;

   virtual int ioParamsFillGroup(enum ParamsIOFlag ioFlag) override;

   virtual Response::Status
   communicateInitInfo(std::shared_ptr<CommunicateInitInfoMessage const> message) override;

   virtual void setDefaultWriteStep(std::shared_ptr<CommunicateInitInfoMessage const> message);

   virtual Response::Status
   registerData(std::shared_ptr<RegisterDataMessage<Checkpointer> const> message) override;

   Response::Status respondLayerOutputState(std::shared_ptr<LayerOutputStateMessage const> message);

   int openOutputStateFile(std::shared_ptr<RegisterDataMessage<Checkpointer> const> message);

   virtual Response::Status outputState(double simTime, double deltaTime);

   /**
    * Appends the current activity to the OutputStateStream if SparseLayer is false.
    * Called by outputState.
    */
   virtual void writeActivity(double simTime, PVLayerCube &cube);

   /**
    * Appends the current activity to the OutputStateStream if SparseLayer is true.
    * Called by outputState.
    */
   virtual void writeActivitySparse(double simTime, PVLayerCube &cube);

   void updateNBands(int numCalls);

  protected:
   double mInitialWriteTime = 0.0; // time of first output
   double mWriteTime        = 0.0; // time of next output
   double mWriteStep        = 0.0; // output time interval

   BasePublisherComponent *mPublisher           = nullptr;
   CheckpointableFileStream *mOutputStateStream = nullptr; // file stream for the pvp file

   int mWriteActivityCalls       = 0; // No. of frames in pvp file (written to nBands in pvp header)
   int mWriteActivitySparseCalls = 0; // No. of frames in pvp file (written to nBands in pvp header)

   Timer *mIOTimer = nullptr;
}; // class LayerOutputComponent

} // namespace PV

#endif // LAYEROUTPUTCOMPONENT_HPP_
<|endoftext|>