<commit_before>/*
 * mainGame.cpp
 *
 *  Created on: Nov 26, 2017
 *      Author: lowji
 */

//created this source file to make the compiler work properly

#include <iostream>
#include <string>
#include "Player.h"
#include "ConsoleUI.h"

//method to determine if a string is an integer
bool isInt(string input){
	//Reference: https://stackoverflow.com/questions/20287186/how-to-check-if-the-input-is-a-valid-integer-without-any-other-chars

	int x; //temporary int variable for checking input validity
	char c; //temporary char variable for checking input validity
	istringstream s(input);

	if (!(s >> x)) {
		return false;
	}
	if (s >> c) {
		return false;
	}

	return true;
}

int main(){

	//set up user interface
	ConsoleUI*ui=new ConsoleUI();

	ui->welcome();

	string inputTemp;
	inputTemp=ui->input("Input your name: ");
	string name = inputTemp;
	Player* human = new Player(inputTemp);
	Player* AI = new Player("AI");

	//Preflop
	inputTemp=ui->input("How much do you want the blind to be? ");
	human->setTotalChips(stoi(inputTemp));
	AI->setTotalChips(stoi(inputTemp));
	ui->output("Your name is "+human->getName());
	ui->output("Your opponent name is "+AI->getName());
	ui->output("Your blind is "+human->getTotalChips());
	ui->output("AI has blind of "+AI->getTotalChips());
	//shuffling

	//draw cards

	//print user's hand

	//print table: your pocket, small blind, big blind, pot(needs to make)

	//prompt user decision: raise, bet, check, fold

	//Postflop: prompt user, update pot and each player stack size(money), user's decision, draw 3 cards into communitycards, print pot and stacksize, print hands, print communitycards

	//Turn:  prompt user, update pot and each player stack size(money), user's decision, draw 1 cards into communitycards, print pot and stacksize, print hands, print communitycards

	//River: repeat Turn, and go back to preflop...

}

<commit_msg>mainGame changed<commit_after>/*
 * mainGame.cpp
 *
 *  Created on: Nov 26, 2017
 *      Author: lowji
 */

//created this source file to make the compiler work properly
#include <sstream>
#include <iostream>
#include <string>
#include "Player.h"
#include "ConsoleUI.h"

//method to determine if a string is an integer
bool isInt(string input){
	//Reference: https://stackoverflow.com/questions/20287186/how-to-check-if-the-input-is-a-valid-integer-without-any-other-chars

	int x; //temporary int variable for checking input validity
	char c; //temporary char variable for checking input validity
	istringstream s(input);

	if (!(s >> x)) {
		return false;
	}
	if (s >> c) {
		return false;
	}

	return true;
}

int main(){

	//set up user interface
	ConsoleUI*ui=new ConsoleUI();

	ui->welcome();

	string inputTemp;
	inputTemp=ui->input("Input your name: ");
	string name = inputTemp;
	Player* human = new Player(inputTemp);
	Player* AI = new Player("AI");

	//Preflop
	inputTemp=ui->input("How much do you want the blind to be? ");
	human->setTotalChips(stoi(inputTemp));
	AI->setTotalChips(stoi(inputTemp));
	ui->output("Your name is "+human->getName());
	ui->output("Your opponent name is "+AI->getName());
	ui->output("Your blind is "+human->getTotalChips());
	ui->output("AI has blind of "+AI->getTotalChips());
	//shuffling(automatic shuffled)
	Deck* deck = new Deck();
	//draw cards
	human->addOne(deck->draw());
	human->addTwo(deck->draw());

	//print user's hand
	(human->getHandOne()).printCard();
	(human->getHandTwo()).printCard();
	//print table: your pocket, small blind, big blind, pot(needs to make)

	//prompt user decision: raise, bet, check, fold

	//Postflop: prompt user, update pot and each player stack size(money), user's decision, draw 3 cards into communitycards, print pot and stacksize, print hands, print communitycards

	//Turn:  prompt user, update pot and each player stack size(money), user's decision, draw 1 cards into communitycards, print pot and stacksize, print hands, print communitycards

	//River: repeat Turn, and go back to preflop...

}

<|endoftext|>


<commit_before>/* vision/vision_processing.cpp
 *
 * Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Entry points for vision processing: distance and angle from image
 */

/*
 * Calculated angles are relative to perpendicular.
 */

#include <vector>
#include <cmath>
#include <Vision/ColorImage.h>
#include <Vision/BinaryImage.h>
#include <Vision2009/VisionAPI.h>
#include <nivision.h>

#include "vision_processing.h"
#include "../ports.h"
#include "../ranges.h"
#include "../trajectory.h"
#include "../visionalg.h"

using namespace vision_processing;

typedef struct particle_rect_struct {
    int top;    //Location of the top edge of the rectangle.
    int left;   //Location of the left edge of the rectangle.
    int height; //Height of the rectangle.
    int width;  //Width of the rectangle.
} particle_rect;

//constants
HSLImage old_image;

BinaryImage* image_mask;
vector<ParticleAnalysisReport>* targets;

BinaryImage* get_image_mask(ColorImage*);
vector<ParticleAnalysisReport>* get_image_targets(BinaryImage*);

double inline degrees_from_ratio(double); // ratio: width/height
double inline radians_from_ratio(double);
double inline distance_from_height(int);
double inline deviation_from_angle(double);

ColorImage* vision_processing::get_image() {
    camera().GetImage(&old_image);
    return &old_image;
}

ColorImage* vision_processing::get_old_image() {
    return &old_image;
}

unsigned int vision_processing::determine_aim_target() {
    // TODO make it do stuff
    return 0;
}

vector<double> vision_processing::get_distance() {
    vector<double> distance;
    for(unsigned int i = 0; i < targets->size(); i++) {
        ParticleAnalysisReport target = targets->at(i);
        Rect target_rect=target.boundingRect;
        int height = target_rect.height;
        int width = target_rect.width;
        double ratio = 1.0 * width/height;
        double image_degrees = degrees_from_ratio(ratio);
		double ground_distance = distance_from_height(height) + deviation_from_angle(image_degrees);
        distance.push_back(ground_distance);
    }
    return distance;
}

vector<double> vision_processing::get_degrees() {
    vector<double> degrees;
    for(unsigned int i = 0; i < targets->size(); i++) {
        ParticleAnalysisReport target = targets->at(i);
        Rect target_rect = target.boundingRect;
        int height = target_rect.height;
        int width = target_rect.width;
        double ratio = 1.0 * width/height;
        double image_degrees = degrees_from_ratio(ratio);
        degrees.push_back(image_degrees);
    }
    return degrees;
}

vector<double> vision_processing::get_radians() {
    vector<double> degrees = get_degrees();
    vector<double> radians;
    for(unsigned int i = 0; i< degrees.size(); i++) {
        radians.push_back(deg2rad(degrees[i]));
    }
    return radians;
}

BinaryImage* get_image_mask(ColorImage* image) {
    if(image == NULL) {
        return image_mask;
    }
    if (COLOR_MODE == HSV) {
        image_mask = image->ThresholdHSV(HSV_HMIN, HSV_HMAX, HSV_SMIN, HSV_SMAX, HSV_VMIN, HSV_VMAX);
    }
    else if(COLOR_MODE == HSI) {
        image_mask = image->ThresholdHSI(HSI_HMIN, HSI_HMAX, HSI_SMIN, HSI_SMAX, HSI_IMIN, HSI_IMAX);
    }
    else { // HSL is implied (not assumed)
        image_mask = image->ThresholdHSL(HSL_HMIN, HSL_HMAX, HSL_SMIN, HSL_SMAX, HSL_LMIN, HSL_LMAX);
    }
    return image_mask;
}

vector<ParticleAnalysisReport>* get_image_targets(BinaryImage* image) {
    vector<ParticleAnalysisReport>* targets = new vector<ParticleAnalysisReport>();
    if(image == NULL) {
        return targets;
    }
    vector<ParticleAnalysisReport>* particles=image->GetOrderedParticleAnalysisReports();
    for(unsigned int i = 0; i < particles->size(); i++) {
        ParticleAnalysisReport particle = particles->at(i);
        double particle_area = particle.particleArea;
        if(particle_area > PARTICLE_AREA_MIN && particle_area <= PARTICLE_AREA_MAX) {
            if(targets->size() >= 4) {
                // TODO change min and max
                //      call function again
                //      if depth is more than 2
                //      explode
                break;
            }
            targets->push_back(particle);
        }
    }
    delete particles;
    return targets;
}

void vision_processing::update() {
    if(!camera().IsFreshImage()) {
        return;
    }
    delete image_mask;
    image_mask = get_image_mask(&old_image);
    delete targets;
    targets = get_image_targets(image_mask);
}

//TODO: Someone else (Jeff?) sanity check this and make sure it's right.  I tried to copy your logic
//from above.
double get_distance_from_report(const ParticleAnalysisReport& report) {
    double ratio = ((double)(report.boundingRect.width))/(report.boundingRect.height);
    double degrees = degrees_from_ratio(ratio);
    double dist = distance_from_height(report.boundingRect.height) + deviation_from_angle(degrees);
    return dist;
}

double get_height_offset_from_report(const ParticleAnalysisReport& r, double dist) {
    //meant to be called once you have dist from get_distance_from_report
    //this way we don't need to have target detection
    double theta = angle_offset(RESOLUTION().Y()/2 - r.center_mass_y, RESOLUTION().Y(), FOV().Y());
    return std::tan(theta)*dist;
}

double inline degrees_from_ratio(double ratio) {
    //a quadratic regression.  Fits rather well.
    //aspect ratio is constant 4:3, so no need to adjust ratio
    return (-94.637 * ratio * ratio) + (119.86 * ratio) + 9.7745;
}

double inline radians_from_ratio(double ratio) {
    return deg2rad(degrees_from_ratio(ratio));
}

double inline distance_from_height(int height) {
    //magic numbers are gross but they do the job...
    //a tad worried about the -0.8.  Not sure what this will do at close distances
#ifdef RESOLUTION_640_480
    //no need to do anything
#elif defined RESOLUTION_320_240
    height *= 2; //adjust for resolution
#elif defined RESOLUTION_160_120
    height *= 4;
#endif
    return ((1277.686246075*(1/height)) - 0.8265433113);
}

double inline deviation_from_angle(double angle) {
    return ((0.0188*angle) + 0.017);
}
<commit_msg>Small update to vision processing (streamline)<commit_after>/* vision/vision_processing.cpp
 *
 * Copyright (c) 2011, 2012 Chantilly Robotics <chantilly612@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Entry points for vision processing: distance and angle from image
 */

