<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library 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 Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: The SOFA Team (see Authors.txt)                                    *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <sofa/core/MultiMapping.inl>
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/defaulttype/RigidTypes.h>

namespace sofa
{

namespace core
{

using namespace sofa::defaulttype;
using namespace core::behavior;

#ifndef SOFA_FLOAT
template class MultiMapping< Vec3dTypes, Vec3dTypes >;
template class MultiMapping< Rigid3dTypes, Vec3dTypes >;
#endif

#ifndef SOFA_DOUBLE
template class MultiMapping< Vec3fTypes, Vec3fTypes >;
template class MultiMapping< Rigid3fTypes, Vec3fTypes >;
#endif

#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class MultiMapping< Vec3dTypes, Vec3fTypes >;
template class MultiMapping< Vec3fTypes, Vec3dTypes > ;
template class MultiMapping< Rigid3dTypes, Vec3fTypes >;
template class MultiMapping< Rigid3fTypes, Vec3dTypes >;
#endif
#endif

} // namespace core

} // namespace sofa
<commit_msg>r10598/sofa : precompiled MultiMapping for Vec1<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library 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 Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: The SOFA Team (see Authors.txt)                                    *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <sofa/core/MultiMapping.inl>
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/defaulttype/RigidTypes.h>

namespace sofa
{

namespace core
{

using namespace sofa::defaulttype;
using namespace core::behavior;

#ifndef SOFA_FLOAT
template class MultiMapping< Vec1dTypes, Vec1dTypes >;
template class MultiMapping< Vec3dTypes, Vec3dTypes >;
template class MultiMapping< Rigid3dTypes, Vec3dTypes >;
#endif

#ifndef SOFA_DOUBLE
template class MultiMapping< Vec1fTypes, Vec1fTypes >;
template class MultiMapping< Vec3fTypes, Vec3fTypes >;
template class MultiMapping< Rigid3fTypes, Vec3fTypes >;
#endif

#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class MultiMapping< Vec1dTypes, Vec1fTypes >;
template class MultiMapping< Vec1fTypes, Vec1dTypes > ;
template class MultiMapping< Vec3dTypes, Vec3fTypes >;
template class MultiMapping< Vec3fTypes, Vec3dTypes > ;
template class MultiMapping< Rigid3dTypes, Vec3fTypes >;
template class MultiMapping< Rigid3fTypes, Vec3dTypes >;
#endif
#endif

} // namespace core

} // namespace sofa
<|endoftext|>


<commit_before>//Made with love by Hadi - Copyright(c) by Hadi Abdi Khojasteh - Summer 2017 until 2018. All right reserved. / Email: hkhojasteh@iasbs.ac.ir, info@hadiabdikhojasteh.ir / Website: iasbs.ac.ir/~hkhojasteh, hadiabdikhojasteh.ir

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/ml/ml.hpp>

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <math.h>
#include <time.h>

using namespace std;
using namespace cv;
using namespace cv::ml;

typedef tuple<char, uint32_t> enumerate;
typedef tuple<double, Mat1d, Mat1d, Mat1d, Mat1d, Mat1d, Mat1d> lossSet;
struct IncGenerator {
	uint32_t current_;
	IncGenerator(uint32_t start) : current_(start) {}
	uint32_t operator() () { return current_++; }
};

vector<uint32_t> sample(Mat1d *, uint32_t, uint32_t);
lossSet lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev);

uint32_t data_size, vocab_size;
Mat1d Wxh, Whh, Why, bh, by;							//model parameters

uint32_t main() {
	srand(time(NULL));

	vector<char> data;
	vector<char> chars;
	vector<enumerate> charenum;
	FILE* inputfile;
	string fileName = "input.txt";
	inputfile = fopen(fileName.c_str(), "r");

	uint32_t i = 0;
	while (!feof(inputfile)) {
		char inchar[1] = { 0 };
		fscanf(inputfile, "%c", inchar);
		if (inchar[0] == 0) {
			continue;
		}
		data.push_back(inchar[0]);

		auto it = find_if(chars.begin(), chars.end(),
			[&](const char element) { return element == inchar[0]; });
		//If this is not in the char set
		if (it == end(chars)) {
			chars.push_back(inchar[0]);
		}
		charenum.push_back(make_tuple(inchar[0], i));
		i++;
	}
	fclose(inputfile);

	data_size = data.size();
	vocab_size = chars.size();
	printf("data has %d characters, %d unique.\n", data_size, vocab_size);
	vector<enumerate> char_to_ix = charenum;
	reverse(charenum.begin(), charenum.end());
	vector<enumerate> ix_to_char = charenum;

	//hyperparameters
	uint32_t hidden_size = 100;							//size of hidden layer of neurons
	uint32_t seq_length = 5;							//number of steps to unroll the RNN for
	double learning_rate = 1e-1;

	Wxh.create(hidden_size, vocab_size);				//Or: Mat mat(2, 4, CV_64FC1);
	Whh.create(hidden_size, hidden_size);
	Why.create(vocab_size, hidden_size);
	double mean = 0.0, stddev = 1.0 / 3.0;				//99.7% of values will be inside [-1, +1] interval
	randn(Wxh, Scalar(mean), Scalar(stddev));			//input to hidden
	randn(Whh, Scalar(mean), Scalar(stddev));			//hidden to hidden
	randn(Why, Scalar(mean), Scalar(stddev));			//hidden to output
	bh = Mat::zeros(hidden_size, 1, CV_32F);			//hidden bias
	by = Mat::zeros(vocab_size, 1, CV_32F);				//output bias

	uint32_t n = 0, p = 0;
	//Make an array of zeros with the same shape and type as a Ws array.
	Mat1d mWxh = Mat::zeros(Wxh.size(), Wxh.type());
	Mat1d mWhh = Mat::zeros(Whh.size(), Whh.type());
	Mat1d mWhy = Mat::zeros(Why.size(), Why.type());
	Mat1d mbh = Mat::zeros(bh.size(), bh.type());		//memory variables for Adagrad
	Mat1d mby = Mat::zeros(by.size(), by.type());		//memory variables for Adagrad
	//loss at iteration 0
	double smooth_loss = -log(1.0 / vocab_size) * seq_length, loss = 0.0;

	Mat1d dWxh, dWhh, dWhy, dbh, dby, hprev;
	vector<enumerate> inputs, targets;
	for (uint32_t i = 0; i < 1e10; i++) {
		//Prepare inputs (we're sweeping from left to right in steps seq_length long)
		if (p + seq_length + 1 >= data.size() || n == 0) {
			hprev = Mat::zeros(hidden_size, 1, CV_32F);	//reset RNN memory
			p = 0;										//go from start of data
		}

		inputs.clear();
		targets.clear();
		for (uint32_t i = 0; i < seq_length && p + i < char_to_ix.size() - 1; i++) {
			inputs.push_back(char_to_ix[p + i]);
			targets.push_back(char_to_ix[p + 1 + i]);
		}

		//Sample from the model now and then
		if (n % 100 == 0) {
			vector<uint32_t> sampWords = sample(&hprev, p + i, 200);
			for (uint32_t i = 0; i < sampWords.size(); i++) {
				printf("%c", get<0>(ix_to_char[sampWords[i]]));
			}
		}

		lossSet d = lossFun(inputs, targets, hprev);
		loss = get<0>(d);
		dWxh = get<1>(d);
		dWhh = get<2>(d);
		dWhy = get<3>(d);
		dbh = get<4>(d);
		dby = get<5>(d);
		hprev = get<6>(d);

		smooth_loss = smooth_loss * 0.999 + loss * 0.001;
		if (n % 100 == 0) {
			printf("\niter %d, loss: %f\n", n, smooth_loss);
		}

		//perform parameter update with Adagrad
		cv::sqrt(dWxh, mWxh);
		cv::sqrt(dWhh, mWhh);
		cv::sqrt(dWhy, mWhy);
		cv::sqrt(dbh, mbh);
		cv::sqrt(dby, mby);
		cout << dby << endl << endl << mby;

		/*Wxh = -learning_rate * dWxh / mWxh;
		Whh = -learning_rate * dWhh / mWhh;
		Why = -learning_rate * dWhy / mWhy;
		bh = -learning_rate * dbh / mbh;
		by = -learning_rate * dby / mby;*/

		p += seq_length;								//move data pointer
		n += 1;											//iteration counter
	}
	return 0;
}

vector<uint32_t> sample(Mat1d * h, uint32_t seed_ix, uint32_t n) {
	//sample a sequence of integers from the model h is memory state,
	//     seed_ix is seed letter for first time step
	Mat1d x = Mat::zeros(vocab_size, 1, CV_32F);
	x[seed_ix][0] = 1.0;
	vector<uint32_t> ixes;
	for (uint32_t i = 0; i < n; i++) {
		Mat1d t = (Wxh * x) + (Whh * (*h)) + bh;
		(*h) = Mat::zeros(t.size(), t.type());
		for (uint32_t i = 0; i < t.rows; i++) {
			(*h)[i][0] = tanh(t[i][0]);
		}
		Mat1d y = (Why * (*h)) + by;
		Mat1d expy;
		exp(y, expy);
		Mat1d p = expy / sum(expy)[0];
		p = p.reshape(1, 1);

		//Generates a random sample from a given 1-D array
		default_random_engine generator;
		discrete_distribution<int> distribution(p.begin(), p.end());
		vector<double> indices(p.size().width);
		generate(indices.begin(), indices.end(), [&generator, &distribution]() { return distribution(generator); });
		vector<int> incNumbers(p.size().width);
		IncGenerator gi(0);
		generate(incNumbers.begin(), incNumbers.end(), gi);
		Mat1d x = Mat::zeros(vocab_size, 1, CV_32F);
		int randSelect = (uint32_t)rand() % vocab_size;
		x[randSelect][0] = 1.0;
		ixes.push_back(randSelect);
	}
	return ixes;
}

