<commit_before>/*
 * Copyright (C) 2013
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 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 GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstring>
using std::cout;
using std::cerr;
using std::endl;
using std::fixed;
using std::setprecision;
using std::ofstream;
using std::ceil;
using std::pow;

#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <Exceptions.hpp>
#include <Read.hpp>
#include <utils.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using isa::Exceptions::OpenCLError;
using isa::Benchmarks::Read;
using isa::utils::same;

const unsigned int nrIterations = 10;

int main(int argc, char * argv[]) {
	unsigned int oclPlatform = 0;
	unsigned int oclDevice = 0;
	unsigned int arrayDim = 0;
	unsigned int minThreads = 0;
	unsigned int maxThreads = 0;
	unsigned int nrLoops = 0;

	// Parse command line
	if ( argc != 11 ) {
		cerr << "Usage: " << argv[0] << " -opencl_platform <opencl_platform> -opencl_device <opencl_device> -min <min_threads> -max <max_threads> -loops <nr_loops>" << endl;
		return 1;
	}

	ArgumentList commandLine(argc, argv);
	try {
		oclPlatform = commandLine.getSwitchArgument< unsigned int >("-opencl_platform");
		oclDevice = commandLine.getSwitchArgument< unsigned int >("-opencl_device");
		minThreads = commandLine.getSwitchArgument< unsigned int >("-min");
		maxThreads = commandLine.getSwitchArgument< unsigned int >("-max");
		nrLoops = commandLine.getSwitchArgument< unsigned int >("-loops");
	} catch ( exception & err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Initialize OpenCL
	vector< cl::Platform > * oclPlatforms = new vector< cl::Platform >();
	cl::Context * oclContext = new cl::Context();
	vector< cl::Device > * oclDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > * oclQueues = new vector< vector< cl::CommandQueue > >();
	try {
		initializeOpenCL(oclPlatform, 1, oclPlatforms, oclContext, oclDevices, oclQueues);
	} catch ( OpenCLError &err ) {
		cerr << err.what() << endl;
		return 1;
	}
	arrayDim = (oclDevices->at(oclDevice)).getInfo< CL_DEVICE_MAX_MEM_ALLOC_SIZE >();
	arrayDim /= sizeof(float);

	CLData< float > * B = new CLData< float >("B", true);
	CLData< float > * C = new CLData< float >("C", true);

	B->setCLContext(oclContext);
	B->setCLQueue(&(oclQueues->at(oclDevice)[0]));
	B->allocateHostData(arrayDim);
	C->setCLContext(oclContext);
	C->setCLQueue(&(oclQueues->at(oclDevice)[0]));
	C->allocateHostData(arrayDim);
	try {
		B->setDeviceReadOnly();
		B->allocateDeviceData();
		C->setDeviceWriteOnly();
		C->allocateDeviceData();
	} catch ( OpenCLError &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	cout << fixed;
	for (unsigned int threads0 = minThreads; threads0 <= maxThreads; threads0 *= 2 ) {
		for (unsigned int threads1 = 1; threads1 <= 32; threads1++ ) {
			if ( (arrayDim % (threads0 * threads1) != 0) || ((threads0 * threads1) > maxThreads) ) {
				continue;
			}

			Read< float > read = Read< float >("float");
			try {
				read.bindOpenCL(oclContext, &(oclDevices->at(oclDevice)), &(oclQueues->at(oclDevice)[0]));
				read.setNrThreads(arrayDim);
				read.setNrThreadsPerBlock(threads0);
				read.setNrRows(threads1);
				read.setNrIterations(nrLoops);
				read.generateCode();

				B->copyHostToDevice(true);
				read(B);
				(read.getTimer()).reset();
				for ( unsigned int iter = 0; iter < nrIterations; iter++ ) {
					read(B, C);
				}
			} catch ( OpenCLError &err ) {
				cerr << err.what() << endl;
				return 1;
			}

			cout << threads0 << " " << threads1 << " " << setprecision(3) << read.getGBs() << " " << setprecision(6) << read.getTimer().getAverageTime() << endl;
		}
	}
	cout << endl;

	return 0;
}
<commit_msg>Damn my forgetful mind.<commit_after>/*
 * Copyright (C) 2013
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 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 GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstring>
using std::cout;
using std::cerr;
using std::endl;
using std::fixed;
using std::setprecision;
using std::ofstream;
using std::ceil;
using std::pow;

#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <Exceptions.hpp>
#include <Read.hpp>
#include <utils.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using isa::Exceptions::OpenCLError;
using isa::Benchmarks::Read;
using isa::utils::same;

const unsigned int nrIterations = 10;

int main(int argc, char * argv[]) {
	unsigned int oclPlatform = 0;
	unsigned int oclDevice = 0;
	unsigned int arrayDim = 0;
	unsigned int minThreads = 0;
	unsigned int maxThreads = 0;
	unsigned int nrLoops = 0;

	// Parse command line
	if ( argc != 11 ) {
		cerr << "Usage: " << argv[0] << " -opencl_platform <opencl_platform> -opencl_device <opencl_device> -min <min_threads> -max <max_threads> -loops <nr_loops>" << endl;
		return 1;
	}

	ArgumentList commandLine(argc, argv);
	try {
		oclPlatform = commandLine.getSwitchArgument< unsigned int >("-opencl_platform");
		oclDevice = commandLine.getSwitchArgument< unsigned int >("-opencl_device");
		minThreads = commandLine.getSwitchArgument< unsigned int >("-min");
		maxThreads = commandLine.getSwitchArgument< unsigned int >("-max");
		nrLoops = commandLine.getSwitchArgument< unsigned int >("-loops");
	} catch ( exception & err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Initialize OpenCL
	vector< cl::Platform > * oclPlatforms = new vector< cl::Platform >();
	cl::Context * oclContext = new cl::Context();
	vector< cl::Device > * oclDevices = new vector< cl::Device >();
	vector< vector< cl::CommandQueue > > * oclQueues = new vector< vector< cl::CommandQueue > >();
	try {
		initializeOpenCL(oclPlatform, 1, oclPlatforms, oclContext, oclDevices, oclQueues);
	} catch ( OpenCLError &err ) {
		cerr << err.what() << endl;
		return 1;
	}
	arrayDim = (oclDevices->at(oclDevice)).getInfo< CL_DEVICE_MAX_MEM_ALLOC_SIZE >();
	arrayDim /= sizeof(float);

	CLData< float > * B = new CLData< float >("B", true);
	CLData< float > * C = new CLData< float >("C", true);

	B->setCLContext(oclContext);
	B->setCLQueue(&(oclQueues->at(oclDevice)[0]));
	B->allocateHostData(arrayDim);
	C->setCLContext(oclContext);
	C->setCLQueue(&(oclQueues->at(oclDevice)[0]));
	C->allocateHostData(arrayDim);
	try {
		B->setDeviceReadOnly();
		B->allocateDeviceData();
		C->setDeviceWriteOnly();
		C->allocateDeviceData();
	} catch ( OpenCLError &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	cout << fixed;
	for (unsigned int threads0 = minThreads; threads0 <= maxThreads; threads0 *= 2 ) {
		for (unsigned int threads1 = 1; threads1 <= 32; threads1++ ) {
			if ( (arrayDim % (threads0 * threads1) != 0) || ((threads0 * threads1) > maxThreads) ) {
				continue;
			}

			Read< float > read = Read< float >("float");
			try {
				read.bindOpenCL(oclContext, &(oclDevices->at(oclDevice)), &(oclQueues->at(oclDevice)[0]));
				read.setNrThreads(arrayDim);
				read.setNrThreadsPerBlock(threads0);
				read.setNrRows(threads1);
				read.setNrIterations(nrLoops);
				read.generateCode();

				B->copyHostToDevice(true);
				read(B, C);
				(read.getTimer()).reset();
				for ( unsigned int iter = 0; iter < nrIterations; iter++ ) {
					read(B, C);
				}
			} catch ( OpenCLError &err ) {
				cerr << err.what() << endl;
				return 1;
			}

			cout << threads0 << " " << threads1 << " " << setprecision(3) << read.getGBs() << " " << setprecision(6) << read.getTimer().getAverageTime() << endl;
		}
	}
	cout << endl;

	return 0;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "Graph.h"
#include "Postgres.h"

using namespace std;

/**
 * A simple in-memory stored Graph, with the word indexer and the edge
 * matrix.
 */
class InMemoryGraph : public Graph {
 private:
  char** index2gloss;
  edge** edges;
  uint32_t* edgesSizes;
  uint64_t size;

 public:
  InMemoryGraph(char** index2gloss, edge** edges, uint32_t* edgesSizes, uint64_t size)
    : index2gloss(index2gloss), edges(edges), edgesSizes(edgesSizes), size(size) { }

  ~InMemoryGraph() {
    for (int i = 0; i < size; ++i) {
      free(index2gloss[i]);
      free(edges[i]);
    }
    free(index2gloss);
    free(edges);
    free(edgesSizes);
  }

  virtual const edge* outgoingEdgesFast(word source, uint32_t* size) {
    *size = edgesSizes[source];
    return edges[source];
  }

  virtual const char* gloss(word word) {
    return index2gloss[word];
  }

  virtual const vector<word> keys() {
    vector<word> keys(size);
    for (int i = 0; i < size; ++i) {
      keys[i] = i;
    }
    return keys;
  }
};