/*
 * Calculated angles are relative to perpendicular.
 */

#include <vector>
#include <cmath>
#include <Vision/ColorImage.h>
#include <Vision/BinaryImage.h>
#include <Vision2009/VisionAPI.h>
#include <nivision.h>

#include "vision_processing.h"
#include "../ports.h"
#include "../ranges.h"
#include "../trajectory.h"
#include "../visionalg.h"

using namespace vision_processing;

typedef struct particle_rect_struct {
    int top;    //Location of the top edge of the rectangle.
    int left;   //Location of the left edge of the rectangle.
    int height; //Height of the rectangle.
    int width;  //Width of the rectangle.
} particle_rect;

//constants
HSLImage old_image;

BinaryImage* image_mask;
vector<ParticleAnalysisReport>* targets;

BinaryImage* get_image_mask(ColorImage*);
vector<ParticleAnalysisReport>* get_image_targets(BinaryImage*);

double inline degrees_from_ratio(double); // ratio: width/height
double inline radians_from_ratio(double);
double inline distance_from_height(int);
double inline deviation_from_angle(double);

ColorImage* vision_processing::get_image() {
    camera().GetImage(&old_image);
    return &old_image;
}

ColorImage* vision_processing::get_old_image() {
    return &old_image;
}

unsigned int vision_processing::determine_aim_target() {
    // TODO make it do stuff
    return 0;
}

vector<double> vision_processing::get_distance() {
    vector<double> distance;
    for (unsigned int i = 0; i < targets->size(); i++) {
        distance.push_back(get_distance_from_report(targets->at(i)));
    }
    return distance;
}

vector<double> vision_processing::get_degrees() {
    vector<double> degrees;
    for (unsigned int i = 0; i < targets->size(); i++) {
        degrees.push_back(get_degrees_from_report(targets->at(i)));
    }
    return degrees;
}

vector<double> vision_processing::get_radians() {
    vector<double> degrees = get_degrees();
    vector<double> radians;
    for(unsigned int i = 0; i< degrees.size(); i++) {
        radians.push_back(deg2rad(degrees[i]));
    }
    return radians;
}

BinaryImage* get_image_mask(ColorImage* image) {
    if(image == NULL) {
        return image_mask;
    }
    if (COLOR_MODE == HSV) {
        image_mask = image->ThresholdHSV(HSV_HMIN, HSV_HMAX, HSV_SMIN, HSV_SMAX, HSV_VMIN, HSV_VMAX);
    }
    else if(COLOR_MODE == HSI) {
        image_mask = image->ThresholdHSI(HSI_HMIN, HSI_HMAX, HSI_SMIN, HSI_SMAX, HSI_IMIN, HSI_IMAX);
    }
    else { // HSL is implied (not assumed)
        image_mask = image->ThresholdHSL(HSL_HMIN, HSL_HMAX, HSL_SMIN, HSL_SMAX, HSL_LMIN, HSL_LMAX);
    }
    return image_mask;
}

vector<ParticleAnalysisReport>* get_image_targets(BinaryImage* image) {
    vector<ParticleAnalysisReport>* targets = new vector<ParticleAnalysisReport>();
    if(image == NULL) {
        return targets;
    }
    vector<ParticleAnalysisReport>* particles=image->GetOrderedParticleAnalysisReports();
    for(unsigned int i = 0; i < particles->size(); i++) {
        ParticleAnalysisReport particle = particles->at(i);
        double particle_area = particle.particleArea;
        if(particle_area > PARTICLE_AREA_MIN && particle_area <= PARTICLE_AREA_MAX) {
            if(targets->size() >= 4) {
                // TODO change min and max
                //      call function again
                //      if depth is more than 2
                //      explode
                break;
            }
            targets->push_back(particle);
        }
    }
    delete particles;
    return targets;
}

void vision_processing::update() {
    if(!camera().IsFreshImage()) {
        return;
    }
    delete image_mask;
    image_mask = get_image_mask(&old_image);
    delete targets;
    targets = get_image_targets(image_mask);
}

//TODO: Someone else (Jeff?) sanity check this and make sure it's right.  I tried to copy your logic
//from above.
double get_distance_from_report(const ParticleAnalysisReport& report) {
    double ratio = ((double)(report.boundingRect.width))/(report.boundingRect.height);
    double degrees = degrees_from_ratio(ratio);
    double dist = distance_from_height(report.boundingRect.height) + deviation_from_angle(degrees);
    return dist;
}

double get_degrees_from_report(const ParticleAnalysisReport& r) {
    double ratio = ((double)(r.boundingRect.width)/(r.boundingRect.height);
    return degrees_from_ratio(ratio);
}

double get_height_offset_from_report(const ParticleAnalysisReport& r, double dist) {
    //meant to be called once you have dist from get_distance_from_report
    //this way we don't need to have target detection
    double theta = angle_offset(RESOLUTION().Y()/2 - r.center_mass_y, RESOLUTION().Y(), FOV().Y());
    return std::tan(theta)*dist;
}

double inline degrees_from_ratio(double ratio) {
    //a quadratic regression.  Fits rather well.
    //aspect ratio is constant 4:3, so no need to adjust ratio
    return (-94.637 * ratio * ratio) + (119.86 * ratio) + 9.7745;
}

double inline radians_from_ratio(double ratio) {
    return deg2rad(degrees_from_ratio(ratio));
}

double inline distance_from_height(int height) {
    //magic numbers are gross but they do the job...
    //a tad worried about the -0.8.  Not sure what this will do at close distances
#ifdef RESOLUTION_640_480
    //no need to do anything
#elif defined RESOLUTION_320_240
    height *= 2; //adjust for resolution
#elif defined RESOLUTION_160_120
    height *= 4;
#endif
    return ((1277.686246075*(1/height)) - 0.8265433113);
}

double inline deviation_from_angle(double angle) {
    return ((0.0188*angle) + 0.017);
}
<|endoftext|>


<commit_before>#include "Effekseer.Parameters.h"
#include "../Effekseer.EffectImplemented.h"
#include "../Effekseer.Instance.h"
#include "../Effekseer.InstanceGlobal.h"
#include "../Effekseer.InternalScript.h"
#include "DynamicParameter.h"

namespace Effekseer
{

void LoadGradient(Gradient& gradient, uint8_t*& pos, int32_t version)
{
	BinaryReader<true> reader(pos, std::numeric_limits<int>::max());
	reader.Read(gradient.ColorCount);
	for (int i = 0; i < gradient.ColorCount; i++)
	{
		reader.Read(gradient.Colors[i]);
	}

	reader.Read(gradient.AlphaCount);
	for (int i = 0; i < gradient.AlphaCount; i++)
	{
		reader.Read(gradient.Alphas[i]);
	}

	pos += reader.GetOffset();
}

void NodeRendererTextureUVTypeParameter::Load(uint8_t*& pos, int32_t version)
{
	memcpy(&Type, pos, sizeof(int));
	pos += sizeof(int);

	if (Type == TextureUVType::Strech)
	{
	}
	else if (Type == TextureUVType::Tile)
	{
		memcpy(&TileEdgeHead, pos, sizeof(TileEdgeHead));
		pos += sizeof(TileEdgeHead);

		memcpy(&TileEdgeTail, pos, sizeof(TileEdgeTail));
		pos += sizeof(TileEdgeTail);

		memcpy(&TileLoopAreaBegin, pos, sizeof(TileLoopAreaBegin));
		pos += sizeof(TileLoopAreaBegin);

		memcpy(&TileLoopAreaEnd, pos, sizeof(TileLoopAreaEnd));
		pos += sizeof(TileLoopAreaEnd);
	}
}

template <typename T, typename U>
void ApplyEq_(T& dstParam, const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, int dpInd, const U& originalParam)
{
	static_assert(sizeof(T) == sizeof(U), "size is not mismatched");
	const int count = sizeof(T) / 4;

	EFK_ASSERT(e != nullptr);
	EFK_ASSERT(0 <= dpInd && dpInd < static_cast<int>(instg->dynamicEqResults.size()));

	auto dst = reinterpret_cast<float*>(&(dstParam));
	auto src = reinterpret_cast<const float*>(&(originalParam));

	auto eqresult = instg->dynamicEqResults[dpInd];
	std::array<float, 1> globals;
	globals[0] = instg->GetUpdatedFrame() / 60.0f;

	std::array<float, 5> locals;

	for (int i = 0; i < count; i++)
	{
		locals[i] = src[i];
	}

	for (int i = count; i < 4; i++)
	{
		locals[i] = 0.0f;
	}

	locals[4] = parrentInstance != nullptr ? parrentInstance->m_LivingTime / 60.0f : 0.0f;

	auto e_ = static_cast<const EffectImplemented*>(e);
	auto& dp = e_->GetDynamicEquation()[dpInd];

	if (dp.GetRunningPhase() == InternalScript::RunningPhaseType::Local)
	{
		eqresult = dp.Execute(instg->GetDynamicInputParameters(), globals, locals, RandCallback::Rand, RandCallback::RandSeed, rand);
	}

	for (int i = 0; i < count; i++)
	{
		dst[i] = eqresult[i];
	}
}

void ApplyEq(float& dstParam, const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, int dpInd, const float& originalParam)
{
	ApplyEq_(dstParam, e, instg, parrentInstance, rand, dpInd, originalParam);
}

template <typename S>
SIMD::Vec3f ApplyEq_(
	const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const int& dpInd, const SIMD::Vec3f& originalParam, const S& scale, const S& scaleInv)
{
	SIMD::Vec3f param = originalParam;
	if (dpInd >= 0)
	{
		param *= SIMD::Vec3f(scaleInv[0], scaleInv[1], scaleInv[2]);

		ApplyEq_(param, e, instg, parrentInstance, rand, dpInd, param);

		param *= SIMD::Vec3f(scale[0], scale[1], scale[2]);
	}
	return param;
}

SIMD::Vec3f ApplyEq(
	const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const int& dpInd, const SIMD::Vec3f& originalParam, const std::array<float, 3>& scale, const std::array<float, 3>& scaleInv)
{
	return ApplyEq_(e, instg, parrentInstance, rand, dpInd, originalParam, scale, scaleInv);
}

random_float ApplyEq(const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const RefMinMax& dpInd, random_float originalParam)
{
	if (dpInd.Max >= 0)
	{
		ApplyEq_(originalParam.max, e, instg, parrentInstance, rand, dpInd.Max, originalParam.max);
	}

	if (dpInd.Min >= 0)
	{
		ApplyEq_(originalParam.min, e, instg, parrentInstance, rand, dpInd.Min, originalParam.min);
	}

	return originalParam;
}

template <typename S>
random_vector3d ApplyEq_(const Effect* e,
						 const InstanceGlobal* instg,
						 const Instance* parrentInstance,
						 IRandObject* rand,
						 const RefMinMax& dpInd,
						 random_vector3d originalParam,
						 const S& scale,
						 const S& scaleInv)
{
	if (dpInd.Max >= 0)
	{
		originalParam.max.x *= scaleInv[0];
		originalParam.max.y *= scaleInv[1];
		originalParam.max.z *= scaleInv[2];

		ApplyEq_(originalParam.max, e, instg, parrentInstance, rand, dpInd.Max, originalParam.max);

		originalParam.max.x *= scale[0];
		originalParam.max.y *= scale[1];
		originalParam.max.z *= scale[2];
	}

	if (dpInd.Min >= 0)
	{
		originalParam.min.x *= scaleInv[0];
		originalParam.min.y *= scaleInv[1];
		originalParam.min.z *= scaleInv[2];

		ApplyEq_(originalParam.min, e, instg, parrentInstance, rand, dpInd.Min, originalParam.min);

		originalParam.min.x *= scale[0];
		originalParam.min.y *= scale[1];
		originalParam.min.z *= scale[2];
	}

	return originalParam;
}

random_vector3d ApplyEq(const Effect* e,
						const InstanceGlobal* instg,
						const Instance* parrentInstance,
						IRandObject* rand,
						const RefMinMax& dpInd,
						random_vector3d originalParam,
						const std::array<float, 3>& scale,
						const std::array<float, 3>& scaleInv)
{
	return ApplyEq_(e,
					instg,
					parrentInstance,
					rand,
					dpInd,
					originalParam,
					scale,
					scaleInv);
}

random_int ApplyEq(const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const RefMinMax& dpInd, random_int originalParam)
{
	if (dpInd.Max >= 0)
	{
		float value = static_cast<float>(originalParam.max);
		ApplyEq_(value, e, instg, parrentInstance, rand, dpInd.Max, value);
		originalParam.max = static_cast<int32_t>(value);
	}

	if (dpInd.Min >= 0)
	{
		float value = static_cast<float>(originalParam.min);
		ApplyEq_(value, e, instg, parrentInstance, rand, dpInd.Min, value);
		originalParam.min = static_cast<int32_t>(value);
	}

	return originalParam;
}

std::array<float, 4> Gradient::GetColor(float x) const
{
	const auto c = GetColorAndIntensity(x);
	return std::array<float, 4>{c[0] * c[3], c[1] * c[3], c[2] * c[3], GetAlpha(x)};
}

std::array<float, 4> Gradient::GetColorAndIntensity(float x) const
{
	if (ColorCount == 0)
	{
		return std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f};
	}

	if (x < Colors[0].Position)
	{
		const auto c = Colors[0].Color;
		return {c[0], c[1], c[2], Colors[0].Intensity};
	}

	if (Colors[ColorCount - 1].Position <= x)
	{
		const auto c = Colors[ColorCount - 1].Color;
		return {c[0], c[1], c[2], Colors[ColorCount - 1].Intensity};
	}

	auto key = ColorKey();
	key.Position = x;

	auto it = std::lower_bound(Colors.begin(), Colors.begin() + ColorCount, key, [](const ColorKey& a, const ColorKey& b)
							   { return a.Position < b.Position; });
	auto ind = static_cast<int32_t>(std::distance(Colors.begin(), it));

	{
		if (Colors[ind].Position != x)
		{
			ind--;
		}

		if (Colors[ind].Position <= x && x <= Colors[ind + 1].Position)
		{
			const auto area = Colors[ind + 1].Position - Colors[ind].Position;
			if (area == 0)
			{
				return std::array<float, 4>{Colors[ind].Color[0], Colors[ind].Color[1], Colors[ind].Color[2], Colors[ind].Intensity};
			}

			const auto alpha = (x - Colors[ind].Position) / area;
			const auto r = Colors[ind + 1].Color[0] * alpha + Colors[ind].Color[0] * (1.0f - alpha);
			const auto g = Colors[ind + 1].Color[1] * alpha + Colors[ind].Color[1] * (1.0f - alpha);
			const auto b = Colors[ind + 1].Color[2] * alpha + Colors[ind].Color[2] * (1.0f - alpha);
			const auto intensity = Colors[ind + 1].Intensity * alpha + Colors[ind].Intensity * (1.0f - alpha);
			return std::array<float, 4>{r, g, b, intensity};
		}
		else
		{
			assert(0);
		}
	}

	return std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f};
}