lossSet lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev) {
	//inputs, targets are both list of integers.
	//     hprev is Hx1 array of initial hidden state
	//     returns the loss, gradients on model parameters, and last hidden state
	Mat1d xs;
	Mat1d hs = Mat::zeros(hprev.rows, 1, hprev.type());
	hs = hprev;

	double loss = 0.0;
	//ps = Mat::zeros(ys.size(), ys.type());
	Mat1d ps = Mat::zeros(Why.rows, 0, Why.type());;
	//forward pass
	for (uint32_t t = 0; t < inputs.size(); t++) {
		//encode in 1-of-k
		xs = Mat::zeros(inputs.size(), vocab_size, CV_32F);
		xs[t][get<1>(inputs[t])] = 1;

		//calculate hidden state matrix (hidden x vocab_size)
		if(t != inputs.size() - 1){
			Mat1d val = (Wxh * xs.row(t).t());
			Mat1d hsTemp = Mat::zeros(hs.rows, 1, hs.type());
			//because of hs[-1] = np.copy(hprev) we must:
			hsTemp[0][0] = tanh(val[0][0]);
			Mat1d temp = (Whh * hprev[0][0]);
			hsTemp[0][0] += temp[0][0] + bh[0][0];

			for (uint32_t i = 1; i < val.rows; i++) {
				hsTemp[i][0] = tanh(val[i][0]);
				Mat1d temp = (Whh * hsTemp[i - 1][0]);
				hsTemp[i][0] += temp[i][0] + bh[i][0];			//hidden state
			}
			hconcat(hs, hsTemp, hs);
		}

		//unnormalized log probabilities for next chars
		Mat1d ys = (Why * hs[0][t]);// +by[t][0];				//unnormalized log probabilities for next chars
		//probabilities for next chars
		//cout << endl << "sum of array " << sum(ys.row(t))[0] << endl;

		Mat1d ysexp = Mat::zeros(hs.size(), hs.type());
		exp(ys.col(t), ysexp);
		hconcat(ps, ysexp / sum(ys.col(t))[0], ps);

		Mat1d pslog = Mat::zeros(ps.size(), ps.type());
		log(ps, pslog);
		for (int32_t i = get<1>(targets[t]); i >= 0; i--) {
			loss += pslog[t][i];			//softmax (cross-entropy loss)
		}
	}
	//backward pass: compute gradients going backwards
	Mat1d dWxh = Mat::zeros(Wxh.size(), Wxh.type());
	Mat1d dWhh = Mat::zeros(Whh.size(), Whh.type());
	Mat1d dWhy = Mat::zeros(Why.size(), Why.type());
	Mat1d dbh = Mat::zeros(bh.size(), bh.type());
	Mat1d dby = Mat::zeros(by.size(), by.type());
	Mat1d dhnext = Mat::zeros(hs.rows, 1, hs.type());
	for (int32_t t = inputs.size() - 1; t > 0; t--){
		//compute derivative of error w.r.t the output probabilites - dE/dy[j] = y[j] - t[j]
		Mat1d dy = Mat::zeros(0, ps.cols, ps.type());
		dy.push_back(ps.col(t));
		dy[get<1>(targets[t])][0] -= 1;						//backprop into y
		dWhy += dy * hs.col(t).t();
		dby += dy;

		//cout << sum(dWhy) << endl << dby << endl << endl;

		Mat1d dh = (Why.t() * dy) + dhnext;					//backprop into h
		Mat1d dhraw = (1 - (hs[t][0] * hs[t][0])) * dh;		//backprop through tanh nonlinearity
		dbh += dhraw;
		dWxh += dhraw * xs.row(t);
		dWhh += dhraw * hs.col(t).t();
		dhnext = Whh.t() * dhraw;
	}
	//ToDo: Clip dWxh, dWhh, dWhy, dbh, dby matrices between -5, 5
	return make_tuple(loss, dWxh, dWhh, dWhy, dbh, dby, hs.col(inputs.size() - 1));
}
<commit_msg>findWord function added updateAdagrad function added charenum initialization changed inputs and targets initialization changed update parameters after loss function loss function fixed<commit_after>//Made with love by Hadi - Copyright(c) by Hadi Abdi Khojasteh - 2017-2018. All right reserved. / Email: hkhojasteh@iasbs.ac.ir, info@hadiabdikhojasteh.ir / Website: iasbs.ac.ir/~hkhojasteh, hadiabdikhojasteh.ir

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/ml/ml.hpp>

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <math.h>
#include <time.h>

using namespace std;
using namespace cv;
using namespace cv::ml;

typedef tuple<char, uint32_t> enumerate;
typedef tuple<double, Mat1d, Mat1d, Mat1d, Mat1d, Mat1d, Mat1d> lossSet;
struct IncGenerator {
	uint32_t current_;
	IncGenerator(uint32_t start) : current_(start) {}
	uint32_t operator() () { return current_++; }
};

enumerate findWord(vector<enumerate>, char);
void updateAdagrad(Mat1d *, Mat1d *, Mat1d *);
vector<uint32_t> sample(Mat1d *, uint32_t, uint32_t);
lossSet lossFun(vector<enumerate>, vector<enumerate>, Mat1d);

uint32_t data_size, vocab_size;
Mat1d Wxh, Whh, Why, bh, by;							//model parameters

//hyperparameters
uint32_t hidden_size = 100;							//size of hidden layer of neurons
uint32_t seq_length = 5;							//number of steps to unroll the RNN for
double learning_rate = 1e-1;

uint32_t main() {
	srand(time(NULL));

	vector<char> data;
	vector<char> chars;
	vector<enumerate> charenum;
	FILE* inputfile;
	string fileName = "input.txt";
	inputfile = fopen(fileName.c_str(), "r");

	uint32_t i = 0;
	while (!feof(inputfile)) {
		char inchar[1] = { 0 };
		fscanf(inputfile, "%c", inchar);
		if (inchar[0] == 0) {
			continue;
		}
		data.push_back(inchar[0]);

		auto it = find_if(chars.begin(), chars.end(),
			[&](const char element) { return element == inchar[0]; });
		//If this is not in the char set
		if (it == end(chars)) {
			chars.push_back(inchar[0]);
			charenum.push_back(make_tuple(inchar[0], i));
		}
		i++;
	}
	fclose(inputfile);

	data_size = data.size();
	vocab_size = chars.size();
	printf("data has %d characters, %d unique.\n", data_size, vocab_size);
	vector<enumerate> char_to_ix = charenum;
	//reverse(charenum.begin(), charenum.end());
	//vector<enumerate> ix_to_char = charenum;

	Wxh.create(hidden_size, vocab_size);				//Or: Mat mat(2, 4, CV_64FC1);
	Whh.create(hidden_size, hidden_size);
	Why.create(vocab_size, hidden_size);
	double mean = 0.0, stddev = 1.0 / 3.0;				//99.7% of values will be inside [-1, +1] interval
	randn(Wxh, Scalar(mean), Scalar(stddev));			//input to hidden
	randn(Whh, Scalar(mean), Scalar(stddev));			//hidden to hidden
	randn(Why, Scalar(mean), Scalar(stddev));			//hidden to output
	bh = Mat::zeros(hidden_size, 1, CV_32F);			//hidden bias
	by = Mat::zeros(vocab_size, 1, CV_32F);				//output bias

	uint32_t n = 0, p = 0;
	//Make an array of zeros with the same shape and type as a Ws array.
	Mat1d mWxh = Mat::zeros(Wxh.size(), Wxh.type());
	Mat1d mWhh = Mat::zeros(Whh.size(), Whh.type());
	Mat1d mWhy = Mat::zeros(Why.size(), Why.type());
	Mat1d mbh = Mat::zeros(bh.size(), bh.type());		//memory variables for Adagrad
	Mat1d mby = Mat::zeros(by.size(), by.type());		//memory variables for Adagrad
	//loss at iteration 0
	double smooth_loss = -log(1.0 / vocab_size) * seq_length, loss = 0.0;

	Mat1d hprev;
	vector<enumerate> inputs, targets;
	for (uint32_t i = 0; i < 1e10; i++) {
		//Prepare inputs (we're sweeping from left to right in steps seq_length long)
		if (p + seq_length + 1 >= data.size() || n == 0) {
			hprev = Mat::zeros(hidden_size, 1, CV_32F);	//reset RNN memory
			p = 0;										//go from start of data
		}

		inputs.clear();
		targets.clear();
		for (uint32_t i = 0; i < seq_length && p + i + 1 < data.size() - 1; i++) {
			inputs.push_back(findWord(char_to_ix, data[p + i]));
			targets.push_back(findWord(char_to_ix, data[p + 1 + i]));
		}

		//Sample from the model now and then
		if (n % 100 == 0) {
			vector<uint32_t> sampWords = sample(&hprev, p + i, 200);
			for (uint32_t i = 0; i < sampWords.size(); i++) {
				printf("%c", get<0>(char_to_ix[sampWords[i]]));
			}
			printf("\n");
		}

		lossSet d = lossFun(inputs, targets, hprev);
		loss = get<0>(d);
		Mat1d dWxh, dWhh, dWhy, dbh, dby;
		dWxh = get<1>(d);
		dWhh = get<2>(d);
		dWhy = get<3>(d);
		dbh = get<4>(d);
		dby = get<5>(d);
		hprev = get<6>(d);

		smooth_loss = smooth_loss * 0.999 + loss * 0.001;
		if (n % 100 == 0) {
			printf("\niter %d, loss: %f\n", n, smooth_loss);
		}
		/*Wxh = dWxh;
		Whh = dWhh;
		Why = dWhy;

		bh = dbh;
		by = dby;*/

		//perform parameter update with Adagrad
		updateAdagrad(&Wxh, &dWxh, &mWxh);
		updateAdagrad(&Whh, &dWhh, &mWhh);
		updateAdagrad(&Why, &dWhy, &mWhy);
		updateAdagrad(&bh, &dbh, &mbh);
		updateAdagrad(&by, &dby, &mby);

		p += seq_length;								//move data pointer
		n += 1;											//iteration counter
	}
	return 0;
}

enumerate findWord(vector<enumerate> char_to_ix, char ichar) {
	uint32_t index = -1;
	auto it = find_if(char_to_ix.begin(), char_to_ix.end(),
		[&](const enumerate element) { return get<0>(element) == ichar; });
	if (it != end(char_to_ix)) {
		index = get<1>(*it);
	}
	return make_tuple(ichar, index);
}

void updateAdagrad(Mat1d * param, Mat1d * dparam, Mat1d * mem) {
	Mat1d powdparam;
	pow((*dparam), 2, powdparam);
	(*mem) += powdparam;
	(*param) += -learning_rate * (*dparam);
}