Graph* ReadGraph() {
  printf("Reading graph...\n");
  const uint32_t numWords
    = atoi(PGIterator("SELECT COUNT(*) FROM word_indexer;").next()[0]);

  // Read words
  char** index2gloss = (char**) malloc( numWords * sizeof(char*) );
  // (query)
  char wordQuery[127];
  snprintf(wordQuery, 127, "SELECT * FROM %s;", PG_TABLE_WORD.c_str());
  PGIterator words = PGIterator(wordQuery);
  uint64_t wordI = 0;
  while (words.hasNext()) {
    PGRow row = words.next();
    size_t len = strlen(row[1]);
    char* gloss = (char*) malloc( len * sizeof(char) );
    strncpy(gloss, row[1], len);
    index2gloss[atoi(row[0])] = gloss;
    wordI += 1;
    if (wordI % 1000000 == 0) {
      printf("loaded %luM words\n", wordI / 1000000);
    }
  }

  // Read edges
  struct edge** edges = (struct edge**) malloc((numWords+1) * sizeof(struct edge*));
  uint32_t* edgesSizes = (uint32_t*) malloc((numWords+1) * sizeof(uint32_t));
  uint32_t* edgeCapacities = (uint32_t*) malloc((numWords+1) * sizeof(uint32_t));
  for (uint32_t i = 0; i < numWords + 1; ++i) {
    edgesSizes[i] = 0;
    edges[i] = (struct edge*) malloc(4 * sizeof(struct edge));
    edgeCapacities[i] = 4;
  }
  // (query)
  char edgeQuery[127];
  snprintf(edgeQuery, 127, "SELECT * FROM %s;", PG_TABLE_EDGE.c_str());
  PGIterator edgeIter = PGIterator(edgeQuery);
  uint64_t edgeI = 0;
  while (edgeIter.hasNext()) {
    PGRow row = edgeIter.next();
    edge edge;
    edge.source = atol(row[0]);
    edge.sink   = atoi(row[1]);
    edge.type   = atoi(row[2]);
    edge.cost   = atof(row[3]);
    if (edgesSizes[edge.source] >= edgeCapacities[edge.source] - 1) {
      struct edge* newEdges = (struct edge*) malloc(edgeCapacities[edge.source] * 2 * sizeof(struct edge));
      memcpy(newEdges, edges[edge.source], edgeCapacities[edge.source] * sizeof(struct edge));
      free(edges[edge.source]);
      edges[edge.source] = newEdges;
    }
    edges[edge.source][edgesSizes[edge.source]] = edge;
    edgesSizes[edge.source] += 1;
    edgeI += 1;
    if (edgeI % 1000000 == 0) {
      printf("loaded %luM edges\n", edgeI / 1000000);
    }
  }
  free(edgeCapacities);

  // Finish
  printf("%s\n", "Done reading the graph.");
  return new InMemoryGraph(index2gloss, edges, edgesSizes, numWords);
}

class MockGraph : public Graph {
 public:
  MockGraph() {
    noEdges = new vector<edge>();
    // Edges out of Lemur
    lemurEdges = new vector<edge>();
    edge lemurToTimone;
    lemurToTimone.source = 2479928;
    lemurToTimone.sink = 16442985;
    lemurToTimone.type = 1;
    lemurToTimone.cost = 0.01;
    lemurEdges->push_back(lemurToTimone);
    edge lemurToAnimal;
    lemurToAnimal.source = 2479928;
    lemurToAnimal.sink = 3701;
    lemurToAnimal.type = 0;
    lemurToAnimal.cost = 0.42;
    lemurEdges->push_back(lemurToAnimal);
    // Edges out of Animal
    animalEdges = new vector<edge>();
    edge animalToCat;
    animalToCat.source = 3701;
    animalToCat.sink = 27970;
    animalToCat.type = 1;
    animalToCat.cost = 42.00;
    animalEdges->push_back(animalToCat);
    // Other edges
    timoneEdges = new vector<edge>();
    catEdges = new vector<edge>();
    haveEdges = new vector<edge>();
    tailEdges = new vector<edge>();
  }
  ~MockGraph() {
    delete noEdges, lemurEdges, animalEdges, timoneEdges,
           catEdges, haveEdges, tailEdges;
  }

  virtual const edge* outgoingEdgesFast(word source, uint32_t* outputLength) {
    vector<edge> edges = outgoingEdges(source);
    *outputLength = edges.size();
    edge* rtn = (struct edge*) malloc( edges.size() * sizeof(edge) );  // WARNING: memory leak
    for (int i = 0; i < edges.size(); ++i) {
      rtn[i] = edges[i];
    }
    return rtn;
  }

  virtual const vector<edge> outgoingEdges(word source) {
    switch (source) {
      case 2479928:  // lemur
        return *lemurEdges;
      case 3701:     // animal
        return *animalEdges;
      case 16442985: // timone
        return *timoneEdges;
      case 27970:    // cat
        return *catEdges;
      case 3844:     // have
        return *haveEdges;
      case 14221:    // tail
        return *tailEdges;
      default:
        return *noEdges;
    }
  }

  virtual const char* gloss(word word) {
    switch (word) {
      case 2479928:  // lemur
        return "lemur";
      case 3701:     // animal
        return "animal";
      case 16442985: // timone
        return "Timone";
      case 27970:    // cat
        return "cat";
      case 3844:     // have
        return "have";
      case 14221:    // tail
        return "tail";
      default:
        return "<<unk>>";
    }
  }

  virtual const vector<word> keys() {
    vector<word> keys(6);
    keys[0] = 2479928;
    keys[1] = 3701;
    keys[2] = 16442985;
    keys[3] = 27970;
    keys[4] = 3844;
    keys[5] = 14221;
    return keys;
  }

 private:
  vector<edge>* noEdges;
  vector<edge>* lemurEdges;
  vector<edge>* animalEdges;
  vector<edge>* timoneEdges;
  vector<edge>* catEdges;
  vector<edge>* haveEdges;
  vector<edge>* tailEdges;
};

Graph* ReadMockGraph() {
  return new MockGraph();
}
<commit_msg>Oops; update capacities as well<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "Graph.h"
#include "Postgres.h"

using namespace std;

/**
 * A simple in-memory stored Graph, with the word indexer and the edge
 * matrix.
 */
class InMemoryGraph : public Graph {
 private:
  char** index2gloss;
  edge** edges;
  uint32_t* edgesSizes;
  uint64_t size;

 public:
  InMemoryGraph(char** index2gloss, edge** edges, uint32_t* edgesSizes, uint64_t size)
    : index2gloss(index2gloss), edges(edges), edgesSizes(edgesSizes), size(size) { }

  ~InMemoryGraph() {
    for (int i = 0; i < size; ++i) {
      free(index2gloss[i]);
      free(edges[i]);
    }
    free(index2gloss);
    free(edges);
    free(edgesSizes);
  }

  virtual const edge* outgoingEdgesFast(word source, uint32_t* size) {
    *size = edgesSizes[source];
    return edges[source];
  }

  virtual const char* gloss(word word) {
    return index2gloss[word];
  }

  virtual const vector<word> keys() {
    vector<word> keys(size);
    for (int i = 0; i < size; ++i) {
      keys[i] = i;
    }
    return keys;
  }
};

Graph* ReadGraph() {
  printf("Reading graph...\n");
  const uint32_t numWords
    = atoi(PGIterator("SELECT COUNT(*) FROM word_indexer;").next()[0]);

  // Read words
  char** index2gloss = (char**) malloc( numWords * sizeof(char*) );
  // (query)
  char wordQuery[127];
  snprintf(wordQuery, 127, "SELECT * FROM %s;", PG_TABLE_WORD.c_str());
  PGIterator words = PGIterator(wordQuery);
  uint64_t wordI = 0;
  while (words.hasNext()) {
    PGRow row = words.next();
    size_t len = strlen(row[1]);
    char* gloss = (char*) malloc( len * sizeof(char) );
    strncpy(gloss, row[1], len);
    index2gloss[atoi(row[0])] = gloss;
    wordI += 1;
    if (wordI % 1000000 == 0) {
      printf("loaded %luM words\n", wordI / 1000000);
    }
  }

  // Read edges
  struct edge** edges = (struct edge**) malloc((numWords+1) * sizeof(struct edge*));
  uint32_t* edgesSizes = (uint32_t*) malloc((numWords+1) * sizeof(uint32_t));
  uint32_t* edgeCapacities = (uint32_t*) malloc((numWords+1) * sizeof(uint32_t));
  for (uint32_t i = 0; i < numWords + 1; ++i) {
    edgesSizes[i] = 0;
    edges[i] = (struct edge*) malloc(4 * sizeof(struct edge));
    edgeCapacities[i] = 4;
  }
  // (query)
  char edgeQuery[127];
  snprintf(edgeQuery, 127, "SELECT * FROM %s;", PG_TABLE_EDGE.c_str());
  PGIterator edgeIter = PGIterator(edgeQuery);
  uint64_t edgeI = 0;
  while (edgeIter.hasNext()) {
    PGRow row = edgeIter.next();
    edge e;
    e.source = atol(row[0]);
    e.sink   = atoi(row[1]);
    e.type   = atoi(row[2]);
    e.cost   = atof(row[3]);
    if (edgesSizes[e.source] >= edgeCapacities[e.source] - 1) {
      struct edge* newEdges = (struct edge*) malloc(edgeCapacities[e.source] * 2 * sizeof(struct edge));
      memcpy(newEdges, edges[e.source], edgeCapacities[e.source] * sizeof(struct edge));
      edgeCapacities[e.source] = 2 * edgeCapacities[e.source];
      free(edges[e.source]);
      edges[e.source] = newEdges;
    }
    edges[e.source][edgesSizes[e.source]] = e;
    edgesSizes[e.source] += 1;
    edgeI += 1;
    if (edgeI % 1000000 == 0) {
      printf("loaded %luM edges\n", edgeI / 1000000);
    }
  }
  free(edgeCapacities);

  // Finish
  printf("%s\n", "Done reading the graph.");
  return new InMemoryGraph(index2gloss, edges, edgesSizes, numWords);
}