float Gradient::GetAlpha(float x) const
{
	if (AlphaCount == 0)
	{
		return 1.0f;
	}

	if (x < Alphas[0].Position)
	{
		return Alphas[0].Alpha;
	}

	if (Alphas[AlphaCount - 1].Position <= x)
	{
		return Alphas[AlphaCount - 1].Alpha;
	}

	auto key = AlphaKey();
	key.Position = x;

	auto it = std::lower_bound(Alphas.begin(), Alphas.begin() + AlphaCount, key, [](const AlphaKey& a, const AlphaKey& b)
							   { return a.Position < b.Position; });
	auto ind = static_cast<int32_t>(std::distance(Alphas.begin(), it));

	{
		if (Alphas[ind].Position != x)
		{
			ind--;
		}

		if (Alphas[ind].Position <= x && x <= Alphas[ind + 1].Position)
		{
			const auto area = Alphas[ind + 1].Position - Alphas[ind].Position;
			if (area == 0)
			{
				return Alphas[ind].Alpha;
			}

			const auto alpha = (x - Alphas[ind].Position) / area;
			return Alphas[ind + 1].Alpha * alpha + Alphas[ind].Alpha * (1.0f - alpha);
		}
		else
		{
			assert(0);
		}
	}

	return 1.0f;
}

} // namespace Effekseer<commit_msg>Fix a compile error in linux<commit_after>#include <algorithm>
#include "Effekseer.Parameters.h"
#include "../Effekseer.EffectImplemented.h"
#include "../Effekseer.Instance.h"
#include "../Effekseer.InstanceGlobal.h"
#include "../Effekseer.InternalScript.h"
#include "DynamicParameter.h"

namespace Effekseer
{

void LoadGradient(Gradient& gradient, uint8_t*& pos, int32_t version)
{
	BinaryReader<true> reader(pos, std::numeric_limits<int>::max());
	reader.Read(gradient.ColorCount);
	for (int i = 0; i < gradient.ColorCount; i++)
	{
		reader.Read(gradient.Colors[i]);
	}

	reader.Read(gradient.AlphaCount);
	for (int i = 0; i < gradient.AlphaCount; i++)
	{
		reader.Read(gradient.Alphas[i]);
	}

	pos += reader.GetOffset();
}

void NodeRendererTextureUVTypeParameter::Load(uint8_t*& pos, int32_t version)
{
	memcpy(&Type, pos, sizeof(int));
	pos += sizeof(int);

	if (Type == TextureUVType::Strech)
	{
	}
	else if (Type == TextureUVType::Tile)
	{
		memcpy(&TileEdgeHead, pos, sizeof(TileEdgeHead));
		pos += sizeof(TileEdgeHead);

		memcpy(&TileEdgeTail, pos, sizeof(TileEdgeTail));
		pos += sizeof(TileEdgeTail);

		memcpy(&TileLoopAreaBegin, pos, sizeof(TileLoopAreaBegin));
		pos += sizeof(TileLoopAreaBegin);

		memcpy(&TileLoopAreaEnd, pos, sizeof(TileLoopAreaEnd));
		pos += sizeof(TileLoopAreaEnd);
	}
}

template <typename T, typename U>
void ApplyEq_(T& dstParam, const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, int dpInd, const U& originalParam)
{
	static_assert(sizeof(T) == sizeof(U), "size is not mismatched");
	const int count = sizeof(T) / 4;

	EFK_ASSERT(e != nullptr);
	EFK_ASSERT(0 <= dpInd && dpInd < static_cast<int>(instg->dynamicEqResults.size()));

	auto dst = reinterpret_cast<float*>(&(dstParam));
	auto src = reinterpret_cast<const float*>(&(originalParam));

	auto eqresult = instg->dynamicEqResults[dpInd];
	std::array<float, 1> globals;
	globals[0] = instg->GetUpdatedFrame() / 60.0f;

	std::array<float, 5> locals;

	for (int i = 0; i < count; i++)
	{
		locals[i] = src[i];
	}

	for (int i = count; i < 4; i++)
	{
		locals[i] = 0.0f;
	}

	locals[4] = parrentInstance != nullptr ? parrentInstance->m_LivingTime / 60.0f : 0.0f;

	auto e_ = static_cast<const EffectImplemented*>(e);
	auto& dp = e_->GetDynamicEquation()[dpInd];

	if (dp.GetRunningPhase() == InternalScript::RunningPhaseType::Local)
	{
		eqresult = dp.Execute(instg->GetDynamicInputParameters(), globals, locals, RandCallback::Rand, RandCallback::RandSeed, rand);
	}

	for (int i = 0; i < count; i++)
	{
		dst[i] = eqresult[i];
	}
}

void ApplyEq(float& dstParam, const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, int dpInd, const float& originalParam)
{
	ApplyEq_(dstParam, e, instg, parrentInstance, rand, dpInd, originalParam);
}

template <typename S>
SIMD::Vec3f ApplyEq_(
	const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const int& dpInd, const SIMD::Vec3f& originalParam, const S& scale, const S& scaleInv)
{
	SIMD::Vec3f param = originalParam;
	if (dpInd >= 0)
	{
		param *= SIMD::Vec3f(scaleInv[0], scaleInv[1], scaleInv[2]);

		ApplyEq_(param, e, instg, parrentInstance, rand, dpInd, param);

		param *= SIMD::Vec3f(scale[0], scale[1], scale[2]);
	}
	return param;
}

SIMD::Vec3f ApplyEq(
	const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const int& dpInd, const SIMD::Vec3f& originalParam, const std::array<float, 3>& scale, const std::array<float, 3>& scaleInv)
{
	return ApplyEq_(e, instg, parrentInstance, rand, dpInd, originalParam, scale, scaleInv);
}

random_float ApplyEq(const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const RefMinMax& dpInd, random_float originalParam)
{
	if (dpInd.Max >= 0)
	{
		ApplyEq_(originalParam.max, e, instg, parrentInstance, rand, dpInd.Max, originalParam.max);
	}

	if (dpInd.Min >= 0)
	{
		ApplyEq_(originalParam.min, e, instg, parrentInstance, rand, dpInd.Min, originalParam.min);
	}

	return originalParam;
}

template <typename S>
random_vector3d ApplyEq_(const Effect* e,
						 const InstanceGlobal* instg,
						 const Instance* parrentInstance,
						 IRandObject* rand,
						 const RefMinMax& dpInd,
						 random_vector3d originalParam,
						 const S& scale,
						 const S& scaleInv)
{
	if (dpInd.Max >= 0)
	{
		originalParam.max.x *= scaleInv[0];
		originalParam.max.y *= scaleInv[1];
		originalParam.max.z *= scaleInv[2];

		ApplyEq_(originalParam.max, e, instg, parrentInstance, rand, dpInd.Max, originalParam.max);

		originalParam.max.x *= scale[0];
		originalParam.max.y *= scale[1];
		originalParam.max.z *= scale[2];
	}

	if (dpInd.Min >= 0)
	{
		originalParam.min.x *= scaleInv[0];
		originalParam.min.y *= scaleInv[1];
		originalParam.min.z *= scaleInv[2];

		ApplyEq_(originalParam.min, e, instg, parrentInstance, rand, dpInd.Min, originalParam.min);

		originalParam.min.x *= scale[0];
		originalParam.min.y *= scale[1];
		originalParam.min.z *= scale[2];
	}

	return originalParam;
}

random_vector3d ApplyEq(const Effect* e,
						const InstanceGlobal* instg,
						const Instance* parrentInstance,
						IRandObject* rand,
						const RefMinMax& dpInd,
						random_vector3d originalParam,
						const std::array<float, 3>& scale,
						const std::array<float, 3>& scaleInv)
{
	return ApplyEq_(e,
					instg,
					parrentInstance,
					rand,
					dpInd,
					originalParam,
					scale,
					scaleInv);
}

random_int ApplyEq(const Effect* e, const InstanceGlobal* instg, const Instance* parrentInstance, IRandObject* rand, const RefMinMax& dpInd, random_int originalParam)
{
	if (dpInd.Max >= 0)
	{
		float value = static_cast<float>(originalParam.max);
		ApplyEq_(value, e, instg, parrentInstance, rand, dpInd.Max, value);
		originalParam.max = static_cast<int32_t>(value);
	}

	if (dpInd.Min >= 0)
	{
		float value = static_cast<float>(originalParam.min);
		ApplyEq_(value, e, instg, parrentInstance, rand, dpInd.Min, value);
		originalParam.min = static_cast<int32_t>(value);
	}

	return originalParam;
}

std::array<float, 4> Gradient::GetColor(float x) const
{
	const auto c = GetColorAndIntensity(x);
	return std::array<float, 4>{c[0] * c[3], c[1] * c[3], c[2] * c[3], GetAlpha(x)};
}

std::array<float, 4> Gradient::GetColorAndIntensity(float x) const
{
	if (ColorCount == 0)
	{
		return std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f};
	}