vector<uint32_t> sample(Mat1d * h, uint32_t seed_ix, uint32_t n) {
	//sample a sequence of integers from the model h is memory state, seed_ix is seed letter for first time step
	//h is changed in calling this function beacuse of hprev in main
	Mat1d x = Mat::zeros(vocab_size, 1, CV_32F);
	x[seed_ix][0] = 1.0;
	vector<uint32_t> ixes;
	for (uint32_t i = 0; i < n; i++) {
		Mat1d t = (Wxh * x) + (Whh * (*h)) + bh;
		(*h) = Mat::zeros(t.size(), t.type());
		for (uint32_t i = 0; i < t.rows; i++) {
			(*h)[i][0] = tanh(t[i][0]);
		}
		Mat1d y = (Why * (*h)) + by;

		Mat1d expy;
		exp(y, expy);
		Mat1d p = expy / sum(expy)[0];
		p = p.reshape(1, 1);

		//Generates a random sample from a given 1-D array
		/*default_random_engine generator;
		discrete_distribution<int> distribution(p.begin(), p.end());
		vector<double> indices(p.size().width);
		generate(indices.begin(), indices.end(), [&generator, &distribution]() { return distribution(generator); });
		vector<int> incNumbers(p.size().width);
		IncGenerator gi(0);
		generate(incNumbers.begin(), incNumbers.end(), gi);*/
		x = Mat::zeros(vocab_size, 1, CV_32F);
		int randSelect = (uint32_t)rand() % vocab_size;
		x[randSelect][0] = 1.0;
		ixes.push_back(randSelect);
	}
	return ixes;
}

lossSet lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev) {
	//inputs, targets are both list of integers.
	//     hprev is Hx1 array of initial hidden state
	//     returns the loss, gradients on model parameters, and last hidden state
	Mat1d xs = Mat::zeros(inputs.size(), vocab_size, CV_32F);
	Mat1d hs = Mat::zeros(inputs.size(), hprev.rows, hprev.type());
	Mat1d ys = Mat::zeros(vocab_size, 0, hprev.type());

	double loss = 0.0;
	Mat1d ps = Mat::zeros(Why.rows, 0, Why.type());;
	//forward pass
	for (uint32_t t = 0; t < inputs.size(); t++) {
		//encode in 1-of-k
		xs[t][get<1>(inputs[t])] = 1;

		//calculate hidden state matrix (hidden x vocab_size)
		Mat1d val;
		if (t == 0) {
			val = (Wxh * xs.row(t).t()) + (Whh * hprev.col(0)) + bh;
		}else{
			val = (Wxh * xs.row(t).t()) + (Whh * hs.row(t - 1).t()) + bh;
		}
		for (uint32_t i = 0; i < val.rows; i++) {
			hs[t][i] = tanh(val[i][0]);
		}
		Mat1d ysTemp = (Why * hs.row(t).t()) + by[t][0];				//unnormalized log probabilities for next chars
		hconcat(ys, ysTemp, ys);

		Mat1d expys;
		exp(ys.col(t), expys);											//probabilities for next chars
		hconcat(ps, expys / sum(expys)[0], ps);

		Mat1d logps;
		log(ps, logps);
		for (int32_t i = get<1>(targets[t]) - 1; i >= 0; i--) {
			loss += logps[t][i];										//softmax (cross-entropy loss)
		}
	}
	//backward pass: compute gradients going backwards
	Mat1d dWxh = Mat::zeros(Wxh.size(), Wxh.type());
	Mat1d dWhh = Mat::zeros(Whh.size(), Whh.type());
	Mat1d dWhy = Mat::zeros(Why.size(), Why.type());
	Mat1d dbh = Mat::zeros(bh.size(), bh.type());
	Mat1d dby = Mat::zeros(by.size(), by.type());
	Mat1d dhnext = Mat::zeros(hs.cols, 1, hs.type());
	for (int32_t t = inputs.size() - 1; t >= 0; t--){
		//compute derivative of error w.r.t the output probabilites - dE/dy[j] = y[j] - t[j]
		Mat1d dy = ps.col(t);
		dy[get<1>(targets[t])][0] -= 1;						//backprop into y
		dWhy += dy * hs.row(t);
		dby += dy;
		Mat1d dh = (Why.t() * dy) + dhnext;					//backprop into h

		Mat1d powhs;
		pow(hs.row(t), 2, powhs);							//backprop through tanh nonlinearity
		powhs = Mat::ones(powhs.size(), powhs.type()) - powhs;
		Mat1d dhraw = powhs.t().mul(dh);
		dbh += dhraw;
		dWxh += dhraw * xs.row(t);
		if (t == 0) {
			dWhh += dhraw * hprev.col(0).t();
		}else{
			dWhh += dhraw * hs.row(t - 1);
		}
		dhnext = Whh.t() * dhraw;
	}
	//clip to mitigate exploding gradients
	Mat1d tdWxh, tdWhh, tdWhy, tdbh, tdby;
	threshold(dWxh, tdWxh, 5.0, 5, THRESH_TRUNC);
	threshold(dWxh, tdWxh, -5.0, -5, THRESH_BINARY_INV);
	threshold(dWhh, tdWhh, 5.0, 5, THRESH_TRUNC);
	threshold(dWhh, tdWhh, -5.0, -5, THRESH_BINARY_INV);
	threshold(dWhy, tdWhy, 5.0, 5, THRESH_TRUNC);
	threshold(dWhy, tdWhy, -5.0, -5, THRESH_BINARY_INV);
	threshold(dbh, tdbh, 5.0, 5, THRESH_TRUNC);
	threshold(dbh, tdbh, -5.0, -5, THRESH_BINARY_INV);
	threshold(dby, tdby, 5.0, 5, THRESH_TRUNC);
	threshold(dby, tdby, -5.0, -5, THRESH_BINARY_INV);

	return make_tuple(loss, tdWxh, tdWhh, tdWhy, tdbh, tdby, hs.row(inputs.size() - 1).t());
}
<|endoftext|>


<commit_before>#include "pacman_vision/kinect2_processor.h"
#include <array>

Kinect2Processor::Kinect2Processor () : device(0), packetPipeline(0), registration(0),
  listener(0), started(false), initialized(false)
{
  undistorted = new libfreenect2::Frame(512, 424, 4);
  registered = new libfreenect2::Frame(512, 424, 4);
}

bool
Kinect2Processor::initDevice ()
{
  if (freenect2.enumerateDevices() <= 0)
  {
    ROS_ERROR("[Kinect2] No Kinect2 devices found");
    return (false);
  }
  //no support for multiple kinects as of now... just get default one.
  std::string serial = freenect2.getDefaultDeviceSerialNumber();

  //Use OpenCL Packet pipeline processor
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
  if (!packetPipeline)
    packetPipeline = new libfreenect2::OpenCLPacketPipeline();
#else
  ROS_ERROR("[Kinect2] LibFreenect2 does not have OpenCL support. Please recompile it with OpenCL support");
  return (false);
#endif

  //Open kinect2
  device = freenect2.openDevice(serial, packetPipeline);
  if (device == 0)
  {
    ROS_ERROR("[Kinect2] Failed to open Kinect2 with serial %s", serial.c_str());
    return (false);
  }

  //create the listener
  listener = new libfreenect2::SyncMultiFrameListener(libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth);
  //and set them
  device->setColorFrameListener(listener);
  device->setIrAndDepthFrameListener(listener);
  //listen to camera parameters
  device->start();
  colorParams = device->getColorCameraParams();
  irParams = device->getIrCameraParams();
  device->stop();

  //init registration
  registration = new libfreenect2::Registration(irParams, colorParams);
  initialized = true;
  return (true);
}

void
Kinect2Processor::processData()
{
  //assume kinect2 is started and initialized
  listener->waitForNewFrame(frames);
  colorFrame = frames[libfreenect2::Frame::Color];
//  irFrame = frames[libfreenect2::Frame::Ir];
  depthFrame = frames[libfreenect2::Frame::Depth];
  registration->apply(colorFrame, depthFrame, undistorted, registered);
  listener->release(frames);
}

void
Kinect2Processor::computePointCloud(PC::Ptr& out_cloud)
{
  std::array<float, 512*424> X,Y,Z,RGB;
  //assume registration was performed
  out_cloud.reset(new PC);
  out_cloud->width = 512;
  out_cloud->height = 424;
  out_cloud->is_dense = false;
  out_cloud->sensor_origin_.setZero();
  out_cloud->sensor_orientation_.setIdentity();
  out_cloud->points.resize(out_cloud->width * out_cloud->height);
  registration->computeCoordinatesAndColor(undistorted, registered, X,Y,Z,RGB);
  for (size_t i=0; i<out_cloud->points.size(); ++i)
  {
    out_cloud->points[i].x = X[i];
    out_cloud->points[i].y = Y[i];
    out_cloud->points[i].z = Z[i];
    out_cloud->points[i].rgb = RGB[i];
  }
}
<commit_msg>updated createPointCloud function in processor<commit_after>#include "pacman_vision/kinect2_processor.h"
#include <array>

Kinect2Processor::Kinect2Processor () : device(0), packetPipeline(0), registration(0),
  listener(0), started(false), initialized(false)
{
  undistorted = new libfreenect2::Frame(512, 424, 4);
  registered = new libfreenect2::Frame(512, 424, 4);
}

bool
Kinect2Processor::initDevice ()
{
  if (freenect2.enumerateDevices() <= 0)
  {
    ROS_ERROR("[Kinect2] No Kinect2 devices found");
    return (false);
  }
  //no support for multiple kinects as of now... just get default one.
  std::string serial = freenect2.getDefaultDeviceSerialNumber();

  //Use OpenCL Packet pipeline processor
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
  if (!packetPipeline)
    packetPipeline = new libfreenect2::OpenCLPacketPipeline();
#else
  ROS_ERROR("[Kinect2] LibFreenect2 does not have OpenCL support. Please recompile it with OpenCL support");
  return (false);
#endif

  //Open kinect2
  device = freenect2.openDevice(serial, packetPipeline);
  if (device == 0)
  {
    ROS_ERROR("[Kinect2] Failed to open Kinect2 with serial %s", serial.c_str());
    return (false);
  }

  //create the listener
  listener = new libfreenect2::SyncMultiFrameListener(libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth);
  //and set them
  device->setColorFrameListener(listener);
  device->setIrAndDepthFrameListener(listener);
  //listen to camera parameters
  device->start();
  colorParams = device->getColorCameraParams();
  irParams = device->getIrCameraParams();
  device->stop();

  //init registration
  registration = new libfreenect2::Registration(irParams, colorParams);
  initialized = true;
  return (true);
}