class MockGraph : public Graph {
 public:
  MockGraph() {
    noEdges = new vector<edge>();
    // Edges out of Lemur
    lemurEdges = new vector<edge>();
    edge lemurToTimone;
    lemurToTimone.source = 2479928;
    lemurToTimone.sink = 16442985;
    lemurToTimone.type = 1;
    lemurToTimone.cost = 0.01;
    lemurEdges->push_back(lemurToTimone);
    edge lemurToAnimal;
    lemurToAnimal.source = 2479928;
    lemurToAnimal.sink = 3701;
    lemurToAnimal.type = 0;
    lemurToAnimal.cost = 0.42;
    lemurEdges->push_back(lemurToAnimal);
    // Edges out of Animal
    animalEdges = new vector<edge>();
    edge animalToCat;
    animalToCat.source = 3701;
    animalToCat.sink = 27970;
    animalToCat.type = 1;
    animalToCat.cost = 42.00;
    animalEdges->push_back(animalToCat);
    // Other edges
    timoneEdges = new vector<edge>();
    catEdges = new vector<edge>();
    haveEdges = new vector<edge>();
    tailEdges = new vector<edge>();
  }
  ~MockGraph() {
    delete noEdges, lemurEdges, animalEdges, timoneEdges,
           catEdges, haveEdges, tailEdges;
  }

  virtual const edge* outgoingEdgesFast(word source, uint32_t* outputLength) {
    vector<edge> edges = outgoingEdges(source);
    *outputLength = edges.size();
    edge* rtn = (struct edge*) malloc( edges.size() * sizeof(edge) );  // WARNING: memory leak
    for (int i = 0; i < edges.size(); ++i) {
      rtn[i] = edges[i];
    }
    return rtn;
  }

  virtual const vector<edge> outgoingEdges(word source) {
    switch (source) {
      case 2479928:  // lemur
        return *lemurEdges;
      case 3701:     // animal
        return *animalEdges;
      case 16442985: // timone
        return *timoneEdges;
      case 27970:    // cat
        return *catEdges;
      case 3844:     // have
        return *haveEdges;
      case 14221:    // tail
        return *tailEdges;
      default:
        return *noEdges;
    }
  }

  virtual const char* gloss(word word) {
    switch (word) {
      case 2479928:  // lemur
        return "lemur";
      case 3701:     // animal
        return "animal";
      case 16442985: // timone
        return "Timone";
      case 27970:    // cat
        return "cat";
      case 3844:     // have
        return "have";
      case 14221:    // tail
        return "tail";
      default:
        return "<<unk>>";
    }
  }

  virtual const vector<word> keys() {
    vector<word> keys(6);
    keys[0] = 2479928;
    keys[1] = 3701;
    keys[2] = 16442985;
    keys[3] = 27970;
    keys[4] = 3844;
    keys[5] = 14221;
    return keys;
  }

 private:
  vector<edge>* noEdges;
  vector<edge>* lemurEdges;
  vector<edge>* animalEdges;
  vector<edge>* timoneEdges;
  vector<edge>* catEdges;
  vector<edge>* haveEdges;
  vector<edge>* tailEdges;
};

Graph* ReadMockGraph() {
  return new MockGraph();
}
<|endoftext|>


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

#include "rpcserver.h"
#include "rpcclient.h"

#include "base58.h"
#include "netbase.h"

#include "test/test_bitcoin.h"

#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>

#include "univalue/univalue.h"

using namespace std;

UniValue
createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)
{
    UniValue result(UniValue::VARR);
    result.push_back(nRequired);
    UniValue addresses(UniValue::VARR);
    if (address1) addresses.push_back(address1);
    if (address2) addresses.push_back(address2);
    result.push_back(addresses);
    return result;
}

UniValue CallRPC(string args)
{
    vector<string> vArgs;
    boost::split(vArgs, args, boost::is_any_of(" \t"));
    string strMethod = vArgs[0];
    vArgs.erase(vArgs.begin());
    UniValue params = RPCConvertValues(strMethod, vArgs);

    rpcfn_type method = tableRPC[strMethod]->actor;
    try {
        UniValue result = (*method)(params, false);
        return result;
    }
    catch (const UniValue& objError) {
        throw runtime_error(find_value(objError, "message").get_str());
    }
}

BOOST_FIXTURE_TEST_SUITE(rpc_tests, TestingSetup)

BOOST_AUTO_TEST_CASE(rpc_rawparams)
{
    // Test raw transaction API argument handling
    UniValue r;

    BOOST_CHECK_THROW(CallRPC("getrawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), runtime_error);

    BOOST_CHECK_THROW(CallRPC("createrawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), runtime_error);
    BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}"));
    BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), runtime_error);

    BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), runtime_error);
    string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
    BOOST_CHECK_NO_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx));
    BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1);
    BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0);
    BOOST_CHECK_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx+" extra"), runtime_error);

    BOOST_CHECK_THROW(CallRPC("signrawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), runtime_error);
    BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx));
    BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY"));
    BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY"));
    BOOST_CHECK_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null badenum"), runtime_error);

    // Only check failure cases for sendrawtransaction, there's no network to send to...
    BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), runtime_error);
    BOOST_CHECK_THROW(CallRPC(string("sendrawtransaction ")+rawtx+" extra"), runtime_error);
}

BOOST_AUTO_TEST_CASE(rpc_rawsign)
{
    UniValue r;
    // input is a 1-of-2 multisig (so is output):
    string prevout =
      "[{\"txid\":\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\","
      "\"vout\":1,\"scriptPubKey\":\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\","
      "\"redeemScript\":\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\"}]";
    r = CallRPC(string("createrawtransaction ")+prevout+" "+
      "{\"3HqAe9LtNBjnsfM4CyYaWTnvCaUYT7v4oZ\":11}");
    string notsigned = r.get_str();
    string privkey1 = "\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\"";
    string privkey2 = "\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\"";
    r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]");
    BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false);
    r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]");
    BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true);
}

BOOST_AUTO_TEST_CASE(rpc_format_monetary_values)
{
    BOOST_CHECK(ValueFromAmount(0LL).write() == "0.00000000");
    BOOST_CHECK(ValueFromAmount(1LL).write() == "0.00000001");
    BOOST_CHECK(ValueFromAmount(17622195LL).write() == "0.17622195");
    BOOST_CHECK(ValueFromAmount(50000000LL).write() == "0.50000000");
    BOOST_CHECK(ValueFromAmount(89898989LL).write() == "0.89898989");
    BOOST_CHECK(ValueFromAmount(100000000LL).write() == "1.00000000");
    BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == "20999999.99999990");
    BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == "20999999.99999999");
}

static UniValue ValueFromString(const std::string &str)
{
    UniValue value;
    BOOST_CHECK(value.setNumStr(str));
    return value;
}

BOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)
{
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001")), 1LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.17622195")), 17622195LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.5")), 50000000LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.50000000")), 50000000LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.89898989")), 89898989LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1.00000000")), 100000000LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.9999999")), 2099999999999990LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.99999999")), 2099999999999999LL);
}

BOOST_AUTO_TEST_CASE(json_parse_errors)
{
    Value value;
    // Valid
    BOOST_CHECK_EQUAL(read_string(std::string("1.0"), value), true);
    // Valid, with trailing whitespace
    BOOST_CHECK_EQUAL(read_string(std::string("1.0 "), value), true);
    // Invalid, initial garbage
    BOOST_CHECK_EQUAL(read_string(std::string("[1.0"), value), false);
    BOOST_CHECK_EQUAL(read_string(std::string("a1.0"), value), false);
    // Invalid, trailing garbage
    BOOST_CHECK_EQUAL(read_string(std::string("1.0sds"), value), false);
    BOOST_CHECK_EQUAL(read_string(std::string("1.0]"), value), false);
    // BTC addresses should fail parsing
    BOOST_CHECK_EQUAL(read_string(std::string("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"), value), false);
    BOOST_CHECK_EQUAL(read_string(std::string("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL"), value), false);
}

BOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)
{
    // Check IPv4 addresses
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("1.2.3.4")).ToString(), "1.2.3.4");
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("127.0.0.1")).ToString(), "127.0.0.1");
    // Check IPv6 addresses
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::1")).ToString(), "::1");
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("123:4567:89ab:cdef:123:4567:89ab:cdef")).ToString(),
                                         "123:4567:89ab:cdef:123:4567:89ab:cdef");
    // v4 compatible must be interpreted as IPv4
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::0:127.0.0.1")).ToString(), "127.0.0.1");
    // v4 mapped must be interpreted as IPv4
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::ffff:127.0.0.1")).ToString(), "127.0.0.1");
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>fix univalue json parse tests<commit_after>// Copyright (c) 2012-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcserver.h"
#include "rpcclient.h"

#include "base58.h"
#include "netbase.h"

#include "test/test_bitcoin.h"

#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>

#include "univalue/univalue.h"

using namespace std;

UniValue
createArgs(int nRequired, const char* address1=NULL, const char* address2=NULL)
{
    UniValue result(UniValue::VARR);
    result.push_back(nRequired);
    UniValue addresses(UniValue::VARR);
    if (address1) addresses.push_back(address1);
    if (address2) addresses.push_back(address2);
    result.push_back(addresses);
    return result;
}

UniValue CallRPC(string args)
{
    vector<string> vArgs;
    boost::split(vArgs, args, boost::is_any_of(" \t"));
    string strMethod = vArgs[0];
    vArgs.erase(vArgs.begin());
    UniValue params = RPCConvertValues(strMethod, vArgs);

    rpcfn_type method = tableRPC[strMethod]->actor;
    try {
        UniValue result = (*method)(params, false);
        return result;
    }
    catch (const UniValue& objError) {
        throw runtime_error(find_value(objError, "message").get_str());
    }
}

BOOST_FIXTURE_TEST_SUITE(rpc_tests, TestingSetup)