	if (x < Colors[0].Position)
	{
		const auto c = Colors[0].Color;
		return {c[0], c[1], c[2], Colors[0].Intensity};
	}

	if (Colors[ColorCount - 1].Position <= x)
	{
		const auto c = Colors[ColorCount - 1].Color;
		return {c[0], c[1], c[2], Colors[ColorCount - 1].Intensity};
	}

	auto key = ColorKey();
	key.Position = x;

	auto it = std::lower_bound(Colors.begin(), Colors.begin() + ColorCount, key, [](const ColorKey& a, const ColorKey& b)
							   { return a.Position < b.Position; });
	auto ind = static_cast<int32_t>(std::distance(Colors.begin(), it));

	{
		if (Colors[ind].Position != x)
		{
			ind--;
		}

		if (Colors[ind].Position <= x && x <= Colors[ind + 1].Position)
		{
			const auto area = Colors[ind + 1].Position - Colors[ind].Position;
			if (area == 0)
			{
				return std::array<float, 4>{Colors[ind].Color[0], Colors[ind].Color[1], Colors[ind].Color[2], Colors[ind].Intensity};
			}

			const auto alpha = (x - Colors[ind].Position) / area;
			const auto r = Colors[ind + 1].Color[0] * alpha + Colors[ind].Color[0] * (1.0f - alpha);
			const auto g = Colors[ind + 1].Color[1] * alpha + Colors[ind].Color[1] * (1.0f - alpha);
			const auto b = Colors[ind + 1].Color[2] * alpha + Colors[ind].Color[2] * (1.0f - alpha);
			const auto intensity = Colors[ind + 1].Intensity * alpha + Colors[ind].Intensity * (1.0f - alpha);
			return std::array<float, 4>{r, g, b, intensity};
		}
		else
		{
			assert(0);
		}
	}

	return std::array<float, 4>{1.0f, 1.0f, 1.0f, 1.0f};
}

float Gradient::GetAlpha(float x) const
{
	if (AlphaCount == 0)
	{
		return 1.0f;
	}

	if (x < Alphas[0].Position)
	{
		return Alphas[0].Alpha;
	}

	if (Alphas[AlphaCount - 1].Position <= x)
	{
		return Alphas[AlphaCount - 1].Alpha;
	}

	auto key = AlphaKey();
	key.Position = x;

	auto it = std::lower_bound(Alphas.begin(), Alphas.begin() + AlphaCount, key, [](const AlphaKey& a, const AlphaKey& b)
							   { return a.Position < b.Position; });
	auto ind = static_cast<int32_t>(std::distance(Alphas.begin(), it));

	{
		if (Alphas[ind].Position != x)
		{
			ind--;
		}

		if (Alphas[ind].Position <= x && x <= Alphas[ind + 1].Position)
		{
			const auto area = Alphas[ind + 1].Position - Alphas[ind].Position;
			if (area == 0)
			{
				return Alphas[ind].Alpha;
			}

			const auto alpha = (x - Alphas[ind].Position) / area;
			return Alphas[ind + 1].Alpha * alpha + Alphas[ind].Alpha * (1.0f - alpha);
		}
		else
		{
			assert(0);
		}
	}

	return 1.0f;
}

} // namespace Effekseer<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.6.36); FILE MERGED 2008/04/01 15:05:19 thb 1.6.36.3: #i85898# Stripping all external header guards 2008/04/01 12:26:24 thb 1.6.36.2: #i85898# Stripping all external header guards 2008/03/31 12:19:27 rt 1.6.36.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|>