void
Kinect2Processor::processData()
{
  //assume kinect2 is started and initialized
  listener->waitForNewFrame(frames);
  colorFrame = frames[libfreenect2::Frame::Color];
//  irFrame = frames[libfreenect2::Frame::Ir];
  depthFrame = frames[libfreenect2::Frame::Depth];
  registration->apply(colorFrame, depthFrame, undistorted, registered);
  listener->release(frames);
}

void
Kinect2Processor::computePointCloud(PC::Ptr& out_cloud)
{
  //assume registration was performed
  out_cloud.reset(new PC);
  out_cloud->width = 512;
  out_cloud->height = 424;
  out_cloud->is_dense = false;
  out_cloud->sensor_origin_.setZero();
  out_cloud->sensor_orientation_.setIdentity();
  out_cloud->points.resize(out_cloud->width * out_cloud->height);
  for (int r=0; r<out_cloud->height; ++r)
  {
    for (int c=0; c<out_cloud->width; ++c)
    {
      unsigned int rgb;
      registration->getPointXYZRGB(undistorted, registered, r,c, out_cloud->points[512*r+c].x,
          out_cloud->points[512*r+c].y, out_cloud->points[512*r+c].z, rgb);
      out_cloud->points[512*r+c].rgb = *reinterpret_cast<float*>(&rgb);
    }
  }
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2010 James Bremner, Raven's Point Consulting, ravenspoint@yahoo.com

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
#include <iomanip>
#include <fstream>
#ifndef raven_set_crunwatch
#include "cRunWatch.h"
#endif
using namespace std;
using namespace boost::accumulators;

namespace raven
{
namespace set
{

int cRunWatch::myFlagProfiling = 0;
map < string, accumulator_set<double, stats<tag::variance(lazy)> > > cRunWatch::myMap;
int cRunWatch::myFlagDaisyChain;
boost::thread_specific_ptr< std::vector< std::string * > > cRunWatch::myDaisyChain;

boost::mutex cRavenProfileMutex;

cRunWatch::cRunWatch( const char* name )
{
    if( myFlagProfiling )
    {
        myFlagTimer = 1;
        myName = std::string( name );
        QueryPerformanceCounter( (LARGE_INTEGER *)&myTimeStart );
    }
    else
    {
        myFlagTimer = 0;
    }

    if( myFlagDaisyChain )
    {
        // using daisy chain feature
        if( ! myDaisyChain.get() )
        {
            // first time called by this thread
            // construct daisy chain to be used in all subsequent calls from this thread
            myDaisyChain.reset( new std::vector< std::string * > );
        }
        // add name of this watcher to the end of the daisy chain
        myDaisyChain->push_back( &myName );

    }
}

/**

  Destructor

  If the timer is running, stop timer and store in accumulator

*/
cRunWatch::~cRunWatch()
{
    // check timer is running
    if( ! myFlagTimer )
        return;

    // get duration of this scope
    __int64 t;
    QueryPerformanceCounter( (LARGE_INTEGER *)&t );
    t -= myTimeStart;

    // name of accumulator where this runtime will be added
    // unless daisy chain is being used, simply the name of the watcher
    std::string acc_name( myName );

    if( myFlagDaisyChain )
    {
        // using daisy chain feature

        // loop through the daisy chain
        // ( list of cuurrently running watcher names in this thread )
        // to build the name of the accumulator
        acc_name = "";
        for( std::vector< std::string * >::iterator it = myDaisyChain->begin();
                it != myDaisyChain->end(); it++ )
        {
            acc_name += **it + '/';
        }

        // remove name of this watcher from the daisy chain
        myDaisyChain->pop_back();
    }

    // ensure that no other thread is updating accumulors
    boost::mutex::scoped_lock
    lock(cRavenProfileMutex);

    // find accumulator for this scope
    map_iter_t p = myMap.find( acc_name );
    if( p == myMap.end() )
    {
        // this is the first time this scope has run
        p = myMap.insert( pair<string,acc_t > (acc_name, acc_t()) ).first;
    }
    // add the time of running to the accumulator for this scope
    (p->second)( (double) t );

}
/**

  Extract statistics from accumulator

  @param[in] f clock frequency
  @param[in] p iterator into map of accumumators

*/
void cRunWatch::Tally(__int64& f, map_iter_t& p)
{
    aver	= ( (float) mean(p->second) / f );
    //stdev	= ( (float) sqrt( ((double) variance(p->second))  ) / f );
    count	= ( boost::accumulators::count(p->second) );
    myTotalTime = count * aver;

}

FILE * cRunWatch::fp;

string cRunWatch::Print() const
{
    stringstream s;
    s << setw(8) << count
        << "\t" << aver
        << "\t" << count*aver
        << "\t" <<  myName << "\n";
    return s.str();
}

/**

  Generate profile report

  @param[in] filename Name of result log file to create, default standard out
  @return the report in a string

  This is a static function, so it can be invoked without an instance of the profiler.

*/
string cRunWatch::Report( const char * filename )
{
    if( ! myFlagProfiling )
    {
        return "";
    }

    // number of ticks per second
    __int64 f;
    QueryPerformanceFrequency( (LARGE_INTEGER *)&f );

    // extract final statistics for all scopes
    multiset < cRunWatch,less<cRunWatch> > sdata;
    for( map_iter_t p = myMap.begin();
            p != myMap.end(); p++ )
    {
        sdata.insert( cRunWatch( p, f ) );
    }

    // format report
    stringstream s;
    s << "raven::set::cRunWatch code timing profile\n";
    s << "Calls\t\tMean (secs)\tTotal\t\tScope\n";
    for( auto& w : sdata )
    {
        s << w.Print();
    }

    cout << s.str();

    if( filename )
    {
        ofstream ofs( filename );
        if( ofs ) {
            ofs << s.str();
        }
    }

    return s.str();
}

}
}
<commit_msg>cRunWatch.cpp includes iostream<commit_after>/*

Copyright (c) 2010 James Bremner, Raven's Point Consulting, ravenspoint@yahoo.com

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
#include <iomanip>
#include <iostream>
#include <fstream>
#ifndef raven_set_crunwatch
#include "cRunWatch.h"
#endif
using namespace std;
using namespace boost::accumulators;

namespace raven
{
namespace set
{

int cRunWatch::myFlagProfiling = 0;
map < string, accumulator_set<double, stats<tag::variance(lazy)> > > cRunWatch::myMap;
int cRunWatch::myFlagDaisyChain;
boost::thread_specific_ptr< std::vector< std::string * > > cRunWatch::myDaisyChain;

boost::mutex cRavenProfileMutex;

cRunWatch::cRunWatch( const char* name )
{
    if( myFlagProfiling )
    {
        myFlagTimer = 1;
        myName = std::string( name );
        QueryPerformanceCounter( (LARGE_INTEGER *)&myTimeStart );
    }
    else
    {
        myFlagTimer = 0;
    }

    if( myFlagDaisyChain )
    {
        // using daisy chain feature
        if( ! myDaisyChain.get() )
        {
            // first time called by this thread
            // construct daisy chain to be used in all subsequent calls from this thread
            myDaisyChain.reset( new std::vector< std::string * > );
        }
        // add name of this watcher to the end of the daisy chain
        myDaisyChain->push_back( &myName );

    }
}

/**

  Destructor

  If the timer is running, stop timer and store in accumulator

*/
cRunWatch::~cRunWatch()
{
    // check timer is running
    if( ! myFlagTimer )
        return;

    // get duration of this scope
    __int64 t;
    QueryPerformanceCounter( (LARGE_INTEGER *)&t );
    t -= myTimeStart;

    // name of accumulator where this runtime will be added
    // unless daisy chain is being used, simply the name of the watcher
    std::string acc_name( myName );

    if( myFlagDaisyChain )
    {
        // using daisy chain feature

        // loop through the daisy chain
        // ( list of cuurrently running watcher names in this thread )
        // to build the name of the accumulator
        acc_name = "";
        for( std::vector< std::string * >::iterator it = myDaisyChain->begin();
                it != myDaisyChain->end(); it++ )
        {
            acc_name += **it + '/';
        }

        // remove name of this watcher from the daisy chain
        myDaisyChain->pop_back();
    }

    // ensure that no other thread is updating accumulors
    boost::mutex::scoped_lock
    lock(cRavenProfileMutex);

    // find accumulator for this scope
    map_iter_t p = myMap.find( acc_name );
    if( p == myMap.end() )
    {
        // this is the first time this scope has run
        p = myMap.insert( pair<string,acc_t > (acc_name, acc_t()) ).first;
    }
    // add the time of running to the accumulator for this scope
    (p->second)( (double) t );

}
/**

  Extract statistics from accumulator

  @param[in] f clock frequency
  @param[in] p iterator into map of accumumators

*/
void cRunWatch::Tally(__int64& f, map_iter_t& p)
{
    aver	= ( (float) mean(p->second) / f );
    //stdev	= ( (float) sqrt( ((double) variance(p->second))  ) / f );
    count	= ( boost::accumulators::count(p->second) );
    myTotalTime = count * aver;

}

FILE * cRunWatch::fp;

string cRunWatch::Print() const
{
    stringstream s;
    s << setw(8) << count
        << "\t" << aver
        << "\t" << count*aver
        << "\t" <<  myName << "\n";
    return s.str();
}

/**

  Generate profile report

  @param[in] filename Name of result log file to create, default standard out
  @return the report in a string

  This is a static function, so it can be invoked without an instance of the profiler.

*/
string cRunWatch::Report( const char * filename )
{
    if( ! myFlagProfiling )
    {
        return "";
    }

    // number of ticks per second
    __int64 f;
    QueryPerformanceFrequency( (LARGE_INTEGER *)&f );

    // extract final statistics for all scopes
    multiset < cRunWatch,less<cRunWatch> > sdata;
    for( map_iter_t p = myMap.begin();
            p != myMap.end(); p++ )
    {
        sdata.insert( cRunWatch( p, f ) );
    }

    // format report
    stringstream s;
    s << "raven::set::cRunWatch code timing profile\n";
    s << "Calls\t\tMean (secs)\tTotal\t\tScope\n";
    for( auto& w : sdata )
    {
        s << w.Print();
    }

    cout << s.str();

    if( filename )
    {
        ofstream ofs( filename );
        if( ofs ) {
            ofs << s.str();
        }
    }

    return s.str();
}

}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cairo_cairo.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-17 14:19:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_canvas.hxx"
#include <X11/extensions/Xrender.h>
#include <X11/Xlib.h>
#include "cairo_cairo.hxx"
#include "cairo_helper.hxx"