BOOST_AUTO_TEST_CASE(rpc_rawparams)
{
    // Test raw transaction API argument handling
    UniValue r;

    BOOST_CHECK_THROW(CallRPC("getrawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), runtime_error);

    BOOST_CHECK_THROW(CallRPC("createrawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), runtime_error);
    BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}"));
    BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), runtime_error);

    BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), runtime_error);
    string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
    BOOST_CHECK_NO_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx));
    BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1);
    BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0);
    BOOST_CHECK_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx+" extra"), runtime_error);

    BOOST_CHECK_THROW(CallRPC("signrawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), runtime_error);
    BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx));
    BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY"));
    BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY"));
    BOOST_CHECK_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null badenum"), runtime_error);

    // Only check failure cases for sendrawtransaction, there's no network to send to...
    BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), runtime_error);
    BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), runtime_error);
    BOOST_CHECK_THROW(CallRPC(string("sendrawtransaction ")+rawtx+" extra"), runtime_error);
}

BOOST_AUTO_TEST_CASE(rpc_rawsign)
{
    UniValue r;
    // input is a 1-of-2 multisig (so is output):
    string prevout =
      "[{\"txid\":\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\","
      "\"vout\":1,\"scriptPubKey\":\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\","
      "\"redeemScript\":\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\"}]";
    r = CallRPC(string("createrawtransaction ")+prevout+" "+
      "{\"3HqAe9LtNBjnsfM4CyYaWTnvCaUYT7v4oZ\":11}");
    string notsigned = r.get_str();
    string privkey1 = "\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\"";
    string privkey2 = "\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\"";
    r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]");
    BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false);
    r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]");
    BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true);
}

BOOST_AUTO_TEST_CASE(rpc_format_monetary_values)
{
    BOOST_CHECK(ValueFromAmount(0LL).write() == "0.00000000");
    BOOST_CHECK(ValueFromAmount(1LL).write() == "0.00000001");
    BOOST_CHECK(ValueFromAmount(17622195LL).write() == "0.17622195");
    BOOST_CHECK(ValueFromAmount(50000000LL).write() == "0.50000000");
    BOOST_CHECK(ValueFromAmount(89898989LL).write() == "0.89898989");
    BOOST_CHECK(ValueFromAmount(100000000LL).write() == "1.00000000");
    BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == "20999999.99999990");
    BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == "20999999.99999999");
}

static UniValue ValueFromString(const std::string &str)
{
    UniValue value;
    BOOST_CHECK(value.setNumStr(str));
    return value;
}

BOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)
{
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001")), 1LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.17622195")), 17622195LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.5")), 50000000LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.50000000")), 50000000LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.89898989")), 89898989LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1.00000000")), 100000000LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.9999999")), 2099999999999990LL);
    BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.99999999")), 2099999999999999LL);
}

BOOST_AUTO_TEST_CASE(json_parse_errors)
{
    UniValue value;
    // Valid
    BOOST_CHECK_EQUAL(value.read(std::string("1.0")), false);
    BOOST_CHECK_EQUAL(value.read(std::string("[1.0]")), true);
    // Valid, with trailing whitespace
    BOOST_CHECK_EQUAL(value.read(std::string("1.0 ")), false);
    BOOST_CHECK_EQUAL(value.read(std::string("[1.0 ] ")), true);
    // Invalid, initial garbage
    BOOST_CHECK_EQUAL(value.read(std::string("[1.0")), false);
    BOOST_CHECK_EQUAL(value.read(std::string("[a1.0]")), false);
     BOOST_CHECK_EQUAL(value.read(std::string("[\"a1.0\"]")), true);
    // Invalid, trailing garbage
    BOOST_CHECK_EQUAL(value.read(std::string("1.0sds")), false);
    BOOST_CHECK_EQUAL(value.read(std::string("1.0]")), false);
    // BTC addresses should fail parsing
    BOOST_CHECK_EQUAL(value.read(std::string("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W")), false);
    BOOST_CHECK_EQUAL(value.read(std::string("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL")), false);
}

BOOST_AUTO_TEST_CASE(rpc_boostasiotocnetaddr)
{
    // Check IPv4 addresses
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("1.2.3.4")).ToString(), "1.2.3.4");
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("127.0.0.1")).ToString(), "127.0.0.1");
    // Check IPv6 addresses
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::1")).ToString(), "::1");
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("123:4567:89ab:cdef:123:4567:89ab:cdef")).ToString(),
                                         "123:4567:89ab:cdef:123:4567:89ab:cdef");
    // v4 compatible must be interpreted as IPv4
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::0:127.0.0.1")).ToString(), "127.0.0.1");
    // v4 mapped must be interpreted as IPv4
    BOOST_CHECK_EQUAL(BoostAsioToCNetAddr(boost::asio::ip::address::from_string("::ffff:127.0.0.1")).ToString(), "127.0.0.1");
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "HLSLParser.h"
#include "GLSLGenerator.h"
#include "HLSLGenerator.h"

#include <fstream>
#include <sstream>
#include <iostream>

enum Target
{
    Target_VertexShader,
    Target_FragmentShader,
};

enum Language
{
	Language_GLSL,
	Language_HLSL,
	Language_LegacyHLSL,
};

std::string ReadFile( const char* fileName )
{
	std::ifstream ifs( fileName );
	std::stringstream buffer;
	buffer << ifs.rdbuf();
	return buffer.str();
}

void PrintUsage()
{
	std::cerr << "usage: hlslparser [-h] [-fs | -vs] FILENAME ENTRYNAME\n"
		<< "\n"
		<< "Translate HLSL shader to GLSL shader.\n"
		<< "\n"
		<< "positional arguments:\n"
		<< " FILENAME    input file name\n"
		<< " ENTRYNAME   entry point of the shader\n"
		<< "\n"
		<< "optional arguments:\n"
		<< " -h, --help  show this help message and exit\n"
		<< " -fs         generate fragment shader (default)\n"
		<< " -vs         generate vertex shader\n"
		<< " -glsl       generate GLSL (default)\n"
		<< " -hlsl       generate HLSL\n"
		<< " -legacyhlsl generate legacy HLSL\n";
}

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

	// Parse arguments
	const char* fileName = NULL;
	const char* entryName = NULL;

	Target target = Target_FragmentShader;
	Language language = Language_GLSL;

	for( int argn = 1; argn < argc; ++argn )
	{
		const char* const arg = argv[ argn ];

		if( String_Equal( arg, "-h" ) || String_Equal( arg, "--help" ) )
		{
			PrintUsage();
			return 0;
		}
		else if( String_Equal( arg, "-fs" ) )
		{
			target = Target_FragmentShader;
		}
		else if( String_Equal( arg, "-vs" ) )
		{
			target = Target_VertexShader;
		}
		else if( String_Equal( arg, "-glsl" ) )
		{
			language = Language_GLSL;
		}
		else if( String_Equal( arg, "-hlsl" ) )
		{
			language = Language_HLSL;
		}
		else if( String_Equal( arg, "-legacyhlsl" ) )
		{
			language = Language_LegacyHLSL;
		}
		else if( fileName == NULL )
		{
			fileName = arg;
		}
		else if( entryName == NULL )
		{
			entryName = arg;
		}
		else
		{
			Log_Error( "Too many arguments\n" );
			PrintUsage();
			return 1;
		}
	}

	if( fileName == NULL || entryName == NULL )
	{
		Log_Error( "Missing arguments\n" );
		PrintUsage();
		return 1;
	}

	// Read input file
	const std::string source = ReadFile( fileName );

	// Parse input file
	Allocator allocator;
	HLSLParser parser( &allocator, fileName, source.data(), source.size() );
	HLSLTree tree( &allocator );
	if( !parser.Parse( &tree ) )
	{
		Log_Error( "Parsing failed, aborting\n" );
		return 1;
	}

	// Generate output
	if (language == Language_GLSL)
	{
		GLSLGenerator generator( &allocator );
		if (!generator.Generate( &tree, GLSLGenerator::Target(target), GLSLGenerator::Version_140, entryName ))
		{
			Log_Error( "Translation failed, aborting\n" );
			return 1;
		}

		std::cout << generator.GetResult();
	}
	else
	{
		HLSLGenerator generator( &allocator );
		if (!generator.Generate( &tree, HLSLGenerator::Target(target), entryName, language == Language_LegacyHLSL ))
		{
			Log_Error( "Translation failed, aborting\n" );
			return 1;
		}

		std::cout << generator.GetResult();
	}

	return 0;
}
<commit_msg>Add Metal support to the command-line compiler<commit_after>#include "HLSLParser.h"

#include "GLSLGenerator.h"
#include "HLSLGenerator.h"
#include "MSLGenerator.h"

#include <fstream>
#include <sstream>
#include <iostream>

enum Target
{
    Target_VertexShader,
    Target_FragmentShader,
};

enum Language
{
	Language_GLSL,
	Language_HLSL,
	Language_LegacyHLSL,
	Language_Metal,
};

std::string ReadFile( const char* fileName )
{
	std::ifstream ifs( fileName );
	std::stringstream buffer;
	buffer << ifs.rdbuf();
	return buffer.str();
}