<commit_before>/*
    This file is part of Kontact.
    Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>

    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, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qcheckbox.h>
#include <qlayout.h>

#include <dcopref.h>

#include <kaboutdata.h>
#include <kaccelmanager.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klistview.h>
#include <klocale.h>

#include "kcmkmailsummary.h"

extern "C"
{
  KCModule *create_kmailsummary( QWidget *parent, const char * )
  {
    return new KCMKMailSummary( parent, "kcmkmailsummary" );
  }
}

KCMKMailSummary::KCMKMailSummary( QWidget *parent, const char *name )
  : KCModule( parent, name )
{
  initGUI();

  connect( mFolderView, SIGNAL( clicked( QListViewItem* ) ), SLOT( modified() ) );
  connect( mFullPath, SIGNAL( toggled( bool ) ), SLOT( modified() ) );

  KAcceleratorManager::manage( this );

  load();
}

void KCMKMailSummary::modified()
{
  emit changed( true );
}

void KCMKMailSummary::initGUI()
{
  QVBoxLayout *layout = new QVBoxLayout( this, KDialog::marginHint(),
                                         KDialog::spacingHint() );

  mFolderView = new KListView( this );
  mFolderView->setRootIsDecorated( true );
  mFolderView->setFullWidth( true );

  mFolderView->addColumn( i18n( "Summary" ) );

  mFullPath = new QCheckBox( i18n( "Show full path for folders" ), this );

  layout->addWidget( mFolderView );
  layout->addWidget( mFullPath );
}

void KCMKMailSummary::initFolders()
{
  DCOPRef kmail( "kmail", "KMailIface" );

  QStringList folderList;
  kmail.call( "folderList" ).get( folderList );

  mFolderView->clear();
  mFolderMap.clear();

  bool firstFound = false;
  QStringList::Iterator it;
  for ( it = folderList.begin(); it != folderList.end(); ++it ) {
    QString displayName;
    if ( !firstFound ) {
      // The first one is the local folders. Can't test for *it to be "/Local", it's translated.
      firstFound = true;
      displayName = i18n( "prefix for local folders", "Local" );
    } else {
      DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
      folderRef.call( "displayName()" ).get( displayName );
    }
    if ( (*it).contains( '/' ) == 1 ) {
      if ( mFolderMap.find( *it ) == mFolderMap.end() )
        mFolderMap.insert( *it, new QListViewItem( mFolderView,
                                                   displayName ) );
    } else {
      const int pos = (*it).findRev( '/' );
      const QString parentFolder = (*it).left( pos );
      mFolderMap.insert( *it,
                         new QCheckListItem( mFolderMap[ parentFolder ],
                                             displayName,
                                             QCheckListItem::CheckBox ) );
    }
  }
}

void KCMKMailSummary::loadFolders()
{
  KConfig config( "kcmkmailsummaryrc" );
  config.setGroup( "General" );

  QStringList folders;
  if ( !config.hasKey( "ActiveFolders" ) )
    folders << "/Local/inbox";
  else
    folders = config.readListEntry( "ActiveFolders" );

  QMap<QString, QListViewItem*>::Iterator it;
  for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it ) {
    if ( QCheckListItem *qli = dynamic_cast<QCheckListItem*>( it.data() ) ) {
      if ( folders.contains( it.key() ) ) {
        qli->setOn( true );
        mFolderView->ensureItemVisible( it.data() );
      } else {
        qli->setOn( false );
      }
    }
  }
  mFullPath->setChecked( config.readBoolEntry( "ShowFullPath", false ) );
}

void KCMKMailSummary::storeFolders()
{
  KConfig config( "kcmkmailsummaryrc" );
  config.setGroup( "General" );

  QStringList folders;

  QMap<QString, QListViewItem*>::Iterator it;
  for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it )
    if ( QCheckListItem *qli = dynamic_cast<QCheckListItem*>( it.data() ) )
      if ( qli->isOn() )
        folders.append( it.key() );

  config.writeEntry( "ActiveFolders", folders );
  config.writeEntry( "ShowFullPath", mFullPath->isChecked() );

  config.sync();
}

void KCMKMailSummary::load()
{
  initFolders();
  loadFolders();

  emit changed( false );
}

void KCMKMailSummary::save()
{
  storeFolders();

  emit changed( false );
}

void KCMKMailSummary::defaults()
{
}

const KAboutData* KCMKMailSummary::aboutData() const
{
  KAboutData *about = new KAboutData( I18N_NOOP( "kcmkmailsummary" ),
                                      I18N_NOOP( "Mail Summary Configuration Dialog" ),
                                      0, 0, KAboutData::License_GPL,
                                      I18N_NOOP( "(c) 2004 Tobias Koenig" ) );

  about->addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" );

  return about;
}

#include "kcmkmailsummary.moc"
<commit_msg>Ingo's kmkernel commit makes this fix unnecessary again<commit_after>/*
    This file is part of Kontact.
    Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>

    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, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qcheckbox.h>
#include <qlayout.h>

#include <dcopref.h>

#include <kaboutdata.h>
#include <kaccelmanager.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klistview.h>
#include <klocale.h>

#include "kcmkmailsummary.h"

extern "C"
{
  KCModule *create_kmailsummary( QWidget *parent, const char * )
  {
    return new KCMKMailSummary( parent, "kcmkmailsummary" );
  }
}

KCMKMailSummary::KCMKMailSummary( QWidget *parent, const char *name )
  : KCModule( parent, name )
{
  initGUI();

  connect( mFolderView, SIGNAL( clicked( QListViewItem* ) ), SLOT( modified() ) );
  connect( mFullPath, SIGNAL( toggled( bool ) ), SLOT( modified() ) );

  KAcceleratorManager::manage( this );

  load();
}

void KCMKMailSummary::modified()
{
  emit changed( true );
}

void KCMKMailSummary::initGUI()
{
  QVBoxLayout *layout = new QVBoxLayout( this, KDialog::marginHint(),
                                         KDialog::spacingHint() );

  mFolderView = new KListView( this );
  mFolderView->setRootIsDecorated( true );
  mFolderView->setFullWidth( true );

  mFolderView->addColumn( i18n( "Summary" ) );

  mFullPath = new QCheckBox( i18n( "Show full path for folders" ), this );

  layout->addWidget( mFolderView );
  layout->addWidget( mFullPath );
}

void KCMKMailSummary::initFolders()
{
  DCOPRef kmail( "kmail", "KMailIface" );

  QStringList folderList;
  kmail.call( "folderList" ).get( folderList );

  mFolderView->clear();
  mFolderMap.clear();

  QStringList::Iterator it;
  for ( it = folderList.begin(); it != folderList.end(); ++it ) {
    QString displayName;
    if ( (*it) == "/Local" )
      displayName = i18n( "prefix for local folders", "Local" );
    else {
      DCOPRef folderRef = kmail.call( "getFolder(QString)", *it );
      folderRef.call( "displayName()" ).get( displayName );
    }
    if ( (*it).contains( '/' ) == 1 ) {
      if ( mFolderMap.find( *it ) == mFolderMap.end() )
        mFolderMap.insert( *it, new QListViewItem( mFolderView,
                                                   displayName ) );
    } else {
      const int pos = (*it).findRev( '/' );
      const QString parentFolder = (*it).left( pos );
      mFolderMap.insert( *it,
                         new QCheckListItem( mFolderMap[ parentFolder ],
                                             displayName,
                                             QCheckListItem::CheckBox ) );
    }
  }
}

void KCMKMailSummary::loadFolders()
{
  KConfig config( "kcmkmailsummaryrc" );
  config.setGroup( "General" );

  QStringList folders;
  if ( !config.hasKey( "ActiveFolders" ) )
    folders << "/Local/inbox";
  else
    folders = config.readListEntry( "ActiveFolders" );

  QMap<QString, QListViewItem*>::Iterator it;
  for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it ) {
    if ( QCheckListItem *qli = dynamic_cast<QCheckListItem*>( it.data() ) ) {
      if ( folders.contains( it.key() ) ) {
        qli->setOn( true );
        mFolderView->ensureItemVisible( it.data() );
      } else {
        qli->setOn( false );
      }
    }
  }
  mFullPath->setChecked( config.readBoolEntry( "ShowFullPath", false ) );
}

void KCMKMailSummary::storeFolders()
{
  KConfig config( "kcmkmailsummaryrc" );
  config.setGroup( "General" );

  QStringList folders;

  QMap<QString, QListViewItem*>::Iterator it;
  for ( it = mFolderMap.begin(); it != mFolderMap.end(); ++it )
    if ( QCheckListItem *qli = dynamic_cast<QCheckListItem*>( it.data() ) )
      if ( qli->isOn() )
        folders.append( it.key() );

  config.writeEntry( "ActiveFolders", folders );
  config.writeEntry( "ShowFullPath", mFullPath->isChecked() );

  config.sync();
}

void KCMKMailSummary::load()
{
  initFolders();
  loadFolders();

  emit changed( false );
}

void KCMKMailSummary::save()
{
  storeFolders();

  emit changed( false );
}

void KCMKMailSummary::defaults()
{
}

const KAboutData* KCMKMailSummary::aboutData() const
{
  KAboutData *about = new KAboutData( I18N_NOOP( "kcmkmailsummary" ),
                                      I18N_NOOP( "Mail Summary Configuration Dialog" ),
                                      0, 0, KAboutData::License_GPL,
                                      I18N_NOOP( "(c) 2004 Tobias Koenig" ) );

  about->addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" );

  return about;
}

#include "kcmkmailsummary.moc"
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* 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 :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
// Author: Hadrien Courtecuisse
//
// Copyright: See COPYING file that comes with this distribution
#include <sofa/component/linearsolver/SparseTAUCSSolver.h>
#include <sofa/core/ObjectFactory.h>
#include <iostream>
#include "sofa/helper/system/thread/CTime.h"
#include <sofa/core/objectmodel/BaseContext.h>
#include <sofa/core/behavior/LinearSolver.h>
#include <math.h>
#include <sofa/helper/system/thread/CTime.h>
#include <sofa/component/linearsolver/CompressedRowSparseMatrix.inl>

namespace sofa
{

namespace component
{

namespace linearsolver
{

using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
using namespace sofa::simulation;
using namespace sofa::core::objectmodel;
using sofa::helper::system::thread::CTime;
using sofa::helper::system::thread::ctime_t;
using std::cerr;
using std::endl;

template<class TMatrix, class TVector>
SparseTAUCSSolver<TMatrix,TVector>::SparseTAUCSSolver()
    : f_options( initData(&f_options,"options","TAUCS unified solver list of space-separated options") )
    , f_symmetric( initData(&f_symmetric,true,"symmetric","Consider the system matrix as symmetric") )
    , f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
#ifdef SOFA_HAVE_CILK
    , f_nproc( initData(&f_nproc,(unsigned) 1,"nproc","NB proc used in taucs library") )
#endif
{
}

template<class T>
int get_taucs_flags();

template<>
int get_taucs_flags<double>() { return TAUCS_DOUBLE; }

template<>
int get_taucs_flags<float>() { return TAUCS_SINGLE; }

template<class TMatrix, class TVector>
void SparseTAUCSSolver<TMatrix,TVector>::invert(Matrix& M)
{
    M.compress();

    SparseTAUCSSolverInvertData * data = (SparseTAUCSSolverInvertData *) getMatrixInvertData(&M);
    if (f_symmetric.getValue())
    {
        data->Mfiltered.copyUpperNonZeros(M);
        sout << "Filtered upper part of M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl;
    }
    else
    {
        data->Mfiltered.copyNonZeros(M);
        sout << "Filtered M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl;
    }
    data->Mfiltered.fullRows();
    data->matrix_taucs.n = data->Mfiltered.rowSize();
    data->matrix_taucs.m = data->Mfiltered.colSize();
    data->matrix_taucs.flags = get_taucs_flags<Real>();
    if (f_symmetric.getValue())
    {
        data->matrix_taucs.flags |= TAUCS_SYMMETRIC;
        data->matrix_taucs.flags |= TAUCS_LOWER; // Upper on row-major is actually lower on column-major transposed matrix
    }
    data->matrix_taucs.colptr = (int *) &(data->Mfiltered.getRowBegin()[0]);
    data->matrix_taucs.rowind = (int *) &(data->Mfiltered.getColsIndex()[0]);
    data->matrix_taucs.values.d = (double*) &(data->Mfiltered.getColsValue()[0]);
    helper::vector<char*> opts;

    const helper::vector<std::string>& options = f_options.getValue();
    if (options.size()==0)
    {
        opts.push_back((char *) "taucs.factor.LLT=true");
        opts.push_back((char *) "taucs.factor.ordering=metis");
    }
    else
    {
        for (unsigned int i=0; i<options.size(); ++i) opts.push_back((char*)options[i].c_str());
    }
#ifdef SOFA_HAVE_CILK
    if (f_nproc.getValue()>1)
    {
        char buf[64];
        sprintf(buf,"taucs.cilk.nproc=%d",f_nproc.getValue());
        opts.push_back(buf);
        opts.push_back((char *) "taucs.factor.mf=true");
    }
#endif
    opts.push_back(NULL);

    if (this->f_printLog.getValue())
        taucs_logfile((char*)"stdout");
    if (data->factorization) taucs_linsolve(NULL, &data->factorization, 0, NULL, NULL, NULL, NULL);
    int rc = taucs_linsolve(&data->matrix_taucs, &data->factorization, 0, NULL, NULL, &(opts[0]), NULL);
    if (this->f_printLog.getValue())
        taucs_logfile((char*)"none");
    if (rc != TAUCS_SUCCESS)
    {
        const char* er = "";
        switch(rc)
        {
        case TAUCS_SUCCESS: er = "SUCCESS"; break;
        case TAUCS_ERROR  : er = "ERROR"; break;
        case TAUCS_ERROR_NOMEM: er = "NOMEM"; break;
        case TAUCS_ERROR_BADARGS: er = "BADARGS"; break;
        case TAUCS_ERROR_MAXDEPTH: er = "MAXDEPTH"; break;
        case TAUCS_ERROR_INDEFINITE: er = "INDEFINITE"; break;
        }
        serr << "TAUCS factorization failed: " << er << sendl;
    }
}

template<class TMatrix, class TVector>
void SparseTAUCSSolver<TMatrix,TVector>::solve (Matrix& M, Vector& z, Vector& r)
{
    SparseTAUCSSolverInvertData * data = (SparseTAUCSSolverInvertData *) getMatrixInvertData(&M);

    helper::vector<char*> opts;
    const helper::vector<std::string>& options = f_options.getValue();
    if (options.size()==0)
    {
        opts.push_back((char *) "taucs.factor.LLT=true");
        opts.push_back((char *) "taucs.factor.ordering=metis");
    }
    else
    {
        for (unsigned int i=0; i<options.size(); ++i) opts.push_back((char*)options[i].c_str());
    }

    opts.push_back((char*)"taucs.factor=false");
    //opts.push_back((char*)"taucs.factor.symbolic=false");
    //opts.push_back((char*)"taucs.factor.numeric=false");
    opts.push_back(NULL);
    if (this->f_printLog.getValue())
        taucs_logfile((char*)"stdout");
    int rc = taucs_linsolve(&data->matrix_taucs, &data->factorization, 1, z.ptr(), r.ptr(), &(opts[0]), NULL);
    if (this->f_printLog.getValue())
        taucs_logfile((char*)"none");
    if (rc != TAUCS_SUCCESS)
    {
        const char* er = "";
        switch(rc)
        {
        case TAUCS_SUCCESS: er = "SUCCESS"; break;
        case TAUCS_ERROR  : er = "ERROR"; break;
        case TAUCS_ERROR_NOMEM: er = "NOMEM"; break;
        case TAUCS_ERROR_BADARGS: er = "BADARGS"; break;
        case TAUCS_ERROR_MAXDEPTH: er = "MAXDEPTH"; break;
        case TAUCS_ERROR_INDEFINITE: er = "INDEFINITE"; break;
        }
        serr << "TAUCS solve failed: " << er << sendl;
    }
}

SOFA_DECL_CLASS(SparseTAUCSSolver)

int SparseTAUCSSolverClass = core::RegisterObject("Direct linear solvers implemented with the TAUCS library")
        .add< SparseTAUCSSolver< CompressedRowSparseMatrix<double>,FullVector<double> > >()
        .add< SparseTAUCSSolver< CompressedRowSparseMatrix<defaulttype::Mat<3,3,double> >,FullVector<double> > >(true)
        .add< SparseTAUCSSolver< CompressedRowSparseMatrix<float>,FullVector<float> > >()
        .add< SparseTAUCSSolver< CompressedRowSparseMatrix<defaulttype::Mat<3,3,float> >,FullVector<float> > >()
        .addAlias("TAUCSSolver")
        ;

} // namespace linearsolver

} // namespace component

} // namespace sofa

<commit_msg>r9716/sofa-dev : FIX : Remove trace.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* 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 :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
// Author: Hadrien Courtecuisse
//
// Copyright: See COPYING file that comes with this distribution
#include <sofa/component/linearsolver/SparseTAUCSSolver.h>
#include <sofa/core/ObjectFactory.h>
#include <iostream>
#include "sofa/helper/system/thread/CTime.h"
#include <sofa/core/objectmodel/BaseContext.h>
#include <sofa/core/behavior/LinearSolver.h>
#include <math.h>
#include <sofa/helper/system/thread/CTime.h>
#include <sofa/component/linearsolver/CompressedRowSparseMatrix.inl>

namespace sofa
{

namespace component
{

namespace linearsolver
{

using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
using namespace sofa::simulation;
using namespace sofa::core::objectmodel;
using sofa::helper::system::thread::CTime;
using sofa::helper::system::thread::ctime_t;
using std::cerr;
using std::endl;

template<class TMatrix, class TVector>
SparseTAUCSSolver<TMatrix,TVector>::SparseTAUCSSolver()
    : f_options( initData(&f_options,"options","TAUCS unified solver list of space-separated options") )
    , f_symmetric( initData(&f_symmetric,true,"symmetric","Consider the system matrix as symmetric") )
    , f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
#ifdef SOFA_HAVE_CILK
    , f_nproc( initData(&f_nproc,(unsigned) 1,"nproc","NB proc used in taucs library") )
#endif
{
}

template<class T>
int get_taucs_flags();

template<>
int get_taucs_flags<double>() { return TAUCS_DOUBLE; }

template<>
int get_taucs_flags<float>() { return TAUCS_SINGLE; }

template<class TMatrix, class TVector>
void SparseTAUCSSolver<TMatrix,TVector>::invert(Matrix& M)
{
    M.compress();

    SparseTAUCSSolverInvertData * data = (SparseTAUCSSolverInvertData *) getMatrixInvertData(&M);
    if (f_symmetric.getValue())
    {
        data->Mfiltered.copyUpperNonZeros(M);
        if (this->f_printLog.getValue())
            sout << "Filtered upper part of M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl;
    }
    else
    {
        data->Mfiltered.copyNonZeros(M);
        if (this->f_printLog.getValue())
            sout << "Filtered M, nnz = " << data->Mfiltered.getRowBegin().back() << sendl;
    }
    data->Mfiltered.fullRows();
    data->matrix_taucs.n = data->Mfiltered.rowSize();
    data->matrix_taucs.m = data->Mfiltered.colSize();
    data->matrix_taucs.flags = get_taucs_flags<Real>();
    if (f_symmetric.getValue())
    {
        data->matrix_taucs.flags |= TAUCS_SYMMETRIC;
        data->matrix_taucs.flags |= TAUCS_LOWER; // Upper on row-major is actually lower on column-major transposed matrix
    }
    data->matrix_taucs.colptr = (int *) &(data->Mfiltered.getRowBegin()[0]);
    data->matrix_taucs.rowind = (int *) &(data->Mfiltered.getColsIndex()[0]);
    data->matrix_taucs.values.d = (double*) &(data->Mfiltered.getColsValue()[0]);
    helper::vector<char*> opts;

    const helper::vector<std::string>& options = f_options.getValue();
    if (options.size()==0)
    {
        opts.push_back((char *) "taucs.factor.LLT=true");
        opts.push_back((char *) "taucs.factor.ordering=metis");
    }
    else
    {
        for (unsigned int i=0; i<options.size(); ++i) opts.push_back((char*)options[i].c_str());
    }
#ifdef SOFA_HAVE_CILK
    if (f_nproc.getValue()>1)
    {
        char buf[64];
        sprintf(buf,"taucs.cilk.nproc=%d",f_nproc.getValue());
        opts.push_back(buf);
        opts.push_back((char *) "taucs.factor.mf=true");
    }
#endif
    opts.push_back(NULL);

    if (this->f_printLog.getValue())
        taucs_logfile((char*)"stdout");
    if (data->factorization) taucs_linsolve(NULL, &data->factorization, 0, NULL, NULL, NULL, NULL);
    int rc = taucs_linsolve(&data->matrix_taucs, &data->factorization, 0, NULL, NULL, &(opts[0]), NULL);
    if (this->f_printLog.getValue())
        taucs_logfile((char*)"none");
    if (rc != TAUCS_SUCCESS)
    {
        const char* er = "";
        switch(rc)
        {
        case TAUCS_SUCCESS: er = "SUCCESS"; break;
        case TAUCS_ERROR  : er = "ERROR"; break;
        case TAUCS_ERROR_NOMEM: er = "NOMEM"; break;
        case TAUCS_ERROR_BADARGS: er = "BADARGS"; break;
        case TAUCS_ERROR_MAXDEPTH: er = "MAXDEPTH"; break;
        case TAUCS_ERROR_INDEFINITE: er = "INDEFINITE"; break;
        }
        serr << "TAUCS factorization failed: " << er << sendl;
    }
}

template<class TMatrix, class TVector>
void SparseTAUCSSolver<TMatrix,TVector>::solve (Matrix& M, Vector& z, Vector& r)
{
    SparseTAUCSSolverInvertData * data = (SparseTAUCSSolverInvertData *) getMatrixInvertData(&M);

    helper::vector<char*> opts;
    const helper::vector<std::string>& options = f_options.getValue();
    if (options.size()==0)
    {
        opts.push_back((char *) "taucs.factor.LLT=true");
        opts.push_back((char *) "taucs.factor.ordering=metis");
    }
    else
    {
        for (unsigned int i=0; i<options.size(); ++i) opts.push_back((char*)options[i].c_str());
    }

    opts.push_back((char*)"taucs.factor=false");
    //opts.push_back((char*)"taucs.factor.symbolic=false");
    //opts.push_back((char*)"taucs.factor.numeric=false");
    opts.push_back(NULL);
    if (this->f_printLog.getValue())
        taucs_logfile((char*)"stdout");
    int rc = taucs_linsolve(&data->matrix_taucs, &data->factorization, 1, z.ptr(), r.ptr(), &(opts[0]), NULL);
    if (this->f_printLog.getValue())
        taucs_logfile((char*)"none");
    if (rc != TAUCS_SUCCESS)
    {
        const char* er = "";
        switch(rc)
        {
        case TAUCS_SUCCESS: er = "SUCCESS"; break;
        case TAUCS_ERROR  : er = "ERROR"; break;
        case TAUCS_ERROR_NOMEM: er = "NOMEM"; break;
        case TAUCS_ERROR_BADARGS: er = "BADARGS"; break;
        case TAUCS_ERROR_MAXDEPTH: er = "MAXDEPTH"; break;
        case TAUCS_ERROR_INDEFINITE: er = "INDEFINITE"; break;
        }
        serr << "TAUCS solve failed: " << er << sendl;
    }
}

SOFA_DECL_CLASS(SparseTAUCSSolver)

int SparseTAUCSSolverClass = core::RegisterObject("Direct linear solvers implemented with the TAUCS library")
        .add< SparseTAUCSSolver< CompressedRowSparseMatrix<double>,FullVector<double> > >()
        .add< SparseTAUCSSolver< CompressedRowSparseMatrix<defaulttype::Mat<3,3,double> >,FullVector<double> > >(true)
        .add< SparseTAUCSSolver< CompressedRowSparseMatrix<float>,FullVector<float> > >()
        .add< SparseTAUCSSolver< CompressedRowSparseMatrix<defaulttype::Mat<3,3,float> >,FullVector<float> > >()
        .addAlias("TAUCSSolver")
        ;

} // namespace linearsolver

} // namespace component

} // namespace sofa

<|endoftext|>


<commit_before>
#include <cnoid/Plugin>
#include <cnoid/ItemTreeView>
#include <cnoid/BodyItem>
#include <cnoid/ToolBar>

using namespace std;
using namespace cnoid;

class PrototypePlugin : public Plugin
{
public:

    PrototypePlugin() : Plugin("PrototypePlugin")
    {
        require("Body");
    }

    virtual bool initialize()
    {
        ToolBar* toolbar = new ToolBar("PrototypeToolbar");
        toolbar->addButton("Movement++")
            ->sigClicked().connect(bind(&PrototypePlugin::onButtonClicked, this, +0.04));
        toolbar->addButton("Movement--")
                ->sigClicked().connect(bind(&PrototypePlugin::onButtonClicked, this, -0.04));
        addToolBar(toolbar);

        return true;
    }

    void onButtonClicked(double dq)
    {
        ItemList<BodyItem> bodyItems =
            ItemTreeView::mainInstance()->selectedItems<BodyItem>();

        for(size_t i=0; i < bodyItems.size(); ++i){
            BodyPtr body = bodyItems[i]->body();
            for(int j=0; j < body->numJoints(); ++j){
                body->joint(j)->q() += dq;
            }
            bodyItems[i]->notifyKinematicStateChange(true);
        }
    }
};

CNOID_IMPLEMENT_PLUGIN_ENTRY(PrototypePlugin)
<commit_msg>test prototype<commit_after>#include <cnoid/Plugin>
#include <cnoid/ItemTreeView>
#include <cnoid/BodyItem>
#include <cnoid/ToolBar>
#include <cnoid/SimpleController>
#include <cnoid/MenuManager>
#include <cnoid/MessageView>
#include <string>
#include <stdlib.h>

using namespace std;
using namespace cnoid;

class PrototypePlugin : public Plugin
{
public:
    bool leftLeg;
	int frame_count;
	Action* menuItem = menuManager().setPath("/View").addItem("Frame Count");
    PrototypePlugin() : Plugin("PrototypePlugin")
    {
        require("Body");

    }
    virtual bool initialize()
	{
		leftLeg = true;
		frame_count = 0;
		ToolBar* TB = new ToolBar("InMoov Kinematics");
		TB->addButton("Walk")
			->sigClicked()
			.connect(bind(&PrototypePlugin::onButtonClicked, this, +0.02));
		/* From here, add buttons and functionality to the TB.
		ToolBar class has member functions for adding buttons
		and defining how the joint sliders react when clicked.
		It is a self-bound function. Look around at the other
		predefined functions for guidance. */

		TB->addButton("SwingLegs")
			->sigClicked()
			.connect(bind(&PrototypePlugin::swingLegs, this, 0.04));
		TB->addButton("RotateRLEG")
			->sigClicked()
			.connect(bind(&PrototypePlugin::changeOrientationR, this, 0.04));
		TB->addButton("RotateLLEG")
			->sigClicked()
			.connect(bind(&PrototypePlugin::changeOrientationL, this, 0.04));
		TB->addButton("Frames++")
			->sigClicked()
			.connect(bind(&PrototypePlugin::changeFrame, this, 100));

		menuItem->sigTriggered().connect(bind(&PrototypePlugin::frameTrigger, this));
		/* Note that this virtual function must return true.
		It may be a good idea to use this restriction as a
		testing parameter */
    addToolBar(TB);
		return true;
	}

   void onButtonClicked(double dq)
	{
		/* vector of type BodyItem */
		ItemList<BodyItem> bodyItems =
		    ItemTreeView::mainInstance()->selectedItems<BodyItem>();

		/* size_t is defined as unsigned long long - to be used for large iterative values > 0 */
		/* for loop: for each body item, assign a pointer to it, same with joints internal loop */
		for(size_t i=0; i < bodyItems.size(); ++i){
		    BodyPtr body = bodyItems[i]->body();
		    for(int j=0; j < body->numJoints(); ++j){
		        body->joint(j)->q() += dq;
		    }
		    bodyItems[i]->notifyKinematicStateChange(true);
		}
	}

 	void swingLegs(double dq)
    	{
		ItemList<BodyItem> bodyItems =
		    ItemTreeView::mainInstance()->selectedItems<BodyItem>();

		for(size_t i=0; i < bodyItems.size(); ++i){
		    BodyPtr body = bodyItems[i]->body();
		    int lleg_hip_p = body->link("LLEG_HIP_P")->jointId();
		    int rleg_hip_p = body->link("RLEG_HIP_P")->jointId();
		    int lleg_knee = body->link("LLEG_KNEE")->jointId();
		    int rleg_knee = body->link("RLEG_KNEE")->jointId();

		    if(body->joint(lleg_hip_p)->q() < -1) {
		        this->leftLeg = true;
		    } else if(body->joint(lleg_hip_p)->q() > 1) {
		        this->leftLeg = false;
		    }

		    if(this->leftLeg) {
		        body->joint(lleg_hip_p)->q() += dq;
		        if(body->joint(lleg_knee)->q() > 0)
		            body->joint(lleg_knee)->q() -= dq;
		        body->joint(rleg_hip_p)->q() -= dq;
		        body->joint(rleg_knee)->q() += dq;
		    } else {
		        body->joint(lleg_hip_p)->q() -= dq;
		        body->joint(lleg_knee)->q() += dq;
		        body->joint(rleg_hip_p)->q() += dq;
		        if(body->joint(rleg_knee)->q() > 0)
		            body->joint(rleg_knee)->q() -= dq;

		    }
		    bodyItems[i]->notifyKinematicStateChange(true);
		}
    	}
	void changeOrientationL(double dq)
	{
		ItemList<BodyItem> bodyItems =
		    ItemTreeView::mainInstance()->selectedItems<BodyItem>();
		for(size_t i=0; i < bodyItems.size(); ++i){
		    BodyPtr body = bodyItems[i]->body();
			int LLEG_HIP_Y = body->link("LLEG_HIP_Y")->jointId();
			int RLEG_HIP_Y = body->link("RLEG_HIP_Y")->jointId();

		body->joint(LLEG_HIP_Y)->q() += dq;
   bodyItems[i]->notifyKinematicStateChange(true);
		}

	}

	void changeOrientationR(double dq) {
	ItemList<BodyItem> bodyItems =
		    ItemTreeView::mainInstance()->selectedItems<BodyItem>();
		for(size_t i=0; i < bodyItems.size(); ++i){
		    BodyPtr body = bodyItems[i]->body();
			int LLEG_HIP_Y = body->link("LLEG_HIP_Y")->jointId();
			int RLEG_HIP_Y = body->link("RLEG_HIP_Y")->jointId();

		body->joint(RLEG_HIP_Y)->q() += dq;
   bodyItems[i]->notifyKinematicStateChange(true);
		}
	}

	void changeFrame(int frames) {
		frame_count += frames;
	}