namespace cairo
{

#include <cairo-xlib.h>
#include <cairo-xlib-xrender.h>

  /**
   * Surface::Surface:   Create Canvas surface with existing data
   * @param pSysData Platform native system environment data (struct SystemEnvData in vcl/inc/sysdata.hxx)
   * @param pSurface Cairo surface
   *
   * pSysData contains the platform native Window reference
   * This constructor only stores data, it does no processing.
   * It is used by e.g. Surface::getSimilar()
   *
   * Set the mpSurface as pSurface
   **/
    Surface::Surface( const void* pSysData, void* pDisplay, long hDrawable, void* pRenderFormat, cairo_surface_t* pSurface )
        : mpSysData( pSysData ),
          mpDisplay( pDisplay ),
          mhDrawable( hDrawable ),
          mpRenderFormat( pRenderFormat ),
          mnRefCount( 1 ),
          mbFreePixmap( true ),
          mpSurface( pSurface )
    {
    }

  /**
   * Surface::Surface:     Create generic Canvas surface using given Cairo Surface
   *
   * @param pSurface Cairo Surface
   *
   * This constructor only stores data, it does no processing.
   * It is used with e.g. cairo_image_surface_create_for_data()
   * Unlike other constructors, mpSysData is set to NULL
   *
   * Set the mpSurface as pSurface
   **/
    Surface::Surface( cairo_surface_t* pSurface )
        : mpSysData( NULL ),
          mpDisplay( NULL ),
          mhDrawable( 0 ),
          mpRenderFormat( NULL ),
          mnRefCount( 1 ),
          mbFreePixmap( false ),
          mpSurface( pSurface )
    {
    }

  /**
   * Surface::Surface:   Create Canvas surface from Window reference.
   * @param pSysData Platform native system environment data (struct SystemEnvData in vcl/inc/sysdata.hxx)
   * @param x horizontal location of the new surface
   * @param y vertical location of the new surface
   * @param width width of the new surface
   * @param height height of the new surface
   *
   * pSysData contains the platform native Window reference.
   *
   * pSysData is used to create a surface on the Window
   *
   * Set the mpSurface to the new surface or NULL
   **/
    Surface::Surface( const void* pSysData, int x, int y, int width, int height )
        : mpSysData( pSysData ),
          mpDisplay( NULL ),
          mhDrawable( 0 ),
          mpRenderFormat( NULL ),
          mnRefCount( 1 ),
          mbFreePixmap( false ),
          mpSurface( NULL )
    {
        mpSurface = (cairo_surface_t*) cairoHelperGetSurface( pSysData, x, y, width, height );
        mpDisplay = (Display*) cairoHelperGetDisplay( pSysData );
        mhDrawable = cairoHelperGetWindow( pSysData );
    }

  /**
   * Surface::Surface:   Create platfrom native Canvas surface from BitmapSystemData
   * @param pSysData Platform native system environment data (struct SystemEnvData in vcl/inc/sysdata.hxx)
   * @param pBmpData Platform native image data (struct BitmapSystemData in vcl/inc/bitmap.hxx)
   * @param width width of the new surface
   * @param height height of the new surface
   *
   * The pBmpData provides the imagedata that the created surface should contain.
   *
   * Set the mpSurface to the new surface or NULL
   **/
    Surface::Surface( const void* pSysData, void *pBmpData, int width, int height )
        : mpSysData( pSysData ),
          mpDisplay( NULL ),
          mhDrawable( 0 ),
          mpRenderFormat( NULL ),
          mnRefCount( 1 ),
          mbFreePixmap( false ),
          mpSurface( NULL )
    {
        mpSurface = (cairo_surface_t*) cairoHelperGetSurface( pSysData, pBmpData, width, height );
        mpDisplay = (Display*) cairoHelperGetDisplay( pSysData );
        mhDrawable = cairoHelperGetWindow( pSysData );
    }

  /**
   * Surface::~Surface:  Destroy the Canvas surface
   *
   * Also free any image data and other references related to the Canvas.
   *
   **/
    Surface::~Surface()
    {
        if( mpSurface )
        {
            cairo_surface_destroy( mpSurface );
            mpSurface = NULL;
        }
        if( mbFreePixmap && mhDrawable )
            XFreePixmap( (Display*) mpDisplay, mhDrawable );
    }

  /**
   * Surface::getCairo:  Create Cairo (drawing object) for the Canvas surface
   *
   * @return new Cairo or NULL
   **/
    Cairo*
    Surface::getCairo()
    {
        return cairo_create( mpSurface );
    }

  /**
   * Surface::getSimilar:  Create new similar Canvas surface
   * @param aContent format of the new surface (cairo_content_t from cairo/src/cairo.h)
   * @param width width of the new surface
   * @param height height of the new surface
   *
   * Creates a new Canvas surface. This normally creates platform native surface, even though
   * generic function is used.
   *
   * Cairo surface from aContent (cairo_content_t)
   *
   * @return new surface or NULL
   **/
    Surface* Surface::getSimilar( Content aContent, int width, int height )
    {
        Pixmap hPixmap;

        if( mpSysData && mpDisplay && mhDrawable ) {
            XRenderPictFormat *pFormat;
            int nFormat;

            switch (aContent) {
            case CAIRO_CONTENT_ALPHA:
                nFormat = PictStandardA8;
                break;
            case CAIRO_CONTENT_COLOR:
                nFormat = PictStandardRGB24;
                break;
            case CAIRO_CONTENT_COLOR_ALPHA:
            default:
                nFormat = PictStandardARGB32;
                break;
            }

            pFormat = XRenderFindStandardFormat( (Display*) mpDisplay, nFormat );
            hPixmap = XCreatePixmap( (Display*) mpDisplay, cairoHelperGetWindow( mpSysData ),
                                     width > 0 ? width : 1, height > 0 ? height : 1,
                                     pFormat->depth );

            return new Surface( mpSysData, mpDisplay, (long) hPixmap, pFormat,
                                cairo_xlib_surface_create_with_xrender_format( (Display*) mpDisplay, hPixmap,
                                                                               DefaultScreenOfDisplay( (Display *) mpDisplay ),
                                                                               pFormat, width, height ) );
        } else
            return new Surface( mpSysData, mpDisplay, 0, NULL, cairo_surface_create_similar( mpSurface, aContent, width, height ) );
    }

  /**
   * Surface::Resize:  Resizes the Canvas surface.
   * @param width new width of the surface
   * @param height new height of the surface
   *
   * Only used on X11.
   *
   * @return The new surface or NULL
   **/
    void
    Surface::Resize( int width, int height )
    {
        cairo_xlib_surface_set_size( mpSurface, width, height );
    }

  /**
   * Surface::getDepth:  Get the color depth of the Canvas surface.
   *
   * @return color depth
   **/
    int
    Surface::getDepth()
    {
        if( mpRenderFormat )
            return ( ( XRenderPictFormat * ) mpRenderFormat )->depth;

        return -1;
    }
}
<commit_msg>INTEGRATION: CWS thbpp10 (1.5.40); FILE MERGED 2008/01/14 15:54:21 thb 1.5.40.1: #i84049# Checking for render existence - patch courtesy jnavrati<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cairo_cairo.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2008-01-29 08:01:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_canvas.hxx"
#include <X11/extensions/Xrender.h>
#include <X11/Xlib.h>
#include "cairo_cairo.hxx"
#include "cairo_helper.hxx"

namespace cairo
{

#include <cairo-xlib.h>
#include <cairo-xlib-xrender.h>

    bool HasXRender( const void* pSysData )
    {
            Display *pDisplay = (Display*) cairoHelperGetDisplay( pSysData );
            int nDummy;
            return XQueryExtension( pDisplay, "RENDER", &nDummy, &nDummy, &nDummy );
    }

  /**
   * Surface::Surface:   Create Canvas surface with existing data
   * @param pSysData Platform native system environment data (struct SystemEnvData in vcl/inc/sysdata.hxx)
   * @param pSurface Cairo surface
   *
   * pSysData contains the platform native Window reference
   * This constructor only stores data, it does no processing.
   * It is used by e.g. Surface::getSimilar()
   *
   * Set the mpSurface as pSurface
   **/
    Surface::Surface( const void* pSysData, void* pDisplay, long hDrawable, void* pRenderFormat, cairo_surface_t* pSurface )
        : mpSysData( pSysData ),
          mpDisplay( pDisplay ),
          mhDrawable( hDrawable ),
          mpRenderFormat( pRenderFormat ),
          mnRefCount( 1 ),
          mbFreePixmap( true ),
          mpSurface( pSurface )
    {
    }

  /**
   * Surface::Surface:     Create generic Canvas surface using given Cairo Surface
   *
   * @param pSurface Cairo Surface
   *
   * This constructor only stores data, it does no processing.
   * It is used with e.g. cairo_image_surface_create_for_data()
   * Unlike other constructors, mpSysData is set to NULL
   *
   * Set the mpSurface as pSurface
   **/
    Surface::Surface( cairo_surface_t* pSurface )
        : mpSysData( NULL ),
          mpDisplay( NULL ),
          mhDrawable( 0 ),
          mpRenderFormat( NULL ),
          mnRefCount( 1 ),
          mbFreePixmap( false ),
          mpSurface( pSurface )
    {
    }

  /**
   * Surface::Surface:   Create Canvas surface from Window reference.
   * @param pSysData Platform native system environment data (struct SystemEnvData in vcl/inc/sysdata.hxx)
   * @param x horizontal location of the new surface
   * @param y vertical location of the new surface
   * @param width width of the new surface
   * @param height height of the new surface
   *
   * pSysData contains the platform native Window reference.
   *
   * pSysData is used to create a surface on the Window
   *
   * Set the mpSurface to the new surface or NULL
   **/
    Surface::Surface( const void* pSysData, int x, int y, int width, int height )
        : mpSysData( pSysData ),
          mpDisplay( NULL ),
          mhDrawable( 0 ),
          mpRenderFormat( NULL ),
          mnRefCount( 1 ),
          mbFreePixmap( false ),
          mpSurface( NULL )
    {
        mpSurface = (cairo_surface_t*) cairoHelperGetSurface( pSysData, x, y, width, height );
        mpDisplay = (Display*) cairoHelperGetDisplay( pSysData );
        mhDrawable = cairoHelperGetWindow( pSysData );
    }