void PrintUsage()
{
	std::cerr << "usage: hlslparser [-h] [-fs | -vs] FILENAME ENTRYNAME\n"
		<< "\n"
		<< "Translate HLSL shader to GLSL shader.\n"
		<< "\n"
		<< "positional arguments:\n"
		<< " FILENAME    input file name\n"
		<< " ENTRYNAME   entry point of the shader\n"
		<< "\n"
		<< "optional arguments:\n"
		<< " -h, --help  show this help message and exit\n"
		<< " -fs         generate fragment shader (default)\n"
		<< " -vs         generate vertex shader\n"
		<< " -glsl       generate GLSL (default)\n"
		<< " -hlsl       generate HLSL\n"
		<< " -legacyhlsl generate legacy HLSL\n"
		<< " -metal      generate MSL\n";
}

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

	// Parse arguments
	const char* fileName = NULL;
	const char* entryName = NULL;

	Target target = Target_FragmentShader;
	Language language = Language_GLSL;

	for( int argn = 1; argn < argc; ++argn )
	{
		const char* const arg = argv[ argn ];

		if( String_Equal( arg, "-h" ) || String_Equal( arg, "--help" ) )
		{
			PrintUsage();
			return 0;
		}
		else if( String_Equal( arg, "-fs" ) )
		{
			target = Target_FragmentShader;
		}
		else if( String_Equal( arg, "-vs" ) )
		{
			target = Target_VertexShader;
		}
		else if( String_Equal( arg, "-glsl" ) )
		{
			language = Language_GLSL;
		}
		else if( String_Equal( arg, "-hlsl" ) )
		{
			language = Language_HLSL;
		}
		else if( String_Equal( arg, "-legacyhlsl" ) )
		{
			language = Language_LegacyHLSL;
		}
		else if( String_Equal( arg, "-metal" ) )
		{
			language = Language_Metal;
		}
		else if( fileName == NULL )
		{
			fileName = arg;
		}
		else if( entryName == NULL )
		{
			entryName = arg;
		}
		else
		{
			Log_Error( "Too many arguments\n" );
			PrintUsage();
			return 1;
		}
	}

	if( fileName == NULL || entryName == NULL )
	{
		Log_Error( "Missing arguments\n" );
		PrintUsage();
		return 1;
	}

	// Read input file
	const std::string source = ReadFile( fileName );

	// Parse input file
	Allocator allocator;
	HLSLParser parser( &allocator, fileName, source.data(), source.size() );
	HLSLTree tree( &allocator );
	if( !parser.Parse( &tree ) )
	{
		Log_Error( "Parsing failed, aborting\n" );
		return 1;
	}

	// Generate output
	if (language == Language_GLSL)
	{
		GLSLGenerator generator( &allocator );
		if (!generator.Generate( &tree, GLSLGenerator::Target(target), GLSLGenerator::Version_140, entryName ))
		{
			Log_Error( "Translation failed, aborting\n" );
			return 1;
		}

		std::cout << generator.GetResult();
	}
	else if (language == Language_HLSL)
	{
		HLSLGenerator generator( &allocator );
		if (!generator.Generate( &tree, HLSLGenerator::Target(target), entryName, language == Language_LegacyHLSL ))
		{
			Log_Error( "Translation failed, aborting\n" );
			return 1;
		}

		std::cout << generator.GetResult();
	}
	else if (language == Language_Metal)
	{
		MSLGenerator generator;
		if (!generator.Generate( &tree, MSLGenerator::Target(target), entryName ))
		{
			Log_Error( "Translation failed, aborting\n" );
			return 1;
		}

		std::cout << generator.GetResult();
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "../include/Main.h"

//using Poco::StringTokenizer;

int main(int argc, char** argv) {
    if (argc == 4) {
        Transaction* session = new Transaction(argv[1], argv[2], argv[3]);

        string input, username, type, event, seller;
        double balance, price;
        int ticketNum;
        bool success = false;

        while (getline(cin, input)) {
            //cout << "Enter your command." << endl;
            input = rtrim(input);
            // TODO Trim right side of the input
            if (!session->isLoggedIn()) {
                if (input.compare("login") == 0) {
                    // Log in stuff.
                    cout << "enter username" << endl;
                    getline(cin, input);

                    if (session->login(input)) {
                        cout << "login successful" << endl;
                    }
                }
                else if (input.compare("quit") == 0) {
                	session->quit();
                    break;
                }
                else {
                    cout << "error: invalid command" << endl;
                }
            }
            else {
                if (input.compare("logout") == 0) {
                    session->logout();
                    cout << "logout successful" << endl;
                }
                else if (input.compare("create") == 0) {
                    cout << "enter username to create" << endl;
                    getline(cin, username);

                    // TODO: Catch create1 testcase
                    // username must be maximum 15 characters

                    cout << "enter account type" << endl;
                    getline(cin, type);

                    cout << "enter user account balance" << endl;
                    //getline(cin, balance);
                    cin >> balance;

                    if (session->create(username, type, balance)) {
                        cout << "create successful" << endl;
                    }
                }
                else if (input.compare("delete") == 0) {
                    cout << "enter username" << endl;
                    getline(cin, username);

                    if (session->removeUser(username)) {
                        cout << "delete successful" << endl;
                    }
                }
                else if (input.compare("addcredit") == 0) {
                    if (session->isAdmin()) {
                        cout << "enter username" << endl;
                        getline(cin, username);
                    }

                    cout << "enter credit amount" << endl;
                    //getline(cin, balance);
                    cin >> balance;

                    success = false;

                    success = validBalance(balance);

                    if (session->isAdmin()) {
                        success = session->addcredit(balance);
                    }
                    else {
                        success = session->addcredit(username, balance);
                    }

                    if (success) {
                        cout << "credit added" << endl;
                    }
                }
                else if (input.compare("sell") == 0) {
                    cout << "enter event title" << endl;
                    getline(cin, event);

                    cout << "enter sale price" << endl;
                    //getline(cin, price);
                    cin >> price;

                    cout << "enter number of tickets" << endl;
                    //getline(cin, ticketNum);
                    cin >> ticketNum;

                    if (session->sell(event, price, ticketNum)) {
                        cout << "tickets added" << endl;
                    }
                }
                else if (input.compare("buy") == 0) {
                    cout << "enter event title" << endl;
                    getline(cin, event);

                    cout << "enter number of tickets" << endl;
                    //getline(cin, ticketNum);
                    cin >> ticketNum;

                    // Skip to next line
                    while (cin.get() != '\n');

                    cout << "enter username of seller" << endl;
                    getline(cin, seller);

                    if (session->buy(event, ticketNum, seller)) {
                        cout << "purchase successful" << endl;
                    }
                }
                else if (input.compare("refund") == 0) {
                    cout << "enter buyer's username" << endl;
                    getline(cin, username);

                    cout << "enter seller's username" << endl;
                    getline(cin, seller);

                    cout << "enter amount to transfer" << endl;
                    //getline(cin, balance);
                    cin >> balance;

                    if (session->refund(username, seller, balance)) {
                        cout << "refund successful" << endl;
                    }
                }
                else {
                    cout << "error: invalid command" << endl;
                }
            }
            //cout << endl;
        }
    }

    cout << endl;

    return 0;
}
<commit_msg>FIXED: buy11<commit_after>#include "../include/Main.h"

//using Poco::StringTokenizer;

int main(int argc, char** argv) {
    if (argc == 4) {
        Transaction* session = new Transaction(argv[1], argv[2], argv[3]);

        string input, username, type, event, seller;
        double balance, price;
        int ticketNum;
        bool success = false;

        while (getline(cin, input)) {
            //cout << "Enter your command." << endl;
            input = rtrim(input);
            // TODO Trim right side of the input
            if (!session->isLoggedIn()) {
                if (input.compare("login") == 0) {
                    // Log in stuff.
                    cout << "enter username" << endl;
                    getline(cin, input);

                    if (session->login(input)) {
                        cout << "login successful" << endl;
                    }
                }
                else if (input.compare("quit") == 0) {
                    session->quit();
                    break;
                }
                else {
                    cout << "error: invalid command" << endl;
                }
            }
            else {
                if (input.compare("logout") == 0) {
                    session->logout();
                    cout << "logout successful" << endl;
                }
                else if (input.compare("create") == 0) {
                    cout << "enter username to create" << endl;
                    getline(cin, username);

                    // TODO: Catch create1 testcase
                    // username must be maximum 15 characters

                    cout << "enter account type" << endl;
                    getline(cin, type);

                    cout << "enter user account balance" << endl;
                    //getline(cin, balance);
                    cin >> balance;

                    if (session->create(username, type, balance)) {
                        cout << "create successful" << endl;
                    }
                }
                else if (input.compare("delete") == 0) {
                    cout << "enter username" << endl;
                    getline(cin, username);

                    if (session->removeUser(username)) {
                        cout << "delete successful" << endl;
                    }
                }
                else if (input.compare("addcredit") == 0) {
                    if (session->isAdmin()) {
                        cout << "enter username" << endl;
                        getline(cin, username);
                    }

                    cout << "enter credit amount" << endl;
                    //getline(cin, balance);
                    cin >> balance;

                    success = false;

                    success = validBalance(balance);

                    if (session->isAdmin()) {
                        success = session->addcredit(balance);
                    }
                    else {
                        success = session->addcredit(username, balance);
                    }

                    if (success) {
                        cout << "credit added" << endl;
                    }
                }
                else if (input.compare("sell") == 0) {
                    cout << "enter event title" << endl;
                    getline(cin, event);

                    cout << "enter sale price" << endl;
                    //getline(cin, price);
                    cin >> price;

                    cout << "enter number of tickets" << endl;
                    //getline(cin, ticketNum);
                    cin >> ticketNum;

                    if (session->sell(event, price, ticketNum)) {
                        cout << "tickets added" << endl;
                    }
                }
                else if (input.compare("buy") == 0) {
                    cout << "enter event title" << endl;
                    getline(cin, event);

                    cout << "enter number of tickets" << endl;
                    //getline(cin, ticketNum);

                    cin >> ticketNum;
                    bool fail = cin.fail();

                    // Skip to next line
                    string dummy;
                    getline(cin, dummy);

                    if (!fail || ticketNum < 1) {
                        cout << "error: invalid ticket number" << endl;
                    } else {
                        cout << "enter username of seller" << endl;
                        getline(cin, seller);

                        if (session->buy(event, ticketNum, seller)) {
                            cout << "purchase successful" << endl;
                        }
                    }
                }
                else if (input.compare("refund") == 0) {
                    cout << "enter buyer's username" << endl;
                    getline(cin, username);

                    cout << "enter seller's username" << endl;
                    getline(cin, seller);

                    cout << "enter amount to transfer" << endl;
                    //getline(cin, balance);
                    cin >> balance;

                    if (session->refund(username, seller, balance)) {
                        cout << "refund successful" << endl;
                    }
                }
                else {
                    cout << "error: invalid command" << endl;
                }
            }
            //cout << endl;
        }
    }

    cout << endl;

    return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program. If not, see <http://www.gnu.org/licenses/>.              *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sstream>
using std::ostringstream ;
#include <fstream>

#include <string>
using std::string;

#include <vector>
using std::vector;

#include <sofa/helper/ArgumentParser.h>
#include <SofaSimulationCommon/common.h>
#include <sofa/simulation/Node.h>
#include <sofa/helper/system/PluginManager.h>
#include <sofa/simulation/config.h> // #defines SOFA_HAVE_DAG (or not)
#include <SofaSimulationCommon/init.h>
#ifdef SOFA_HAVE_DAG
#include <SofaSimulationGraph/init.h>
#include <SofaSimulationGraph/DAGSimulation.h>
#endif
#include <SofaSimulationTree/init.h>
#include <SofaSimulationTree/TreeSimulation.h>
using sofa::simulation::Node;

#include <SofaComponentCommon/initComponentCommon.h>
#include <SofaComponentBase/initComponentBase.h>
#include <SofaComponentGeneral/initComponentGeneral.h>
#include <SofaComponentAdvanced/initComponentAdvanced.h>
#include <SofaComponentMisc/initComponentMisc.h>

#include <SofaGeneralLoader/ReadState.h>
#include <SofaValidation/CompareState.h>
#include <sofa/helper/Factory.h>
#include <sofa/helper/cast.h>
#include <sofa/helper/BackTrace.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <sofa/helper/Utils.h>
#include <sofa/gui/GUIManager.h>
using sofa::gui::GUIManager;

#include <sofa/gui/Main.h>
#include <sofa/gui/BatchGUI.h>  // For the default number of iterations
#include <sofa/helper/system/gl.h>
#include <sofa/helper/system/atomic.h>

using sofa::core::ExecParams ;

#include <sofa/helper/system/console.h>
using sofa::helper::Utils;
using sofa::helper::Console;

using sofa::component::misc::CompareStateCreator;
using sofa::component::misc::ReadStateActivator;
using sofa::simulation::tree::TreeSimulation;
using sofa::simulation::graph::DAGSimulation;
using sofa::helper::system::SetDirectory;
using sofa::core::objectmodel::BaseNode ;
using sofa::gui::BatchGUI;
using sofa::gui::BaseGUI;

#include <sofa/helper/logging/Messaging.h>

#include <sofa/helper/logging/ConsoleMessageHandler.h>
using sofa::helper::logging::ConsoleMessageHandler ;

#include <sofa/core/logging/RichConsoleStyleMessageFormatter.h>
using  sofa::helper::logging::RichConsoleStyleMessageFormatter ;

#include <sofa/core/logging/PerComponentLoggingMessageHandler.h>
using  sofa::helper::logging::MainPerComponentLoggingMessageHandler ;

#ifdef SOFA_HAVE_GLUT_GUI
#include <sofa/helper/system/glut.h>
#endif // SOFA_HAVE_GLUT_GUI

#ifdef WIN32
#include <windows.h>
#endif

using sofa::helper::system::DataRepository;
using sofa::helper::system::PluginRepository;
using sofa::helper::system::PluginManager;

#include <sofa/helper/logging/MessageDispatcher.h>
using sofa::helper::logging::MessageDispatcher ;

#include <sofa/helper/logging/ClangMessageHandler.h>
using sofa::helper::logging::ClangMessageHandler ;

#include <sofa/helper/logging/ExceptionMessageHandler.h>
using sofa::helper::logging::ExceptionMessageHandler;

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

void loadVerificationData(string& directory, string& filename, Node* node)
{
    msg_info("") << "loadVerificationData from " << directory << " and file " << filename ;

    string refFile;

    refFile += directory;
    refFile += '/';
    refFile += SetDirectory::GetFileName(filename.c_str());

    msg_info("") << "loadVerificationData " << refFile ;

    CompareStateCreator compareVisitor(ExecParams::defaultInstance());
    compareVisitor.setCreateInMapping(true);
    compareVisitor.setSceneName(refFile);
    compareVisitor.execute(node);

    ReadStateActivator v_read(ExecParams::defaultInstance(), true);
    v_read.execute(node);
}

// ---------------------------------------------------------------------
// ---
// ---------------------------------------------------------------------
int main(int argc, char** argv)
{
    sofa::helper::BackTrace::autodump();

    ExecParams::defaultInstance()->setAspectID(0);

#ifdef WIN32
    {
        HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
        COORD s;
        s.X = 160; s.Y = 10000;
        SetConsoleScreenBufferSize(hStdout, s);
        CONSOLE_SCREEN_BUFFER_INFO csbi;
        if (GetConsoleScreenBufferInfo(hStdout, &csbi))
        {
            SMALL_RECT winfo;
            winfo = csbi.srWindow;
            //winfo.Top = 0;
            winfo.Left = 0;
            //winfo.Bottom = csbi.dwSize.Y-1;
            winfo.Right = csbi.dwMaximumWindowSize.X-1;
            SetConsoleWindowInfo(hStdout, TRUE, &winfo);
        }

    }
#endif

    sofa::gui::initMain();

    string fileName ;
    bool        startAnim = false;
    bool        printFactory = false;
    bool        loadRecent = false;
    bool        temporaryFile = false;
    bool        testMode = false;
    bool        noAutoloadPlugins = false;
    int         nbIterations = BatchGUI::DEFAULT_NUMBER_OF_ITERATIONS;
    unsigned int nbMSSASamples = 1;
    unsigned    computationTimeSampling=0; ///< Frequency of display of the computation time statistics, in number of animation steps. 0 means never.

    string gui = "";
    string verif = "";

#if defined(SOFA_HAVE_DAG)
    string simulationType = "dag";
#else
    string simulationType = "tree";
#endif

    vector<string> plugins;
    vector<string> files;
    string colorsStatus = "auto";
    string messageHandler = "auto";
    bool enableInteraction = false ;

    string gui_help = "choose the UI (";
    gui_help += GUIManager::ListSupportedGUI('|');
    gui_help += ")";

    sofa::helper::parse(&files, "This is a SOFA application. Here are the command line arguments")
    // alphabetical order on short name
    .option(&startAnim,'a',"start","start the animation loop")
    .option(&computationTimeSampling,'c',"computationTimeSampling","Frequency of display of the computation time statistics, in number of animation steps. 0 means never.")
    .option(&gui,'g',"gui",gui_help.c_str())
    .option(&plugins,'l',"load","load given plugins")
    .option(&noAutoloadPlugins, '0', "noautoload", "disable plugins autoloading")
    .option(&nbMSSASamples, 'm', "msaa", "number of samples for MSAA (Multi Sampling Anti Aliasing ; value < 2 means disabled")
    .option(&nbIterations,'n',"nb_iterations","(only batch) Number of iterations of the simulation")
    .option(&printFactory,'p',"factory","print factory logs")
    .option(&loadRecent,'r',"recent","load most recently opened file")
    .option(&simulationType,'s',"simu","select the type of simulation (bgl, dag, tree)")
    .option(&temporaryFile,'t',"temporary","the loaded scene won't appear in history of opened files")
    .option(&testMode,'x',"test","select test mode with xml output after N iteration")
    .option(&verif,'v',"verification","load verification data for the scene")
    .option(&colorsStatus,'z',"colors","use colors on stdout and stderr (yes, no, auto)")
    .option(&messageHandler,'f',"formatting","select the message formatting to use (auto, clang, sofa, rich, test)")
    .option(&enableInteraction, 'i', "interactive", "enable interactive mode for the GUI which includes idle and mouse events (EXPERIMENTAL)")
    (argc,argv);

    // Note that initializations must be done after ArgumentParser that can exit the application (without cleanup)
    // even if everything is ok e.g. asking for help
    sofa::simulation::tree::init();
#ifdef SOFA_HAVE_DAG
    sofa::simulation::graph::init();
#endif
    sofa::component::initComponentBase();
    sofa::component::initComponentCommon();
    sofa::component::initComponentGeneral();
    sofa::component::initComponentAdvanced();
    sofa::component::initComponentMisc();

#ifndef SOFA_NO_OPENGL
#ifdef SOFA_HAVE_GLUT_GUI
    if(gui!="batch") glutInit(&argc,argv);
#endif // SOFA_HAVE_GLUT_GUI
#endif // SOFA_NO_OPENGL

#ifdef SOFA_HAVE_DAG
    if (simulationType == "tree")
        sofa::simulation::setSimulation(new TreeSimulation());
    else
        sofa::simulation::setSimulation(new DAGSimulation());
#else //SOFA_HAVE_DAG
    sofa::simulation::setSimulation(new TreeSimulation());
#endif

    if (colorsStatus == "auto")
        Console::setColorsStatus(Console::ColorsAuto);
    else if (colorsStatus == "yes")
        Console::setColorsStatus(Console::ColorsEnabled);
    else if (colorsStatus == "no")
        Console::setColorsStatus(Console::ColorsDisabled);

    //TODO(dmarchal): Use smart pointer there to avoid memory leaks !!
    if (messageHandler == "auto" )
    {
        MessageDispatcher::clearHandlers() ;
        MessageDispatcher::addHandler( new ConsoleMessageHandler() ) ;
    }
    else if (messageHandler == "clang")
    {
        MessageDispatcher::clearHandlers() ;
        MessageDispatcher::addHandler( new ClangMessageHandler() ) ;
    }
    else if (messageHandler == "sofa")
    {
        MessageDispatcher::clearHandlers() ;
        MessageDispatcher::addHandler( new ConsoleMessageHandler() ) ;
    }
    else if (messageHandler == "rich")
    {
        MessageDispatcher::clearHandlers() ;
        MessageDispatcher::addHandler( new ConsoleMessageHandler(new RichConsoleStyleMessageFormatter()) ) ;
    }
    else if (messageHandler == "test"){
        MessageDispatcher::addHandler( new ExceptionMessageHandler() ) ;
    }
    else{
        msg_warning("") << "Invalid argument '" << messageHandler << "' for '--formatting'";
    }
    MessageDispatcher::addHandler(&MainPerComponentLoggingMessageHandler::getInstance()) ;

    // Initialise paths
    BaseGUI::setConfigDirectoryPath(Utils::getSofaPathPrefix() + "/config", true);
    BaseGUI::setScreenshotDirectoryPath(Utils::getSofaPathPrefix() + "/screenshots", true);

    if (!files.empty())
        fileName = files[0];

    for (unsigned int i=0; i<plugins.size(); i++)
        PluginManager::getInstance().loadPlugin(plugins[i]);

    std::string configPluginPath = PluginRepository.getFirstPath() + "/" + TOSTRING(CONFIG_PLUGIN_FILENAME);
    std::string defaultConfigPluginPath = PluginRepository.getFirstPath() + "/" + TOSTRING(DEFAULT_CONFIG_PLUGIN_FILENAME);

    if (!noAutoloadPlugins)
    {
        if (DataRepository.findFile(configPluginPath))
        {
            msg_info("runSofa") << "Loading automatically plugin list in " << configPluginPath;
            PluginManager::getInstance().readFromIniFile(configPluginPath);
        }
        else if (DataRepository.findFile(defaultConfigPluginPath))
        {
            msg_info("runSofa") << "Loading automatically plugin list in " << defaultConfigPluginPath;
            PluginManager::getInstance().readFromIniFile(defaultConfigPluginPath);
        }
        else
            msg_info("runSofa") << "No plugin list found. No plugin will be automatically loaded.";
    }
    else
        msg_info("runSofa") << "Automatic plugin loading disabled.";

    PluginManager::getInstance().init();

    if(gui.compare("batch") == 0 && nbIterations >= 0)
    {
        ostringstream oss ;
        oss << "nbIterations=";
        oss << nbIterations;
        GUIManager::AddGUIOption(oss.str().c_str());
    }

    if(enableInteraction){
        msg_warning("Main") << "you activated the interactive mode. This is currently an experimental feature "
                               "that may change or be removed in the future. " ;
        GUIManager::AddGUIOption("enableInteraction");
    }

    if(nbMSSASamples > 1)
    {
        ostringstream oss ;
        oss << "msaa=";
        oss << nbMSSASamples;
        GUIManager::AddGUIOption(oss.str().c_str());
    }

    if (int err = GUIManager::Init(argv[0],gui.c_str()))
        return err;

    if (fileName.empty())
    {
        if (loadRecent) // try to reload the latest scene
        {
            string scenes = BaseGUI::getConfigDirectoryPath() + "/runSofa.ini";
            std::ifstream mrulist(scenes.c_str());
            std::getline(mrulist,fileName);
            mrulist.close();
        }
        else
            fileName = "Demos/caduceus.scn";

        fileName = DataRepository.getFile(fileName);
    }

    if (int err=GUIManager::createGUI(NULL))
        return err;

    //To set a specific resolution for the viewer, use the component ViewerSetting in you scene graph
    GUIManager::SetDimension(800,600);

    Node::SPtr groot = sofa::simulation::getSimulation()->load(fileName.c_str());
    if( !groot )
        groot = sofa::simulation::getSimulation()->createNewGraph("");

    if (!verif.empty())
    {
        loadVerificationData(verif, fileName, groot.get());
    }

    sofa::simulation::getSimulation()->init(groot.get());
    GUIManager::SetScene(groot,fileName.c_str(), temporaryFile);

    //=======================================
    //Apply Options

    if (startAnim)
        groot->setAnimate(true);
    if (printFactory)
    {
        msg_info("") << "////////// FACTORY //////////" ;
        sofa::helper::printFactoryLog();
        msg_info("") << "//////// END FACTORY ////////" ;
    }

    if( computationTimeSampling>0 )
    {
        sofa::helper::AdvancedTimer::setEnabled("Animate", true);
        sofa::helper::AdvancedTimer::setInterval("Animate", computationTimeSampling);
    }

    //=======================================
    // Run the main loop
    if (int err = GUIManager::MainLoop(groot,fileName.c_str()))
        return err;
    groot = dynamic_cast<Node*>( GUIManager::CurrentSimulation() );

    if (testMode)
    {
        string xmlname = fileName.substr(0,fileName.length()-4)+"-scene.scn";
        msg_info("") << "Exporting to XML " << xmlname ;
        sofa::simulation::getSimulation()->exportXML(groot.get(), xmlname.c_str());
    }

    if (groot!=NULL)
        sofa::simulation::getSimulation()->unload(groot);

    GUIManager::closeGUI();

    sofa::simulation::common::cleanup();
    sofa::simulation::tree::cleanup();
#ifdef SOFA_HAVE_DAG
    sofa::simulation::graph::cleanup();
#endif
    return 0;
}
<commit_msg>[runSofa] FIX PluginRepository initialization<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program. If not, see <http://www.gnu.org/licenses/>.              *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sstream>
using std::ostringstream ;
#include <fstream>

#include <string>
using std::string;

#include <vector>
using std::vector;

#include <sofa/helper/ArgumentParser.h>
#include <SofaSimulationCommon/common.h>
#include <sofa/simulation/Node.h>
#include <sofa/helper/system/PluginManager.h>
#include <sofa/simulation/config.h> // #defines SOFA_HAVE_DAG (or not)
#include <SofaSimulationCommon/init.h>
#ifdef SOFA_HAVE_DAG
#include <SofaSimulationGraph/init.h>
#include <SofaSimulationGraph/DAGSimulation.h>
#endif
#include <SofaSimulationTree/init.h>
#include <SofaSimulationTree/TreeSimulation.h>
using sofa::simulation::Node;

#include <SofaComponentCommon/initComponentCommon.h>
#include <SofaComponentBase/initComponentBase.h>
#include <SofaComponentGeneral/initComponentGeneral.h>
#include <SofaComponentAdvanced/initComponentAdvanced.h>
#include <SofaComponentMisc/initComponentMisc.h>

#include <SofaGeneralLoader/ReadState.h>
#include <SofaValidation/CompareState.h>
#include <sofa/helper/Factory.h>
#include <sofa/helper/cast.h>
#include <sofa/helper/BackTrace.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <sofa/helper/Utils.h>
#include <sofa/gui/GUIManager.h>
using sofa::gui::GUIManager;

#include <sofa/gui/Main.h>
#include <sofa/gui/BatchGUI.h>  // For the default number of iterations
#include <sofa/helper/system/gl.h>
#include <sofa/helper/system/atomic.h>

using sofa::core::ExecParams ;

#include <sofa/helper/system/console.h>
using sofa::helper::Utils;
using sofa::helper::Console;

using sofa::component::misc::CompareStateCreator;
using sofa::component::misc::ReadStateActivator;
using sofa::simulation::tree::TreeSimulation;
using sofa::simulation::graph::DAGSimulation;
using sofa::helper::system::SetDirectory;
using sofa::core::objectmodel::BaseNode ;
using sofa::gui::BatchGUI;
using sofa::gui::BaseGUI;

#include <sofa/helper/logging/Messaging.h>

#include <sofa/helper/logging/ConsoleMessageHandler.h>
using sofa::helper::logging::ConsoleMessageHandler ;

#include <sofa/core/logging/RichConsoleStyleMessageFormatter.h>
using  sofa::helper::logging::RichConsoleStyleMessageFormatter ;

#include <sofa/core/logging/PerComponentLoggingMessageHandler.h>
using  sofa::helper::logging::MainPerComponentLoggingMessageHandler ;

#ifdef SOFA_HAVE_GLUT_GUI
#include <sofa/helper/system/glut.h>
#endif // SOFA_HAVE_GLUT_GUI

#ifdef WIN32
#include <windows.h>
#endif

using sofa::helper::system::DataRepository;
using sofa::helper::system::PluginRepository;
using sofa::helper::system::PluginManager;

#include <sofa/helper/logging/MessageDispatcher.h>
using sofa::helper::logging::MessageDispatcher ;

#include <sofa/helper/logging/ClangMessageHandler.h>
using sofa::helper::logging::ClangMessageHandler ;

#include <sofa/helper/logging/ExceptionMessageHandler.h>
using sofa::helper::logging::ExceptionMessageHandler;

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

void loadVerificationData(string& directory, string& filename, Node* node)
{
    msg_info("") << "loadVerificationData from " << directory << " and file " << filename ;

    string refFile;

    refFile += directory;
    refFile += '/';
    refFile += SetDirectory::GetFileName(filename.c_str());

    msg_info("") << "loadVerificationData " << refFile ;

    CompareStateCreator compareVisitor(ExecParams::defaultInstance());
    compareVisitor.setCreateInMapping(true);
    compareVisitor.setSceneName(refFile);
    compareVisitor.execute(node);

    ReadStateActivator v_read(ExecParams::defaultInstance(), true);
    v_read.execute(node);
}

// ---------------------------------------------------------------------
// ---
// ---------------------------------------------------------------------
int main(int argc, char** argv)
{
    sofa::helper::BackTrace::autodump();

    ExecParams::defaultInstance()->setAspectID(0);

#ifdef WIN32
    {
        HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
        COORD s;
        s.X = 160; s.Y = 10000;
        SetConsoleScreenBufferSize(hStdout, s);
        CONSOLE_SCREEN_BUFFER_INFO csbi;
        if (GetConsoleScreenBufferInfo(hStdout, &csbi))
        {
            SMALL_RECT winfo;
            winfo = csbi.srWindow;
            //winfo.Top = 0;
            winfo.Left = 0;
            //winfo.Bottom = csbi.dwSize.Y-1;
            winfo.Right = csbi.dwMaximumWindowSize.X-1;
            SetConsoleWindowInfo(hStdout, TRUE, &winfo);
        }

    }
#endif

    sofa::gui::initMain();

    string fileName ;
    bool        startAnim = false;
    bool        printFactory = false;
    bool        loadRecent = false;
    bool        temporaryFile = false;
    bool        testMode = false;
    bool        noAutoloadPlugins = false;
    int         nbIterations = BatchGUI::DEFAULT_NUMBER_OF_ITERATIONS;
    unsigned int nbMSSASamples = 1;
    unsigned    computationTimeSampling=0; ///< Frequency of display of the computation time statistics, in number of animation steps. 0 means never.

    string gui = "";
    string verif = "";

#if defined(SOFA_HAVE_DAG)
    string simulationType = "dag";
#else
    string simulationType = "tree";
#endif

    vector<string> plugins;
    vector<string> files;
    string colorsStatus = "auto";
    string messageHandler = "auto";
    bool enableInteraction = false ;

    string gui_help = "choose the UI (";
    gui_help += GUIManager::ListSupportedGUI('|');
    gui_help += ")";

    sofa::helper::parse(&files, "This is a SOFA application. Here are the command line arguments")
    // alphabetical order on short name
    .option(&startAnim,'a',"start","start the animation loop")
    .option(&computationTimeSampling,'c',"computationTimeSampling","Frequency of display of the computation time statistics, in number of animation steps. 0 means never.")
    .option(&gui,'g',"gui",gui_help.c_str())
    .option(&plugins,'l',"load","load given plugins")
    .option(&noAutoloadPlugins, '0', "noautoload", "disable plugins autoloading")
    .option(&nbMSSASamples, 'm', "msaa", "number of samples for MSAA (Multi Sampling Anti Aliasing ; value < 2 means disabled")
    .option(&nbIterations,'n',"nb_iterations","(only batch) Number of iterations of the simulation")
    .option(&printFactory,'p',"factory","print factory logs")
    .option(&loadRecent,'r',"recent","load most recently opened file")
    .option(&simulationType,'s',"simu","select the type of simulation (bgl, dag, tree)")
    .option(&temporaryFile,'t',"temporary","the loaded scene won't appear in history of opened files")
    .option(&testMode,'x',"test","select test mode with xml output after N iteration")
    .option(&verif,'v',"verification","load verification data for the scene")
    .option(&colorsStatus,'z',"colors","use colors on stdout and stderr (yes, no, auto)")
    .option(&messageHandler,'f',"formatting","select the message formatting to use (auto, clang, sofa, rich, test)")
    .option(&enableInteraction, 'i', "interactive", "enable interactive mode for the GUI which includes idle and mouse events (EXPERIMENTAL)")
    (argc,argv);

    // Note that initializations must be done after ArgumentParser that can exit the application (without cleanup)
    // even if everything is ok e.g. asking for help
    sofa::simulation::tree::init();
#ifdef SOFA_HAVE_DAG
    sofa::simulation::graph::init();
#endif
    sofa::component::initComponentBase();
    sofa::component::initComponentCommon();
    sofa::component::initComponentGeneral();
    sofa::component::initComponentAdvanced();
    sofa::component::initComponentMisc();

#ifndef SOFA_NO_OPENGL
#ifdef SOFA_HAVE_GLUT_GUI
    if(gui!="batch") glutInit(&argc,argv);
#endif // SOFA_HAVE_GLUT_GUI
#endif // SOFA_NO_OPENGL

#ifdef SOFA_HAVE_DAG
    if (simulationType == "tree")
        sofa::simulation::setSimulation(new TreeSimulation());
    else
        sofa::simulation::setSimulation(new DAGSimulation());
#else //SOFA_HAVE_DAG
    sofa::simulation::setSimulation(new TreeSimulation());
#endif

    if (colorsStatus == "auto")
        Console::setColorsStatus(Console::ColorsAuto);
    else if (colorsStatus == "yes")
        Console::setColorsStatus(Console::ColorsEnabled);
    else if (colorsStatus == "no")
        Console::setColorsStatus(Console::ColorsDisabled);

    //TODO(dmarchal): Use smart pointer there to avoid memory leaks !!
    if (messageHandler == "auto" )
    {
        MessageDispatcher::clearHandlers() ;
        MessageDispatcher::addHandler( new ConsoleMessageHandler() ) ;
    }
    else if (messageHandler == "clang")
    {
        MessageDispatcher::clearHandlers() ;
        MessageDispatcher::addHandler( new ClangMessageHandler() ) ;
    }
    else if (messageHandler == "sofa")
    {
        MessageDispatcher::clearHandlers() ;
        MessageDispatcher::addHandler( new ConsoleMessageHandler() ) ;
    }
    else if (messageHandler == "rich")
    {
        MessageDispatcher::clearHandlers() ;
        MessageDispatcher::addHandler( new ConsoleMessageHandler(new RichConsoleStyleMessageFormatter()) ) ;
    }
    else if (messageHandler == "test"){
        MessageDispatcher::addHandler( new ExceptionMessageHandler() ) ;
    }
    else{
        msg_warning("") << "Invalid argument '" << messageHandler << "' for '--formatting'";
    }
    MessageDispatcher::addHandler(&MainPerComponentLoggingMessageHandler::getInstance()) ;

    // Initialise paths
    BaseGUI::setConfigDirectoryPath(Utils::getSofaPathPrefix() + "/config", true);
    BaseGUI::setScreenshotDirectoryPath(Utils::getSofaPathPrefix() + "/screenshots", true);
    PluginRepository.addFirstPath( Utils::getPluginDirectory() );

    if (!files.empty())
        fileName = files[0];

    for (unsigned int i=0; i<plugins.size(); i++)
        PluginManager::getInstance().loadPlugin(plugins[i]);

    std::string configPluginPath = PluginRepository.getFirstPath() + "/" + TOSTRING(CONFIG_PLUGIN_FILENAME);
    std::string defaultConfigPluginPath = PluginRepository.getFirstPath() + "/" + TOSTRING(DEFAULT_CONFIG_PLUGIN_FILENAME);

    if (!noAutoloadPlugins)
    {
        if (DataRepository.findFile(configPluginPath))
        {
            msg_info("runSofa") << "Loading automatically custom plugin list from " << configPluginPath;
            PluginManager::getInstance().readFromIniFile(configPluginPath);
        }
        else if (DataRepository.findFile(defaultConfigPluginPath))
        {
            msg_info("runSofa") << "Loading automatically default plugin list from " << defaultConfigPluginPath;
            PluginManager::getInstance().readFromIniFile(defaultConfigPluginPath);
        }
        else
            msg_info("runSofa") << "No plugin will be automatically loaded" << msgendl
                                << "- No custom list found at " << configPluginPath << msgendl
                                << "- No default list found at " << defaultConfigPluginPath;
    }
    else
        msg_info("runSofa") << "Automatic plugin loading disabled.";

    PluginManager::getInstance().init();

    if(gui.compare("batch") == 0 && nbIterations >= 0)
    {
        ostringstream oss ;
        oss << "nbIterations=";
        oss << nbIterations;
        GUIManager::AddGUIOption(oss.str().c_str());
    }

    if(enableInteraction){
        msg_warning("Main") << "you activated the interactive mode. This is currently an experimental feature "
                               "that may change or be removed in the future. " ;
        GUIManager::AddGUIOption("enableInteraction");
    }

    if(nbMSSASamples > 1)
    {
        ostringstream oss ;
        oss << "msaa=";
        oss << nbMSSASamples;
        GUIManager::AddGUIOption(oss.str().c_str());
    }

    if (int err = GUIManager::Init(argv[0],gui.c_str()))
        return err;

    if (fileName.empty())
    {
        if (loadRecent) // try to reload the latest scene
        {
            string scenes = BaseGUI::getConfigDirectoryPath() + "/runSofa.ini";
            std::ifstream mrulist(scenes.c_str());
            std::getline(mrulist,fileName);
            mrulist.close();
        }
        else
            fileName = "Demos/caduceus.scn";

        fileName = DataRepository.getFile(fileName);
    }

    if (int err=GUIManager::createGUI(NULL))
        return err;

    //To set a specific resolution for the viewer, use the component ViewerSetting in you scene graph
    GUIManager::SetDimension(800,600);

    Node::SPtr groot = sofa::simulation::getSimulation()->load(fileName.c_str());
    if( !groot )
        groot = sofa::simulation::getSimulation()->createNewGraph("");

    if (!verif.empty())
    {
        loadVerificationData(verif, fileName, groot.get());
    }

    sofa::simulation::getSimulation()->init(groot.get());
    GUIManager::SetScene(groot,fileName.c_str(), temporaryFile);

    //=======================================
    //Apply Options

    if (startAnim)
        groot->setAnimate(true);
    if (printFactory)
    {
        msg_info("") << "////////// FACTORY //////////" ;
        sofa::helper::printFactoryLog();
        msg_info("") << "//////// END FACTORY ////////" ;
    }

    if( computationTimeSampling>0 )
    {
        sofa::helper::AdvancedTimer::setEnabled("Animate", true);
        sofa::helper::AdvancedTimer::setInterval("Animate", computationTimeSampling);
    }

    //=======================================
    // Run the main loop
    if (int err = GUIManager::MainLoop(groot,fileName.c_str()))
        return err;
    groot = dynamic_cast<Node*>( GUIManager::CurrentSimulation() );

    if (testMode)
    {
        string xmlname = fileName.substr(0,fileName.length()-4)+"-scene.scn";
        msg_info("") << "Exporting to XML " << xmlname ;
        sofa::simulation::getSimulation()->exportXML(groot.get(), xmlname.c_str());
    }

    if (groot!=NULL)
        sofa::simulation::getSimulation()->unload(groot);

    GUIManager::closeGUI();

    sofa::simulation::common::cleanup();
    sofa::simulation::tree::cleanup();
#ifdef SOFA_HAVE_DAG
    sofa::simulation::graph::cleanup();
#endif
    return 0;
}
<|endoftext|>