void frameTrigger()
    {
	string frameNum = to_string(frame_count);
        MessageView::instance()->putln("Frames to be walked: ");
	MessageView::instance()->putln(frameNum);
    }
};

CNOID_IMPLEMENT_PLUGIN_ENTRY(PrototypePlugin)
<|endoftext|>


<commit_before>///
/// \file PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto/AddNuTaskPionPionRoot6.C
/// \author Andrew Kubera, Ohio State University, andrew.kubera@cern.ch
///

#include <TROOT.h>

#include <TString.h>
#include <TList.h>
#include <TObjArray.h>
#include <TObjString.h>

#include <AliAnalysisManager.h>

#include "AliAnalysisTaskFemtoNu.h"

/// \class MacroCfg
/// \brief All parameters for this macro
///
struct MacroCfg : public TNamed {

  TString macro = "%%/ConfigNuFemtoAnalysisR6.C",
          auto_directory = "$ALICE_PHYSICS/PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto",
          output_filename,
          output_container = "PWG2FEMTO",
          subwagon_array = "",
          subwagon_type = "centrality";

  MacroCfg()
    : TNamed("cfg", "MacroCfg")
    , output_filename(AliAnalysisManager::GetAnalysisManager()->GetCommonFileName())
    {}

  TString GetFilename()
    {
      return (output_container == "")
           ? output_filename
           : TString::Format("%s:%s", output_filename.Data(), output_container.Data());
    }
};