  /**
   * Surface::Surface:   Create platfrom native Canvas surface from BitmapSystemData
   * @param pSysData Platform native system environment data (struct SystemEnvData in vcl/inc/sysdata.hxx)
   * @param pBmpData Platform native image data (struct BitmapSystemData in vcl/inc/bitmap.hxx)
   * @param width width of the new surface
   * @param height height of the new surface
   *
   * The pBmpData provides the imagedata that the created surface should contain.
   *
   * Set the mpSurface to the new surface or NULL
   **/
    Surface::Surface( const void* pSysData, void *pBmpData, int width, int height )
        : mpSysData( pSysData ),
          mpDisplay( NULL ),
          mhDrawable( 0 ),
          mpRenderFormat( NULL ),
          mnRefCount( 1 ),
          mbFreePixmap( false ),
          mpSurface( NULL )
    {
        mpSurface = (cairo_surface_t*) cairoHelperGetSurface( pSysData, pBmpData, width, height );
        mpDisplay = (Display*) cairoHelperGetDisplay( pSysData );
        mhDrawable = cairoHelperGetWindow( pSysData );
    }

  /**
   * Surface::~Surface:  Destroy the Canvas surface
   *
   * Also free any image data and other references related to the Canvas.
   *
   **/
    Surface::~Surface()
    {
        if( mpSurface )
        {
            cairo_surface_destroy( mpSurface );
            mpSurface = NULL;
        }
        if( mbFreePixmap && mhDrawable )
            XFreePixmap( (Display*) mpDisplay, mhDrawable );
    }

  /**
   * Surface::getCairo:  Create Cairo (drawing object) for the Canvas surface
   *
   * @return new Cairo or NULL
   **/
    Cairo*
    Surface::getCairo()
    {
        return cairo_create( mpSurface );
    }

  /**
   * Surface::getSimilar:  Create new similar Canvas surface
   * @param aContent format of the new surface (cairo_content_t from cairo/src/cairo.h)
   * @param width width of the new surface
   * @param height height of the new surface
   *
   * Creates a new Canvas surface. This normally creates platform native surface, even though
   * generic function is used.
   *
   * Cairo surface from aContent (cairo_content_t)
   *
   * @return new surface or NULL
   **/
    Surface* Surface::getSimilar( Content aContent, int width, int height )
    {
        Pixmap hPixmap;

        if( mpSysData && mpDisplay && mhDrawable ) {
            XRenderPictFormat *pFormat;
            int nFormat;

            switch (aContent) {
            case CAIRO_CONTENT_ALPHA:
                nFormat = PictStandardA8;
                break;
            case CAIRO_CONTENT_COLOR:
                nFormat = PictStandardRGB24;
                break;
            case CAIRO_CONTENT_COLOR_ALPHA:
            default:
                nFormat = PictStandardARGB32;
                break;
            }

            pFormat = XRenderFindStandardFormat( (Display*) mpDisplay, nFormat );
            hPixmap = XCreatePixmap( (Display*) mpDisplay, cairoHelperGetWindow( mpSysData ),
                                     width > 0 ? width : 1, height > 0 ? height : 1,
                                     pFormat->depth );

            return new Surface( mpSysData, mpDisplay, (long) hPixmap, pFormat,
                                cairo_xlib_surface_create_with_xrender_format( (Display*) mpDisplay, hPixmap,
                                                                               DefaultScreenOfDisplay( (Display *) mpDisplay ),
                                                                               pFormat, width, height ) );
        } else
            return new Surface( mpSysData, mpDisplay, 0, NULL, cairo_surface_create_similar( mpSurface, aContent, width, height ) );
    }

  /**
   * Surface::Resize:  Resizes the Canvas surface.
   * @param width new width of the surface
   * @param height new height of the surface
   *
   * Only used on X11.
   *
   * @return The new surface or NULL
   **/
    void
    Surface::Resize( int width, int height )
    {
        cairo_xlib_surface_set_size( mpSurface, width, height );
    }

  /**
   * Surface::getDepth:  Get the color depth of the Canvas surface.
   *
   * @return color depth
   **/
    int
    Surface::getDepth()
    {
        if( mpRenderFormat )
            return ( ( XRenderPictFormat * ) mpRenderFormat )->depth;

        return -1;
    }
}
<|endoftext|>


<commit_before>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                                  wxparaver                                *
 *              Paraver Trace Visualization and Analysis Tool                *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "saveconfigurationdialog.h"

////@begin XPM images
////@end XPM images

/*!
 * SaveConfigurationDialog type definition
 */

IMPLEMENT_DYNAMIC_CLASS( SaveConfigurationDialog, wxDialog )

/*!
 * SaveConfigurationDialog event table definition
 */

BEGIN_EVENT_TABLE( SaveConfigurationDialog, wxDialog )

////@begin SaveConfigurationDialog event table entries
  EVT_BUTTON( wxID_SAVE, SaveConfigurationDialog::OnSaveClick )

////@end SaveConfigurationDialog event table entries

END_EVENT_TABLE()

/*!
 * SaveConfigurationDialog constructors
 */

SaveConfigurationDialog::SaveConfigurationDialog()
{
  Init();
}

SaveConfigurationDialog::SaveConfigurationDialog( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
  Init();
  Create(parent, id, caption, pos, size, style);
}

/*!
 * SaveConfigurationDialog creator
 */

bool SaveConfigurationDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin SaveConfigurationDialog creation
  SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
  wxDialog::Create( parent, id, caption, pos, size, style );

  CreateControls();
  if (GetSizer())
  {
    GetSizer()->SetSizeHints(this);
  }
  Centre();
////@end SaveConfigurationDialog creation
  return true;
}

/*!
 * SaveConfigurationDialog destructor
 */

SaveConfigurationDialog::~SaveConfigurationDialog()
{
////@begin SaveConfigurationDialog destruction
////@end SaveConfigurationDialog destruction
}

/*!
 * Member initialisation
 */

void SaveConfigurationDialog::Init()
{
////@begin SaveConfigurationDialog member initialisation
  listTimelines = NULL;
  listHistograms = NULL;
  optRelativeBegin = NULL;
  optRelativeEnd = NULL;
  optComputeSemantic = NULL;
  radioAllTrace = NULL;
  radioAllWindow = NULL;
  optComputeLimits = NULL;
  optComputeGradient = NULL;
  textDescription = NULL;
////@end SaveConfigurationDialog member initialisation
}

/*!
 * Control creation for SaveConfigurationDialog
 */