/// \brief Adds an AliAnalysisTaskFemtoNu analysis object, constructed
///        with parameters provided, to the global AliAnalysisManager.
///
/// This macro creates and returns an :class:`AliAnalysisTaskFemto` object.
/// The task object is given a macro
/// is given the config macro "Train/PionPionFemto/ConfigFemtoAnalysis.C"
/// which is run to create the analysis objects.
/// This is fixed (for now), and if an alternative is required, you
/// should use the general AddTaskFemto.C macro.
///
/// Subwagons are supported, the name of which will be appended to
/// the task name.
/// The task name by default is "TaskPionPionFemto" which cannot be
/// changed.
///
/// The output container name is fixed at the standard "femtolist".
///
/// \param configuration
///     A string containing commands to execute, separated by semicolons.
///     Assign the old parameters using this command.
///     Single quotes are turned to double quotes.
///
///     * macro: Path to the FemtoConfig macro to load; "%%" is
///          expaneded to directory containing this file.
///     * output_filename: Name of the output file to produce.
///         Default generated by AliAnalysisManager::GetCommonFileName()
///     * output_container: Name of top-level ROOT directory in the output file.
///         Default is the classic 'PWG2FEMTO'.
///     * container: Name of the AliAnalysis container.
///     * task_name: Name of the AliAnalysisTask - May need to be unique...
///     * verbose: Task created in verbose mode
///
/// \param params
///     A string forwarded to the ConfigFemtoAnalysis macro for parsing.
///     This string is wrapped in double-quotes so escaping some to
///     ensure results is a string is unneccessary.
///
/// \param subwagon_suffix
///     If this macro is run in a train with subwagons, this will be
///     set with the identifier.
///
AliAnalysisTask* AddNuTaskPionPionRoot6(TString container,
                                        TString configuration,
                                        TString params,
                                        TString subwagon_suffix)
{
  std::cout << "\n\n============== AddNuTaskPionPion (ROOT6 Version) ===============\n";

  // Get the global analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddNuTaskPionPion", "Could not get the global AliAnalysisManager.");
    return nullptr;
  }

  MacroCfg cfg;

  bool verbose = kFALSE;

  TObjArray* lines = configuration.Tokenize("\n;");

  TIter next_line(lines);
  TObject *line_obj = nullptr;

  gDirectory->Add(&cfg);

  while ((line_obj = next_line())) {
    TObjString *s = static_cast<TObjString*>(line_obj);
    TString cmd = s->String().Strip(TString::kBoth, ' ');
    if (cmd.IsWhitespace()) {
      continue;
    }

    cmd.ReplaceAll("'", '"');

    cmd = "static_cast<MacroCfg*>(cfg)->" + cmd + ";";

    std::cout << "running `" << cmd  << "`\n";
    gROOT->ProcessLineFast(cmd);
  }

  gDirectory->Remove(&cfg);

  // Replace %% with this directory for convenience
  cfg.macro.ReplaceAll("%%", cfg.auto_directory);

  // Dealing with subwagons
  if (!subwagon_suffix.IsWhitespace()) {
    Int_t index = subwagon_suffix.Atoi();
    TObjArray *values = cfg.subwagon_array.Tokenize(",");
    TIter next_value(values);
    if (values->GetEntries() < index) {
      std::cerr << "Could not use subwagon-index " << index << " in subwagon_array of only " << values->GetEntries() << " entries\n";
      return nullptr;
    }
    for (int i=0; i<index; ++i) {
      next_value();
    }
    TString ss = ((TObjString*)next_value())->String();
    params += ";" + cfg.subwagon_type + " = " + ss;

    container += "_" + subwagon_suffix;
  }

  std::cout << "[AddTaskPionPion]\n"
               "   container: " << container << "\n"
               "   output: '" << cfg.output_filename << "'\n"
               "   macro: '" << cfg.macro << "'\n"
               "   params: '" << params << "'\n";

  // The analysis config macro for PionPionFemto accepts a single string
  // argument, which it interprets.
  // This line escapes some escapable characters (backslash, newline, tab)
  // and wraps that string in double quotes, ensuring that the interpreter
  // reads a string when passing to the macro.
  const TString analysis_params = '"' + params.ReplaceAll("\\", "\\\\")
                                              .ReplaceAll("\n", "\\n")
                                              .ReplaceAll("\"", "\\\"")
                                              .ReplaceAll("\t", "\\t") + '"';

  std::cout << "   params-normalized: '" << analysis_params << "'\n";

  AliAnalysisTaskFemto *femtotask = new AliAnalysisTaskFemtoNu(
    container,
    cfg.macro,
    analysis_params,
    verbose
  );

  mgr->AddTask(femtotask);

  const TString outputfile = cfg.GetFilename();
  auto *out_container = mgr->CreateContainer(container,
                                             AliFemtoResultStorage::Class(),
                                             AliAnalysisManager::kOutputContainer,
                                             outputfile);

  mgr->ConnectInput(femtotask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(femtotask, AliAnalysisTaskFemtoNu::RESULT_STORAGE_OUTPUT_SLOT, out_container);

  // quiet a warning
  out_container = mgr->CreateContainer(container + "_list",
                                       TList::Class(),
                                       AliAnalysisManager::kOutputContainer,
                                       outputfile);
  mgr->ConnectOutput(femtotask, 0, out_container);

  std::cout << "============== AddNuTaskPionPion : Done ===============\n\n";
  return femtotask;
}

AliAnalysisTask*
AddNuTaskPionPionRoot6(TString container,
                       TString configuration,
                       TString params="")
{
  return AddNuTaskPionPionRoot6(container, configuration, params, "");
}

AliAnalysisTask*
AddNuTaskPionPionRoot6(TString container)
{
  AddNuTaskPionPionRoot6(container, "", "");
  return nullptr;
}
<commit_msg>FemtoAnalysisPion - Update train-macro to tokenize using ~ and compile config-macro by default<commit_after>///
/// \file PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto/AddNuTaskPionPionRoot6.C
/// \author Andrew Kubera, Ohio State University, andrew.kubera@cern.ch
///

#include <TROOT.h>

#include <TString.h>
#include <TList.h>
#include <TObjArray.h>
#include <TObjString.h>

#include <AliAnalysisManager.h>

#include "AliAnalysisTaskFemtoNu.h"

/// \class MacroCfg
/// \brief All parameters for this macro
///
struct MacroCfg : public TNamed {

  TString macro = "%%/ConfigNuFemtoAnalysisR6.C+",
          auto_directory = "$ALICE_PHYSICS/PWGCF/FEMTOSCOPY/macros/Train/PionPionFemto",
          output_filename,
          output_container = "PWG2FEMTO",
          subwagon_array = "",
          subwagon_type = "centrality";

  MacroCfg()
    : TNamed("cfg", "MacroCfg")
    , output_filename(AliAnalysisManager::GetAnalysisManager()->GetCommonFileName())
    {}

  TString GetFilename()
    {
      return (output_container == "")
           ? output_filename
           : TString::Format("%s:%s", output_filename.Data(), output_container.Data());
    }
};

/// \brief Adds an AliAnalysisTaskFemtoNu analysis object, constructed
///        with parameters provided, to the global AliAnalysisManager.
///
/// This macro creates and returns an :class:`AliAnalysisTaskFemto` object.
/// The task object is given a macro
/// is given the config macro "Train/PionPionFemto/ConfigFemtoAnalysis.C"
/// which is run to create the analysis objects.
/// This is fixed (for now), and if an alternative is required, you
/// should use the general AddTaskFemto.C macro.
///
/// Subwagons are supported, the name of which will be appended to
/// the task name.
/// The task name by default is "TaskPionPionFemto" which cannot be
/// changed.
///
/// The output container name is fixed at the standard "femtolist".
///
/// \param configuration
///     A string containing commands to execute, separated by semicolons.
///     Assign the old parameters using this command.
///     Single quotes are turned to double quotes.
///
///     * macro: Path to the FemtoConfig macro to load; "%%" is
///          expaneded to directory containing this file.
///     * output_filename: Name of the output file to produce.
///         Default generated by AliAnalysisManager::GetCommonFileName()
///     * output_container: Name of top-level ROOT directory in the output file.
///         Default is the classic 'PWG2FEMTO'.
///     * container: Name of the AliAnalysis container.
///     * task_name: Name of the AliAnalysisTask - May need to be unique...
///     * verbose: Task created in verbose mode
///
/// \param params
///     A string forwarded to the ConfigFemtoAnalysis macro for parsing.
///     This string is wrapped in double-quotes so escaping some to
///     ensure results is a string is unneccessary.
///
/// \param subwagon_suffix
///     If this macro is run in a train with subwagons, this will be
///     set with the identifier.
///
AliAnalysisTask* AddNuTaskPionPionRoot6(TString container,
                                        TString configuration,
                                        TString params,
                                        TString subwagon_suffix)
{
  std::cout << "\n\n============== AddNuTaskPionPion (ROOT6 Version) ===============\n";

  // Get the global analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddNuTaskPionPion", "Could not get the global AliAnalysisManager.");
    return nullptr;
  }

  MacroCfg cfg;

  bool verbose = kFALSE;

  TObjArray* lines = configuration.Tokenize("\n;");

  TIter next_line(lines);
  TObject *line_obj = nullptr;

  gDirectory->Add(&cfg);

  while ((line_obj = next_line())) {
    TObjString *s = static_cast<TObjString*>(line_obj);
    TString cmd = s->String().Strip(TString::kBoth, ' ');
    if (cmd.IsWhitespace()) {
      continue;
    }

    cmd.ReplaceAll("'", '"');

    cmd = "static_cast<MacroCfg*>(cfg)->" + cmd + ";";

    std::cout << "running `" << cmd  << "`\n";
    gROOT->ProcessLineFast(cmd);
  }

  gDirectory->Remove(&cfg);

  // Replace %% with this directory for convenience
  cfg.macro.ReplaceAll("%%", cfg.auto_directory);

  // Dealing with subwagons
  if (!subwagon_suffix.IsWhitespace()) {
    Int_t index = subwagon_suffix.Atoi();
    TObjArray *values = cfg.subwagon_array.Tokenize("~");
    TIter next_value(values);
    if (values->GetEntries() < index) {
      std::cerr << "Could not use subwagon-index " << index << " in subwagon_array of only " << values->GetEntries() << " entries\n";
      return nullptr;
    }
    for (int i=0; i<index; ++i) {
      next_value();
    }
    TString ss = ((TObjString*)next_value())->String();
    params += ";" + cfg.subwagon_type + " = " + ss;

    container += "_" + subwagon_suffix;
  }

  std::cout << "[AddTaskPionPion]\n"
               "   container: " << container << "\n"
               "   output: '" << cfg.output_filename << "'\n"
               "   macro: '" << cfg.macro << "'\n"
               "   params: '" << params << "'\n";

  // The analysis config macro for PionPionFemto accepts a single string
  // argument, which it interprets.
  // This line escapes some escapable characters (backslash, newline, tab)
  // and wraps that string in double quotes, ensuring that the interpreter
  // reads a string when passing to the macro.
  const TString analysis_params = '"' + params.ReplaceAll("\\", "\\\\")
                                              .ReplaceAll("\n", "\\n")
                                              .ReplaceAll("\"", "\\\"")
                                              .ReplaceAll("\t", "\\t") + '"';

  std::cout << "   params-normalized: '" << analysis_params << "'\n";

  AliAnalysisTaskFemto *femtotask = new AliAnalysisTaskFemtoNu(
    container,
    cfg.macro,
    analysis_params,
    verbose
  );

  mgr->AddTask(femtotask);

  const TString outputfile = cfg.GetFilename();
  auto *out_container = mgr->CreateContainer(container,
                                             AliFemtoResultStorage::Class(),
                                             AliAnalysisManager::kOutputContainer,
                                             outputfile);

  mgr->ConnectInput(femtotask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(femtotask, AliAnalysisTaskFemtoNu::RESULT_STORAGE_OUTPUT_SLOT, out_container);

  // quiet a warning
  out_container = mgr->CreateContainer(container + "_list",
                                       TList::Class(),
                                       AliAnalysisManager::kOutputContainer,
                                       outputfile);
  mgr->ConnectOutput(femtotask, 0, out_container);

  std::cout << "============== AddNuTaskPionPion : Done ===============\n\n";
  return femtotask;
}

AliAnalysisTask*
AddNuTaskPionPionRoot6(TString container,
                       TString configuration,
                       TString params="")
{
  return AddNuTaskPionPionRoot6(container, configuration, params, "");
}

AliAnalysisTask*
AddNuTaskPionPionRoot6(TString container)
{
  AddNuTaskPionPionRoot6(container, "", "");
  return nullptr;
}
<|endoftext|>


<commit_before><commit_msg>Avoid undefined signed integer overflow<commit_after><|endoftext|>