void SaveConfigurationDialog::CreateControls()
{
////@begin SaveConfigurationDialog content construction
  SaveConfigurationDialog* itemDialog1 = this;

  wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
  itemDialog1->SetSizer(itemBoxSizer2);

  wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer2->Add(itemBoxSizer3, 2, wxGROW|wxALL, 0);

  wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxVERTICAL);
  itemBoxSizer3->Add(itemBoxSizer4, 1, wxGROW|wxALL, 5);

  wxStaticText* itemStaticText5 = new wxStaticText( itemDialog1, wxID_STATIC, _("Timelines"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer4->Add(itemStaticText5, 0, wxALIGN_CENTER_HORIZONTAL|wxLEFT|wxRIGHT|wxTOP, 5);

  wxArrayString listTimelinesStrings;
  listTimelines = new wxCheckListBox( itemDialog1, ID_LISTTIMELINES, wxDefaultPosition, wxSize(200, -1), listTimelinesStrings, wxLB_SINGLE );
  itemBoxSizer4->Add(listTimelines, 1, wxGROW|wxALL, 5);

  wxBoxSizer* itemBoxSizer7 = new wxBoxSizer(wxVERTICAL);
  itemBoxSizer3->Add(itemBoxSizer7, 1, wxGROW|wxALL, 5);

  wxStaticText* itemStaticText8 = new wxStaticText( itemDialog1, wxID_STATIC, _("Histograms"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer7->Add(itemStaticText8, 0, wxALIGN_CENTER_HORIZONTAL|wxLEFT|wxRIGHT|wxTOP, 5);

  wxArrayString listHistogramsStrings;
  listHistograms = new wxCheckListBox( itemDialog1, ID_LISTHISTOGRAMS, wxDefaultPosition, wxSize(200, -1), listHistogramsStrings, wxLB_SINGLE );
  itemBoxSizer7->Add(listHistograms, 1, wxGROW|wxALL, 5);

  wxBoxSizer* itemBoxSizer10 = new wxBoxSizer(wxVERTICAL);
  itemBoxSizer3->Add(itemBoxSizer10, 0, wxGROW|wxALL, 5);

  wxStaticBox* itemStaticBoxSizer11Static = new wxStaticBox(itemDialog1, wxID_ANY, _("Timeline options"));
  wxStaticBoxSizer* itemStaticBoxSizer11 = new wxStaticBoxSizer(itemStaticBoxSizer11Static, wxVERTICAL);
  itemBoxSizer10->Add(itemStaticBoxSizer11, 3, wxGROW|wxALL, 5);

  optRelativeBegin = new wxCheckBox( itemDialog1, ID_CHECKBEGIN, _("Relative begin time"), wxDefaultPosition, wxDefaultSize, 0 );
  optRelativeBegin->SetValue(false);
  itemStaticBoxSizer11->Add(optRelativeBegin, 1, wxALIGN_LEFT|wxALL, 5);

  optRelativeEnd = new wxCheckBox( itemDialog1, ID_CHECKEND, _("Relative end time"), wxDefaultPosition, wxDefaultSize, 0 );
  optRelativeEnd->SetValue(false);
  itemStaticBoxSizer11->Add(optRelativeEnd, 1, wxALIGN_LEFT|wxALL, 5);

  optComputeSemantic = new wxCheckBox( itemDialog1, ID_CHECKSEMANTIC, _("Compute semantic scale"), wxDefaultPosition, wxDefaultSize, 0 );
  optComputeSemantic->SetValue(false);
  itemStaticBoxSizer11->Add(optComputeSemantic, 1, wxALIGN_LEFT|wxALL, 5);

  wxStaticBox* itemStaticBoxSizer15Static = new wxStaticBox(itemDialog1, wxID_ANY, _("Histogram options"));
  wxStaticBoxSizer* itemStaticBoxSizer15 = new wxStaticBoxSizer(itemStaticBoxSizer15Static, wxVERTICAL);
  itemBoxSizer10->Add(itemStaticBoxSizer15, 5, wxGROW|wxALL, 5);

  radioAllTrace = new wxRadioButton( itemDialog1, ID_RADIOALLTRACE, _("All trace"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP );
  radioAllTrace->SetValue(false);
  itemStaticBoxSizer15->Add(radioAllTrace, 1, wxALIGN_LEFT|wxALL, 5);

  radioAllWindow = new wxRadioButton( itemDialog1, ID_RADIOALLWINDOW, _("All window"), wxDefaultPosition, wxDefaultSize, 0 );
  radioAllWindow->SetValue(false);
  itemStaticBoxSizer15->Add(radioAllWindow, 1, wxGROW|wxALL, 5);

  wxStaticLine* itemStaticLine18 = new wxStaticLine( itemDialog1, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
  itemStaticBoxSizer15->Add(itemStaticLine18, 1, wxGROW|wxLEFT|wxRIGHT, 5);

  optComputeLimits = new wxCheckBox( itemDialog1, ID_CHECKLIMITS, _("Compute min, max, delta limits"), wxDefaultPosition, wxDefaultSize, 0 );
  optComputeLimits->SetValue(false);
  itemStaticBoxSizer15->Add(optComputeLimits, 1, wxALIGN_LEFT|wxALL, 5);

  optComputeGradient = new wxCheckBox( itemDialog1, ID_CHECKGRADIENT, _("Compute gradient limits"), wxDefaultPosition, wxDefaultSize, 0 );
  optComputeGradient->SetValue(false);
  itemStaticBoxSizer15->Add(optComputeGradient, 1, wxALIGN_LEFT|wxALL, 5);

  wxStaticText* itemStaticText21 = new wxStaticText( itemDialog1, wxID_STATIC, _("Description"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer2->Add(itemStaticText21, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);

  textDescription = new wxTextCtrl( itemDialog1, ID_TEXTDESCRIPTION, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE );
  itemBoxSizer2->Add(textDescription, 1, wxGROW|wxALL, 5);

  wxStdDialogButtonSizer* itemStdDialogButtonSizer23 = new wxStdDialogButtonSizer;

  itemBoxSizer2->Add(itemStdDialogButtonSizer23, 0, wxALIGN_RIGHT|wxALL, 5);
  wxButton* itemButton24 = new wxButton( itemDialog1, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
  itemStdDialogButtonSizer23->AddButton(itemButton24);

  wxButton* itemButton25 = new wxButton( itemDialog1, wxID_SAVE, _("&Save"), wxDefaultPosition, wxDefaultSize, 0 );
  itemStdDialogButtonSizer23->AddButton(itemButton25);

  itemStdDialogButtonSizer23->Realize();

////@end SaveConfigurationDialog content construction
}

/*!
 * Should we show tooltips?
 */

bool SaveConfigurationDialog::ShowToolTips()
{
  return true;
}

/*!
 * Get bitmap resources
 */

wxBitmap SaveConfigurationDialog::GetBitmapResource( const wxString& name )
{
  // Bitmap retrieval
////@begin SaveConfigurationDialog bitmap retrieval
  wxUnusedVar(name);
  return wxNullBitmap;
////@end SaveConfigurationDialog bitmap retrieval
}

/*!
 * Get icon resources
 */

wxIcon SaveConfigurationDialog::GetIconResource( const wxString& name )
{
  // Icon retrieval
////@begin SaveConfigurationDialog icon retrieval
  wxUnusedVar(name);
  return wxNullIcon;
////@end SaveConfigurationDialog icon retrieval
}

bool SaveConfigurationDialog::TransferDataToWindow()
{
  wxArrayString items;
  for( vector<Window *>::iterator it = timelines.begin(); it != timelines.end(); ++it )
    items.Add( wxString::FromAscii( (*it)->getName().c_str() ) );
  listTimelines->InsertItems( items, 0 );

  items.Clear();
  for( vector<Histogram *>::iterator it = histograms.begin(); it != histograms.end(); ++it )
    items.Add( wxString::FromAscii( (*it)->getName().c_str() ) );
  listHistograms->InsertItems( items, 0 );

  optRelativeBegin->SetValue( options.windowBeginTimeRelative );
  optRelativeEnd->SetValue( options.windowScaleRelative );
  optComputeSemantic->SetValue( options.windowComputeYMaxOnLoad );
  radioAllTrace->SetValue( options.histoAllTrace );
  optComputeLimits->SetValue( options.histoComputeYScale );
  optComputeGradient->SetValue( options.histoComputeGradient );

  return true;
}

bool SaveConfigurationDialog::TransferDataFromWindow()
{
  vector<Window *> tmpTimelines;
  for( size_t i = 0; i < listTimelines->GetCount(); ++i )
  {
    if( listTimelines->IsChecked( i ) )
      tmpTimelines.push_back( timelines[ i ] );
  }
  timelines.clear();
  timelines = tmpTimelines;

  vector<Histogram *> tmpHistograms;
  for( size_t i = 0; i < listHistograms->GetCount(); ++i )
  {
    if( listHistograms->IsChecked( i ) )
      tmpHistograms.push_back( histograms[ i ] );
  }
  histograms.clear();
  histograms = tmpHistograms;

  options.windowBeginTimeRelative = optRelativeBegin->GetValue();
  options.windowScaleRelative = optRelativeEnd->GetValue();
  options.windowComputeYMaxOnLoad = optComputeSemantic->GetValue();
  options.histoAllTrace = radioAllTrace->GetValue();
  options.histoComputeYScale = optComputeLimits->GetValue();
  options.histoComputeGradient = optComputeGradient->GetValue();
  options.description = std::string( textDescription->GetValue().mb_str() );

  return true;
}

/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_SAVE
 */

void SaveConfigurationDialog::OnSaveClick( wxCommandEvent& event )
{
  TransferDataFromWindow();
  if( timelines.begin() == timelines.end() &&
      histograms.begin() == histograms.end() )
    EndModal( wxID_OK );//EndModal( wxID_CANCEL );
  else
    EndModal( wxID_OK );
}

<commit_msg>*** empty log message ***<commit_after>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                                  wxparaver                                *
 *              Paraver Trace Visualization and Analysis Tool                *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "saveconfigurationdialog.h"

////@begin XPM images
////@end XPM images

/*!
 * SaveConfigurationDialog type definition
 */

IMPLEMENT_DYNAMIC_CLASS( SaveConfigurationDialog, wxDialog )

/*!
 * SaveConfigurationDialog event table definition
 */

BEGIN_EVENT_TABLE( SaveConfigurationDialog, wxDialog )

////@begin SaveConfigurationDialog event table entries
  EVT_BUTTON( wxID_SAVE, SaveConfigurationDialog::OnSaveClick )

////@end SaveConfigurationDialog event table entries

END_EVENT_TABLE()

/*!
 * SaveConfigurationDialog constructors
 */

SaveConfigurationDialog::SaveConfigurationDialog()
{
  Init();
}

SaveConfigurationDialog::SaveConfigurationDialog( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
  Init();
  Create(parent, id, caption, pos, size, style);
}

/*!
 * SaveConfigurationDialog creator
 */

bool SaveConfigurationDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin SaveConfigurationDialog creation
  SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
  wxDialog::Create( parent, id, caption, pos, size, style );

  CreateControls();
  if (GetSizer())
  {
    GetSizer()->SetSizeHints(this);
  }
  Centre();
////@end SaveConfigurationDialog creation
  return true;
}

/*!
 * SaveConfigurationDialog destructor
 */

SaveConfigurationDialog::~SaveConfigurationDialog()
{
////@begin SaveConfigurationDialog destruction
////@end SaveConfigurationDialog destruction
}

/*!
 * Member initialisation
 */

void SaveConfigurationDialog::Init()
{
////@begin SaveConfigurationDialog member initialisation
  listTimelines = NULL;
  listHistograms = NULL;
  optRelativeBegin = NULL;
  optRelativeEnd = NULL;
  optComputeSemantic = NULL;
  radioAllTrace = NULL;
  radioAllWindow = NULL;
  optComputeLimits = NULL;
  optComputeGradient = NULL;
  textDescription = NULL;
////@end SaveConfigurationDialog member initialisation
}

/*!
 * Control creation for SaveConfigurationDialog
 */

void SaveConfigurationDialog::CreateControls()
{
////@begin SaveConfigurationDialog content construction
  SaveConfigurationDialog* itemDialog1 = this;

  wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
  itemDialog1->SetSizer(itemBoxSizer2);

  wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxHORIZONTAL);
  itemBoxSizer2->Add(itemBoxSizer3, 2, wxGROW|wxALL, 0);

  wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxVERTICAL);
  itemBoxSizer3->Add(itemBoxSizer4, 1, wxGROW|wxALL, 5);

  wxStaticText* itemStaticText5 = new wxStaticText( itemDialog1, wxID_STATIC, _("Timelines"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer4->Add(itemStaticText5, 0, wxALIGN_CENTER_HORIZONTAL|wxLEFT|wxRIGHT|wxTOP, 5);

  wxArrayString listTimelinesStrings;
  listTimelines = new wxCheckListBox( itemDialog1, ID_LISTTIMELINES, wxDefaultPosition, wxSize(200, -1), listTimelinesStrings, wxLB_SINGLE );
  itemBoxSizer4->Add(listTimelines, 1, wxGROW|wxALL, 5);

  wxBoxSizer* itemBoxSizer7 = new wxBoxSizer(wxVERTICAL);
  itemBoxSizer3->Add(itemBoxSizer7, 1, wxGROW|wxALL, 5);

  wxStaticText* itemStaticText8 = new wxStaticText( itemDialog1, wxID_STATIC, _("Histograms"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer7->Add(itemStaticText8, 0, wxALIGN_CENTER_HORIZONTAL|wxLEFT|wxRIGHT|wxTOP, 5);

  wxArrayString listHistogramsStrings;
  listHistograms = new wxCheckListBox( itemDialog1, ID_LISTHISTOGRAMS, wxDefaultPosition, wxSize(200, -1), listHistogramsStrings, wxLB_SINGLE );
  itemBoxSizer7->Add(listHistograms, 1, wxGROW|wxALL, 5);

  wxBoxSizer* itemBoxSizer10 = new wxBoxSizer(wxVERTICAL);
  itemBoxSizer3->Add(itemBoxSizer10, 0, wxGROW|wxALL, 5);

  wxStaticBox* itemStaticBoxSizer11Static = new wxStaticBox(itemDialog1, wxID_ANY, _("Timeline options"));
  wxStaticBoxSizer* itemStaticBoxSizer11 = new wxStaticBoxSizer(itemStaticBoxSizer11Static, wxVERTICAL);
  itemBoxSizer10->Add(itemStaticBoxSizer11, 3, wxGROW|wxALL, 5);

  optRelativeBegin = new wxCheckBox( itemDialog1, ID_CHECKBEGIN, _("Relative begin time"), wxDefaultPosition, wxDefaultSize, 0 );
  optRelativeBegin->SetValue(false);
  itemStaticBoxSizer11->Add(optRelativeBegin, 1, wxALIGN_LEFT|wxALL, 5);

  optRelativeEnd = new wxCheckBox( itemDialog1, ID_CHECKEND, _("Relative end time"), wxDefaultPosition, wxDefaultSize, 0 );
  optRelativeEnd->SetValue(false);
  itemStaticBoxSizer11->Add(optRelativeEnd, 1, wxALIGN_LEFT|wxALL, 5);

  optComputeSemantic = new wxCheckBox( itemDialog1, ID_CHECKSEMANTIC, _("Compute semantic scale"), wxDefaultPosition, wxDefaultSize, 0 );
  optComputeSemantic->SetValue(false);
  itemStaticBoxSizer11->Add(optComputeSemantic, 1, wxALIGN_LEFT|wxALL, 5);

  wxStaticBox* itemStaticBoxSizer15Static = new wxStaticBox(itemDialog1, wxID_ANY, _("Histogram options"));
  wxStaticBoxSizer* itemStaticBoxSizer15 = new wxStaticBoxSizer(itemStaticBoxSizer15Static, wxVERTICAL);
  itemBoxSizer10->Add(itemStaticBoxSizer15, 5, wxGROW|wxALL, 5);

  radioAllTrace = new wxRadioButton( itemDialog1, ID_RADIOALLTRACE, _("All trace"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP );
  radioAllTrace->SetValue(false);
  itemStaticBoxSizer15->Add(radioAllTrace, 1, wxALIGN_LEFT|wxALL, 5);

  radioAllWindow = new wxRadioButton( itemDialog1, ID_RADIOALLWINDOW, _("All window"), wxDefaultPosition, wxDefaultSize, 0 );
  radioAllWindow->SetValue(false);
  itemStaticBoxSizer15->Add(radioAllWindow, 1, wxGROW|wxALL, 5);

  wxStaticLine* itemStaticLine18 = new wxStaticLine( itemDialog1, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL );
  itemStaticBoxSizer15->Add(itemStaticLine18, 1, wxGROW|wxLEFT|wxRIGHT, 5);

  optComputeLimits = new wxCheckBox( itemDialog1, ID_CHECKLIMITS, _("Compute min, max, delta limits"), wxDefaultPosition, wxDefaultSize, 0 );
  optComputeLimits->SetValue(false);
  itemStaticBoxSizer15->Add(optComputeLimits, 1, wxALIGN_LEFT|wxALL, 5);

  optComputeGradient = new wxCheckBox( itemDialog1, ID_CHECKGRADIENT, _("Compute gradient limits"), wxDefaultPosition, wxDefaultSize, 0 );
  optComputeGradient->SetValue(false);
  itemStaticBoxSizer15->Add(optComputeGradient, 1, wxALIGN_LEFT|wxALL, 5);

  wxStaticText* itemStaticText21 = new wxStaticText( itemDialog1, wxID_STATIC, _("Description"), wxDefaultPosition, wxDefaultSize, 0 );
  itemBoxSizer2->Add(itemStaticText21, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5);

  textDescription = new wxTextCtrl( itemDialog1, ID_TEXTDESCRIPTION, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE );
  itemBoxSizer2->Add(textDescription, 1, wxGROW|wxALL, 5);

  wxStdDialogButtonSizer* itemStdDialogButtonSizer23 = new wxStdDialogButtonSizer;

  itemBoxSizer2->Add(itemStdDialogButtonSizer23, 0, wxALIGN_RIGHT|wxALL, 5);
  wxButton* itemButton24 = new wxButton( itemDialog1, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
  itemStdDialogButtonSizer23->AddButton(itemButton24);

  wxButton* itemButton25 = new wxButton( itemDialog1, wxID_SAVE, _("&Save"), wxDefaultPosition, wxDefaultSize, 0 );
  itemStdDialogButtonSizer23->AddButton(itemButton25);

  itemStdDialogButtonSizer23->Realize();

////@end SaveConfigurationDialog content construction
}

/*!
 * Should we show tooltips?
 */

bool SaveConfigurationDialog::ShowToolTips()
{
  return true;
}

/*!
 * Get bitmap resources
 */

wxBitmap SaveConfigurationDialog::GetBitmapResource( const wxString& name )
{
  // Bitmap retrieval
////@begin SaveConfigurationDialog bitmap retrieval
  wxUnusedVar(name);
  return wxNullBitmap;
////@end SaveConfigurationDialog bitmap retrieval
}

/*!
 * Get icon resources
 */

wxIcon SaveConfigurationDialog::GetIconResource( const wxString& name )
{
  // Icon retrieval
////@begin SaveConfigurationDialog icon retrieval
  wxUnusedVar(name);
  return wxNullIcon;
////@end SaveConfigurationDialog icon retrieval
}

bool SaveConfigurationDialog::TransferDataToWindow()
{
  wxArrayString items;
  for( vector<Window *>::iterator it = timelines.begin(); it != timelines.end(); ++it )
    items.Add( wxString::FromAscii( (*it)->getName().c_str() ) + " @ " + (*it)->getTrace()->getTraceName().c_str() );
  listTimelines->InsertItems( items, 0 );

  items.Clear();
  for( vector<Histogram *>::iterator it = histograms.begin(); it != histograms.end(); ++it )
    items.Add( wxString::FromAscii( (*it)->getName().c_str() ) + " @ " + (*it)->getTrace()->getTraceName().c_str() );
  listHistograms->InsertItems( items, 0 );

  optRelativeBegin->SetValue( options.windowBeginTimeRelative );
  optRelativeEnd->SetValue( options.windowScaleRelative );
  optComputeSemantic->SetValue( options.windowComputeYMaxOnLoad );
  radioAllTrace->SetValue( options.histoAllTrace );
  optComputeLimits->SetValue( options.histoComputeYScale );
  optComputeGradient->SetValue( options.histoComputeGradient );

  return true;
}

bool SaveConfigurationDialog::TransferDataFromWindow()
{
  vector<Window *> tmpTimelines;
  for( size_t i = 0; i < listTimelines->GetCount(); ++i )
  {
    if( listTimelines->IsChecked( i ) )
      tmpTimelines.push_back( timelines[ i ] );
  }
  timelines.clear();
  timelines = tmpTimelines;

  vector<Histogram *> tmpHistograms;
  for( size_t i = 0; i < listHistograms->GetCount(); ++i )
  {
    if( listHistograms->IsChecked( i ) )
      tmpHistograms.push_back( histograms[ i ] );
  }
  histograms.clear();
  histograms = tmpHistograms;

  options.windowBeginTimeRelative = optRelativeBegin->GetValue();
  options.windowScaleRelative = optRelativeEnd->GetValue();
  options.windowComputeYMaxOnLoad = optComputeSemantic->GetValue();
  options.histoAllTrace = radioAllTrace->GetValue();
  options.histoComputeYScale = optComputeLimits->GetValue();
  options.histoComputeGradient = optComputeGradient->GetValue();
  options.description = std::string( textDescription->GetValue().mb_str() );

  return true;
}

/*!
 * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_SAVE
 */

void SaveConfigurationDialog::OnSaveClick( wxCommandEvent& event )
{
  TransferDataFromWindow();
  if( timelines.begin() == timelines.end() &&
      histograms.begin() == histograms.end() )
    EndModal( wxID_OK );//EndModal( wxID_CANCEL );
  else
    EndModal( wxID_OK );
}

<|endoftext|>


<commit_before>#include "Look.h"
#include "GameState.h"

string Look::parseNoun(vector<string> options, ScreenState * state)
{
	GameState* game = dynamic_cast<GameState*>(state);

	return game->level->player->currentRoom->getDescritption();
}
<commit_msg>made it so you can look at items with the look comand.<commit_after>#include "Look.h"
#include "GameState.h"
#include "Item.h"

string Look::parseNoun(vector<string> options, ScreenState * state)
{
	GameState* game = dynamic_cast<GameState*>(state);

	if (options.size() > 0) {
		if (options[0] == "at" && options.size() > 1) {
			for (auto item : game->level->player->currentRoom->items) {
				if (item->getName() == options[1]) {
					return item->Interact(*game->level);
				}
			}
		}
		else {
			for (auto item : game->level->player->currentRoom->items) {
				if (item->getName() == options[0]) {
					return item->Interact(*game->level);
				}
			}
		}

		return "There isn't anything like that in the room.";
	}

	return game->level->player->currentRoom->getDescritption();
}
<|endoftext|>


<commit_before>/*
  Part of the Wiring project - http://wiring.org.co
  Copyright (c) 2004-06 Hernando Barragan
  Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library 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
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA

  $Id$
*/
extern "C" {
	#include <stdlib.h>
	#include <stdint.h>
	#include <inttypes.h>
}
#include "WMath.h"

void randomSeed(uint32_t dwSeed)
{
	if (dwSeed != 0)
		srand(dwSeed);
}

long random(long howbig)
{
	if (howbig == 0) {
		return 0;
	}
	return rand() % howbig;
}

long random(long howsmall, long howbig)
{
	if (howsmall >= howbig) {
		return howsmall;
	}
	long diff = howbig - howsmall;
		return random(diff) + howsmall;
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

unsigned int makeWord(unsigned int w) { return w; }
unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; }
<commit_msg>Some refactoring in WMath.cpp<commit_after>/*
  Part of the Wiring project - http://wiring.org.co
  Copyright (c) 2004-06 Hernando Barragan
  Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library 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
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA

  $Id$
*/
extern "C" {
	#include <stdlib.h>
	#include <stdint.h>
	#include <inttypes.h>
}
#include "WMath.h"

void randomSeed(uint32_t dwSeed)
{
	if (dwSeed != 0)
		srand(dwSeed);
}

long random(long howbig)
{
	if (howbig == 0) {
		return 0;
	}
	return rand() % howbig;
}

long random(long howsmall, long howbig)
{
	if (howsmall >= howbig) {
		return howsmall;
	}
	long diff = howbig - howsmall;
	return random(diff) + howsmall;
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

unsigned int makeWord(unsigned int w)
{
	return w;
}
unsigned int makeWord(unsigned char h, unsigned char l)
{
	return (h << 8) | l;
}
<|endoftext|>