<commit_before>/*
 * Jamoma NodeLib
 * Copyright © 2008, Tim Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "NodeLib.h"

JamomaNode::JamomaNode(TTSymbolPtr oscAddress, TTSymbolPtr newType, ObjectPtr newObject):TTObject(oscAddress->getCString())
{
	TTSymbolPtr oscAddress_parent;
	TTSymbolPtr oscAddress_name;
	TTSymbolPtr oscAddress_instance;
	TTSymbolPtr oscAddress_attribute;
	TTBoolean parent_created;
	TTErr err;

	// split the oscAddress in /parent/name
	err = splitOSCAddress(oscAddress,&oscAddress_parent,&oscAddress_name, &oscAddress_instance, &oscAddress_attribute);

	// DEBUG
	post("JamomaNode : %s",oscAddress->getCString());
	if(oscAddress_parent)
		post("	parent : %s ",oscAddress_parent->getCString());
	if(oscAddress_name)
		post("	name : %s ",oscAddress_name->getCString());
	if(oscAddress_instance)
		post("	instance : %s ",oscAddress_instance->getCString());
	if(oscAddress_attribute)
		post("	attribute : %s ",oscAddress_attribute->getCString());

	if(err == kTTErrNone){

		this->name = oscAddress_name;
		this->type = newType;
		this->maxObject = newObject;
		this->instance = oscAddress_instance;

		// create a hashtab
		this->children = new TTHash();

		// ensure that the path to the new node exists
		if(oscAddress_parent){
			parent_created = false;
			JamomaNodeCheck(oscAddress_parent, &this->parent, &parent_created);
		}

		// register the node with his OSC address in the jamoma_node_hashtab
		jamoma_node_hashtab->append(TT(oscAddress->getCString()),this);

	}
}

JamomaNode::~JamomaNode()
{
	;
}

#if 0
#pragma mark -
#pragma mark Static Methods
#endif

TTSymbolPtr	JamomaNode::getName(){return this->name;}
TTSymbolPtr	JamomaNode::getInstance(){return this->instance;}
TTSymbolPtr	JamomaNode::getType(){return this->type;}
ObjectPtr	JamomaNode::getMaxObject(){return this->maxObject;}
JamomaNodePtr	JamomaNode::getParent(){return this->parent;}
TTHashPtr	JamomaNode::getChildren(){return this->children;}

TTErr	JamomaNode::getDump()
{
	uint i;
	TTValue *hk = NULL;
	TTValue *c = NULL;
	JamomaNodePtr* n_c = NULL;

	// CRASH !!!
	post("dump : here I tried to display the name and the instance of the node");
	post("!!! BUT IT CRASHES !!!");
	//post("%s.%s",this->name->getCString(),this->instance->getCString());

	// DON'T CRASH
	post("dump : here I display the type of the node");
	post("type %s",this->type->getCString());

	//this->children->getKeys(*hk);

	//post("%d children",this->children->getSize());

	//for(i=0; i<this->children->getSize(); i++){
	//	this->children->lookup(hk[i],*c);
	//	c->get(0,(TTPtr*)n_c);
	//	(*n_c)->getDump();
	//}

	return kTTErrNone;
}

TTErr JamomaNode::getNodeForOSC(const char* oscAddress, JamomaNodePtr* returnedNode)
{
	return getNodeForOSC(TT((char*)oscAddress), returnedNode);
}

TTErr JamomaNode::getNodeForOSC(TTSymbolPtr oscAddress, JamomaNodePtr* returnedNode)
{
	TTValue* found = new TTValue();

	// look into the hashtab to check if the address exist in the tree
	jamoma_node_hashtab->lookup(oscAddress,*found);

	// if this address doesn't exist
	if(found == kTTErrValueNotFound)
		return kTTErrGeneric;

	else{

		found->get(0,(TTPtr*)returnedNode);
		return kTTErrNone;
	}

}

TTErr JamomaNodeLookup(TTSymbolPtr oscAddress, LinkedListPtr* returnedNodes, JamomaNodePtr* firstReturnedNode)
{
	return kTTErrNone;
}

TTErr JamomaNodeCreate(TTSymbolPtr oscAddress, TTSymbolPtr newType, ObjectPtr newObject, JamomaNodePtr* returnedNode, TTBoolean* created)
{
	TTValue* found;
	TTErr err;

	// look into the hashtab to check if the address exist in the tree
	found = new TTValue();
	err = jamoma_node_hashtab->lookup(oscAddress,*found);

	// if this address doesn't exist
	if(err == kTTErrValueNotFound){

		// we create the node
		JamomaNodePtr new_node = new JamomaNode(oscAddress, newType, newObject);

		// if the node have parent
		if(new_node->getParent())
			// add this node as a children of his parent
			new_node->getParent()->getChildren()->append(oscAddress,new_node);
		else
			// this is the root
			;

		*returnedNode = new_node;
		*created = true;
		return kTTErrNone;
	}

	// else this address already exist
	else{

		// TODO: create an instance

		found->get(0,(TTPtr*)returnedNode);
		*created = true;
		return kTTErrNone;
	}

}

TTErr JamomaNodeCheck(TTSymbolPtr oscAddress, JamomaNodePtr* returnedNode, TTBoolean* created)
{
	TTValue* found;
	TTErr err;
	TTBoolean parent_created;

	// look into the hashtab to check if the address exist in the tree
	found = new TTValue();
	err = jamoma_node_hashtab->lookup(oscAddress,*found);

	//// if the address doesn't exist
	if(err == kTTErrValueNotFound){

		post("JamomaNodeCheck : %s doesn't exists", oscAddress->getCString());

	//	// we create a container node
		JamomaNodePtr new_node = new JamomaNode(oscAddress, TT("container"), NULL);

	//	// if the node have parent
	//	if(new_node->getParent())
	//		// add this node as a children of his parent
	//		new_node->getParent()->getChildren()->append(key,new_node);
	//	else
	//		// this is the root
	//		;

		*returnedNode = new_node;
		*created = true;
	}

	return kTTErrNone;
}

TTErr splitOSCAddress(TTSymbolPtr oscAddress, TTSymbolPtr* returnedParentOscAdress, TTSymbolPtr* returnedNodeName, TTSymbolPtr* returnedNodeInstance, TTSymbolPtr* returnedNodeAttribute)
{
	int i, len, pos;
	bool stop;
	char *last_colon, *last_slash, *last_dot;
	char *attribute, *parent, *node, *instance;
	char *to_split;

	// Make sure we are dealing with valid OSC input by looking for a leading slash
	if(oscAddress->getCString()[0] != '/')
		return kTTErrGeneric;

	to_split = (char *)malloc(sizeof(char)*(strlen(oscAddress->getCString())+1));
	strcpy(to_split,oscAddress->getCString());

	// find the last ':' in the OSCaddress
	// if exists, split the OSC address in an address part (to split) and an attribute part
	len = strlen(to_split);
	last_colon = strrchr(to_split,':');
	pos = (int)last_colon - (int)to_split;

	if(last_colon){
		attribute = (char *)malloc(sizeof(char)*(len - (pos+1)));
		strcpy(attribute,to_split + pos+1);
		*returnedNodeAttribute = TT(attribute);

		to_split[pos] = NULL;	// split to keep only the address part
	}
	else
		*returnedNodeAttribute = NULL;

	// find the last '/' in the address part
	// if exists, split the address part in a node part (to split) and a parent part
	len = strlen(to_split);
	last_slash = strrchr(to_split,'/');
	pos = (int)last_slash - (int)to_split;

	if(last_slash && pos){		// && pos to avoid the root
		parent = (char *)malloc(sizeof(char)*(pos+1));
		strncpy(parent,to_split,pos);
		parent[pos] = NULL;
		*returnedParentOscAdress = TT(parent);

		to_split = last_slash+1;	// split to keep only the node part
	}
	else
		*returnedParentOscAdress = NULL;

	// find the last '.' in the node part
	// if exists, split the node part in a name part and an instance part
	len = strlen(to_split);
	last_dot = strrchr(to_split,'.');
	pos = (int)last_dot - (int)to_split;

	if(last_dot > 0){
		instance = (char *)malloc(sizeof(char)*(len - (pos+1)));
		strcpy(instance,to_split + pos+1);
		*returnedNodeInstance = TT(instance);

		to_split[pos] = NULL;	// split to keep only the name part
	}
	else
		*returnedNodeInstance = NULL;

	// TODO : ??? (detect unusual characters in a node name)
	if(strlen(to_split) > 0){
		if(*returnedParentOscAdress)
			*returnedNodeName = TT(to_split);
		else
			*returnedNodeName = TT(to_split+1); // to remove the slash when it's the root
	}
	else
		*returnedNodeName = NULL;

	return kTTErrNone;
}

/************************************************************************************/

JamomaError	jamoma_node_init()
{
	if(jamoma_node_root)
		return JAMOMA_ERR_NONE;	// already have a root, do nothing...

	post("> CREATION OF AN EXPERIMENTAL TREE");
	post("");

	jamoma_node_hashtab = new TTHash();
	jamoma_node_root = new JamomaNode(TT("/jamoma"), TT("container"), NULL);

	// TEST : an experimental tree
	JamomaNodePtr test;

	test = new JamomaNode(TT("/jamoma/degrade~/bitdepth"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/degrade~/bypass"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/degrade~/gain"), TT("parameter"), NULL);

	test = new JamomaNode(TT("/jamoma/input.1/pan"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/input.1/gain"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/input.2/pan"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/input.2/gain"), TT("parameter"), NULL);

	test = new JamomaNode(TT("/jamoma/output/audio/gain"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/output/limiter"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/output/preamp"), TT("parameter"), NULL);

	post("");
	post("> DUMP THE TREE");
	post("");
	post("> dump the root");
	jamoma_node_root->getDump();
	post("");
	post("> dump the node /jamoma/output/preamp");
	test->getDump();

	return JAMOMA_ERR_NONE;
}

void jamoma_node_free(void)
{
	;
}
<commit_msg>a dump function to display the tree<commit_after>/*
 * Jamoma NodeLib
 * Copyright © 2008, Tim Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "NodeLib.h"

JamomaNode::JamomaNode(TTSymbolPtr oscAddress, TTSymbolPtr newType, ObjectPtr newObject):TTObject(oscAddress->getCString())
{
	TTSymbolPtr oscAddress_parent;
	TTSymbolPtr oscAddress_name;
	TTSymbolPtr oscAddress_instance;
	TTSymbolPtr oscAddress_attribute;
	TTBoolean parent_created;
	TTErr err;

	// split the oscAddress in /parent/name
	err = splitOSCAddress(oscAddress,&oscAddress_parent,&oscAddress_name, &oscAddress_instance, &oscAddress_attribute);

	// DEBUG
	post("JamomaNode : %s",oscAddress->getCString());
	if(oscAddress_parent)
		post("	parent : %s ",oscAddress_parent->getCString());
	if(oscAddress_name)
		post("	name : %s ",oscAddress_name->getCString());
	if(oscAddress_instance)
		post("	instance : %s ",oscAddress_instance->getCString());
	if(oscAddress_attribute)
		post("	attribute : %s ",oscAddress_attribute->getCString());

	if(err == kTTErrNone){

		this->name = oscAddress_name;
		this->type = newType;
		this->maxObject = newObject;
		this->instance = oscAddress_instance;

		// create a hashtab
		this->children = new TTHash();

		// ensure that the path to the new node exists
		if(oscAddress_parent){
			parent_created = false;
			JamomaNodeCheck(oscAddress_parent, &this->parent, &parent_created);
			// add this node as a children of his parent
			this->getParent()->getChildren()->append(oscAddress_name,this);
		}
		else
			// this is the root
			;

		// register the node with his OSC address in the jamoma_node_hashtab
		jamoma_node_hashtab->append(TT(oscAddress->getCString()),this);

	}
}

JamomaNode::~JamomaNode()
{
	;
}

#if 0
#pragma mark -
#pragma mark Static Methods
#endif

TTSymbolPtr	JamomaNode::getName(){return this->name;}
TTSymbolPtr	JamomaNode::getInstance(){return this->instance;}
TTSymbolPtr	JamomaNode::getType(){return this->type;}
ObjectPtr	JamomaNode::getMaxObject(){return this->maxObject;}
JamomaNodePtr	JamomaNode::getParent(){return this->parent;}
TTHashPtr	JamomaNode::getChildren(){return this->children;}

TTErr	JamomaNode::getDump()
{
	uint i;
	TTValue *hk;
	TTSymbolPtr key;
	TTValue *c;
	JamomaNodePtr n_c;

	if(this->name && this->instance)
		post("%s.%s",this->name->getCString(),this->instance->getCString());
	else
		if(this->name)
			post("%s",this->name->getCString());

	if(this->children->getSize()){
		post("{");

		hk = new TTValue();
		c = new TTValue();
		this->children->getKeys(*hk);

		for(i=0; i<this->children->getSize(); i++){
			hk->get(i,(TTSymbol**)&key);
			this->children->lookup(key,*c);
			c->get(0,(TTPtr*)&n_c);
			n_c->getDump();
		}

		post("}");
	}

	return kTTErrNone;
}

TTErr JamomaNode::getNodeForOSC(const char* oscAddress, JamomaNodePtr* returnedNode)
{
	return getNodeForOSC(TT((char*)oscAddress), returnedNode);
}

TTErr JamomaNode::getNodeForOSC(TTSymbolPtr oscAddress, JamomaNodePtr* returnedNode)
{
	TTValue* found = new TTValue();

	// look into the hashtab to check if the address exist in the tree
	jamoma_node_hashtab->lookup(oscAddress,*found);

	// if this address doesn't exist
	if(found == kTTErrValueNotFound)
		return kTTErrGeneric;

	else{

		found->get(0,(TTPtr*)returnedNode);
		return kTTErrNone;
	}

}

TTErr JamomaNodeLookup(TTSymbolPtr oscAddress, LinkedListPtr* returnedNodes, JamomaNodePtr* firstReturnedNode)
{
	return kTTErrNone;
}

TTErr JamomaNodeCreate(TTSymbolPtr oscAddress, TTSymbolPtr newType, ObjectPtr newObject, JamomaNodePtr* returnedNode, TTBoolean* created)
{
	TTValue* found;
	TTErr err;

	// look into the hashtab to check if the address exist in the tree
	found = new TTValue();
	err = jamoma_node_hashtab->lookup(oscAddress,*found);

	// if this address doesn't exist
	if(err == kTTErrValueNotFound){

		// we create the node
		JamomaNodePtr new_node = new JamomaNode(oscAddress, newType, newObject);

		*returnedNode = new_node;
		*created = true;
		return kTTErrNone;
	}

	// else this address already exist
	else{

		// TODO: create an instance

		found->get(0,(TTPtr*)returnedNode);
		*created = true;
		return kTTErrNone;
	}

}

TTErr JamomaNodeCheck(TTSymbolPtr oscAddress, JamomaNodePtr* returnedNode, TTBoolean* created)
{
	TTValue* found;
	TTErr err;
	TTBoolean parent_created;

	// look into the hashtab to check if the address exist in the tree
	found = new TTValue();
	*created = false;
	err = jamoma_node_hashtab->lookup(oscAddress,*found);

	//// if the address doesn't exist
	if(err == kTTErrValueNotFound){

		post("JamomaNodeCheck : %s doesn't exists", oscAddress->getCString());

		// we create a container node
		JamomaNodePtr new_node = new JamomaNode(oscAddress, TT("container"), NULL);

		*returnedNode = new_node;
		*created = true;
	}
	else
		found->get(0,(TTPtr*)returnedNode);

	return kTTErrNone;
}

TTErr splitOSCAddress(TTSymbolPtr oscAddress, TTSymbolPtr* returnedParentOscAdress, TTSymbolPtr* returnedNodeName, TTSymbolPtr* returnedNodeInstance, TTSymbolPtr* returnedNodeAttribute)
{
	int i, len, pos;
	bool stop;
	char *last_colon, *last_slash, *last_dot;
	char *attribute, *parent, *node, *instance;
	char *to_split;

	// Make sure we are dealing with valid OSC input by looking for a leading slash
	if(oscAddress->getCString()[0] != '/')
		return kTTErrGeneric;

	to_split = (char *)malloc(sizeof(char)*(strlen(oscAddress->getCString())+1));
	strcpy(to_split,oscAddress->getCString());

	// find the last ':' in the OSCaddress
	// if exists, split the OSC address in an address part (to split) and an attribute part
	len = strlen(to_split);
	last_colon = strrchr(to_split,':');
	pos = (int)last_colon - (int)to_split;

	if(last_colon){
		attribute = (char *)malloc(sizeof(char)*(len - (pos+1)));
		strcpy(attribute,to_split + pos+1);
		*returnedNodeAttribute = TT(attribute);

		to_split[pos] = NULL;	// split to keep only the address part
	}
	else
		*returnedNodeAttribute = NULL;

	// find the last '/' in the address part
	// if exists, split the address part in a node part (to split) and a parent part
	len = strlen(to_split);
	last_slash = strrchr(to_split,'/');
	pos = (int)last_slash - (int)to_split;

	if(last_slash && pos){		// && pos to avoid the root
		parent = (char *)malloc(sizeof(char)*(pos+1));
		strncpy(parent,to_split,pos);
		parent[pos] = NULL;
		*returnedParentOscAdress = TT(parent);

		to_split = last_slash+1;	// split to keep only the node part
	}
	else
		*returnedParentOscAdress = NULL;

	// find the last '.' in the node part
	// if exists, split the node part in a name part and an instance part
	len = strlen(to_split);
	last_dot = strrchr(to_split,'.');
	pos = (int)last_dot - (int)to_split;

	if(last_dot > 0){
		instance = (char *)malloc(sizeof(char)*(len - (pos+1)));
		strcpy(instance,to_split + pos+1);
		*returnedNodeInstance = TT(instance);

		to_split[pos] = NULL;	// split to keep only the name part
	}
	else
		*returnedNodeInstance = NULL;

	// TODO : ??? (detect unusual characters in a node name)
	if(strlen(to_split) > 0){
		if(*returnedParentOscAdress)
			*returnedNodeName = TT(to_split);
		else
			*returnedNodeName = TT(to_split+1); // to remove the slash when it's the root
	}
	else
		*returnedNodeName = NULL;

	return kTTErrNone;
}

/************************************************************************************/

JamomaError	jamoma_node_init()
{
	if(jamoma_node_root)
		return JAMOMA_ERR_NONE;	// already have a root, do nothing...

	post("> CREATION OF AN EXPERIMENTAL TREE");
	post("");

	jamoma_node_hashtab = new TTHash();
	jamoma_node_root = new JamomaNode(TT("/jamoma"), TT("container"), NULL);

	// TEST : an experimental tree
	JamomaNodePtr test;

	test = new JamomaNode(TT("/jamoma/degrade~/bitdepth"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/degrade~/bypass"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/degrade~/gain"), TT("parameter"), NULL);

	test = new JamomaNode(TT("/jamoma/input.1/pan"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/input.1/gain"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/input.2/pan"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/input.2/gain"), TT("parameter"), NULL);

	test = new JamomaNode(TT("/jamoma/output/audio/gain"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/output/limiter"), TT("parameter"), NULL);
	test = new JamomaNode(TT("/jamoma/output/preamp"), TT("parameter"), NULL);

	post("");
	post("> DUMP THE TREE");
	post("");
	jamoma_node_root->getDump();

	return JAMOMA_ERR_NONE;
}

void jamoma_node_free(void)
{
	;
}
<|endoftext|>


<commit_before>/*
 * Jamoma RampLib Base Class
 * Copyright © 2008, Tim Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#ifdef WIN_VERSION
 #pragma warning(disable:4083) //warning C4083: expected 'newline'; found identifier 's'
#endif // WIN_VERSION

#include "RampLib.h"
#include "ext.h"

RampUnit::RampUnit(const char* rampName, RampUnitCallback aCallbackMethod, void *aBaton)
	: TTObject(rampName), startValue(NULL), targetValue(NULL), currentValue(NULL), normalizedValue(0.0), numValues(0), functionUnit(NULL)
{
	callback = aCallbackMethod;
	baton = aBaton;
	setNumValues(1);
	currentValue[0] = 0.0;
	targetValue[0] = 0.0;
	startValue[0] = 0.0;

	registerAttribute(TT("function"),	kTypeSymbol,	&attrFunction,	(TTSetterMethod)&RampUnit::setFunction);
	setAttributeValue(TT("function"), TT("linear"));
}

RampUnit::~RampUnit()
{
	delete functionUnit;
	delete [] currentValue;
	delete [] targetValue;
	delete [] startValue;
}

void RampUnit::set(TTUInt32 newNumValues, TTFloat64 *newValues)
{
	TTUInt32 i;

	stop();
	setNumValues(newNumValues);
	for(i=0; i<newNumValues; i++)
		currentValue[i] = newValues[i];
}

TTErr RampUnit::setFunction(const TTValue& functionName)
{
	TTErr	err;

	attrFunction = functionName;
	err = FunctionLib::createUnit(attrFunction, &functionUnit);
	if(err)
		logError("Jamoma ramp unit failed to load the requested FunctionUnit from TTBlue.");
	return err;
}

TTErr RampUnit::getFunctionParameterNames(TTSymbol* parameterName, TTValue& names)
{
	functionUnit->getAttributeNames(names);
	return kTTErrNone;
}

TTErr RampUnit::setFunctionParameterValue(TTSymbol* parameterName, const TTValue& newValue)
{
	functionUnit->setAttributeValue(parameterName, newValue);
	return kTTErrNone;
}

TTErr RampUnit::getFunctionParameterValue(TTSymbol* parameterName, TTValue& value)
{
	functionUnit->getAttributeValue(parameterName, value);
	return kTTErrNone;
}

void RampUnit::setNumValues(TTUInt32 newNumValues)
{
	if(newNumValues != numValues){
		if(numValues != 0){
			delete [] currentValue;
			delete [] targetValue;
			delete [] startValue;
		}

		currentValue = new TTFloat64[newNumValues];
		targetValue = new TTFloat64[newNumValues];
		startValue = new TTFloat64[newNumValues];
		numValues = newNumValues;
	}
	sendMessage(TT("numValuesChanged"));	// Notify sub-classes (if they respond to this message)
}

/***************************************************************************
	RampLib
 ***************************************************************************/

#include "AsyncRamp.h"
#include "NoneRamp.h"
#include "QueueRamp.h"
#include "SchedulerRamp.h"

JamomaError RampLib::createUnit(const TTSymbol* unitName, RampUnit **unit, RampUnitCallback callback, void* baton)
{
	if(*unit)
		delete *unit;

	// These should be alphabetized
	if(unitName == TT("async"))
		*unit = (RampUnit*) new AsyncRamp(callback, baton);
	else if(unitName == TT("none"))
		*unit = (RampUnit*) new NoneRamp(callback, baton);
	else if(unitName == TT("queue"))
		*unit = (RampUnit*) new QueueRamp(callback, baton);
	else if(unitName == TT("scheduler"))
		*unit = (RampUnit*) new SchedulerRamp(callback, baton);
	else {
		// Invalid function specified default to linear
//		TTLogError("rampLib: Invalid rampUnit: %s", (char*)unitName);
		error("puke");
		*unit = (RampUnit*) new NoneRamp(callback, baton);
	}
	return JAMOMA_ERR_NONE;
}

void RampLib::getUnitNames(TTValue& unitNames)
{
	unitNames.clear();
	unitNames.append(TT("async"));
	unitNames.append(TT("none"));
	unitNames.append(TT("queue"));
	unitNames.append(TT("scheduler"));
}

<commit_msg>If 'none' is specified for a ramp function, then linear is used.<commit_after>/*
 * Jamoma RampLib Base Class
 * Copyright © 2008, Tim Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#ifdef WIN_VERSION
 #pragma warning(disable:4083) //warning C4083: expected 'newline'; found identifier 's'
#endif // WIN_VERSION

#include "RampLib.h"
#include "ext.h"

RampUnit::RampUnit(const char* rampName, RampUnitCallback aCallbackMethod, void *aBaton)
	: TTObject(rampName), startValue(NULL), targetValue(NULL), currentValue(NULL), normalizedValue(0.0), numValues(0), functionUnit(NULL)
{
	callback = aCallbackMethod;
	baton = aBaton;
	setNumValues(1);
	currentValue[0] = 0.0;
	targetValue[0] = 0.0;
	startValue[0] = 0.0;

	registerAttribute(TT("function"),	kTypeSymbol,	&attrFunction,	(TTSetterMethod)&RampUnit::setFunction);
	setAttributeValue(TT("function"), TT("linear"));
}

RampUnit::~RampUnit()
{
	delete functionUnit;
	delete [] currentValue;
	delete [] targetValue;
	delete [] startValue;
}

void RampUnit::set(TTUInt32 newNumValues, TTFloat64 *newValues)
{
	TTUInt32 i;

	stop();
	setNumValues(newNumValues);
	for(i=0; i<newNumValues; i++)
		currentValue[i] = newValues[i];
}

TTErr RampUnit::setFunction(const TTValue& functionName)
{
	TTErr	err;

	attrFunction = functionName;
	if(attrFunction == TT("none"))
		attrFunction = TT("linear");

	err = FunctionLib::createUnit(attrFunction, &functionUnit);
	if(err)
		logError("Jamoma ramp unit failed to load the requested FunctionUnit from TTBlue.");
	return err;
}

TTErr RampUnit::getFunctionParameterNames(TTSymbol* parameterName, TTValue& names)
{
	functionUnit->getAttributeNames(names);
	return kTTErrNone;
}

TTErr RampUnit::setFunctionParameterValue(TTSymbol* parameterName, const TTValue& newValue)
{
	functionUnit->setAttributeValue(parameterName, newValue);
	return kTTErrNone;
}

TTErr RampUnit::getFunctionParameterValue(TTSymbol* parameterName, TTValue& value)
{
	functionUnit->getAttributeValue(parameterName, value);
	return kTTErrNone;
}

void RampUnit::setNumValues(TTUInt32 newNumValues)
{
	if(newNumValues != numValues){
		if(numValues != 0){
			delete [] currentValue;
			delete [] targetValue;
			delete [] startValue;
		}

		currentValue = new TTFloat64[newNumValues];
		targetValue = new TTFloat64[newNumValues];
		startValue = new TTFloat64[newNumValues];
		numValues = newNumValues;
	}
	sendMessage(TT("numValuesChanged"));	// Notify sub-classes (if they respond to this message)
}

/***************************************************************************
	RampLib
 ***************************************************************************/

#include "AsyncRamp.h"
#include "NoneRamp.h"
#include "QueueRamp.h"
#include "SchedulerRamp.h"

JamomaError RampLib::createUnit(const TTSymbol* unitName, RampUnit **unit, RampUnitCallback callback, void* baton)
{
	if(*unit)
		delete *unit;

	// These should be alphabetized
	if(unitName == TT("async"))
		*unit = (RampUnit*) new AsyncRamp(callback, baton);
	else if(unitName == TT("none"))
		*unit = (RampUnit*) new NoneRamp(callback, baton);
	else if(unitName == TT("queue"))
		*unit = (RampUnit*) new QueueRamp(callback, baton);
	else if(unitName == TT("scheduler"))
		*unit = (RampUnit*) new SchedulerRamp(callback, baton);
	else {
		// Invalid function specified default to linear
//		TTLogError("rampLib: Invalid rampUnit: %s", (char*)unitName);
		error("puke");
		*unit = (RampUnit*) new NoneRamp(callback, baton);
	}
	return JAMOMA_ERR_NONE;
}

void RampLib::getUnitNames(TTValue& unitNames)
{
	unitNames.clear();
	unitNames.append(TT("async"));
	unitNames.append(TT("none"));
	unitNames.append(TT("queue"));
	unitNames.append(TT("scheduler"));
}

<|endoftext|>


<commit_before>#include "ofApp.h"

//#include "ECURabbitObject.h"
#include "ecuaObject.h"

ofVec3f p;

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetVerticalSync(true);
//    mesh.load("lofi-bunny.ply");

//    cout << cam.getTarget().getPosition() << endl;
    universe = new ECUUniverse();
    universe->addObject(new ecuaObject(ofVec3f(0, 0, -1000)));
    //    cam.disableMouseInput();

    //    cam.set

    ofSetSmoothLighting(true);
    pointLight2.setDiffuseColor( ofFloatColor(.3, .3, .3));
    pointLight2.setSpecularColor(ofFloatColor(10, 10, 10));
    pointLight2.setPosition(120, 80, 500);

<<<<<<< HEAD
=======

    currentEditingObj = NULL;

>>>>>>> b2dd5efc5cac1a8e1fe86c0dd15be4646f103e27
//    ofAddListener(ofEvent::mousePressed, &control, control::mousePressed)
//    ofAddListener(ofEvents().mouseDragged , &control, &ctrls::mouseDragged);
//    ofAddListener(ofEvents().mousePressed, &control, &ctrls::mousePressed);
//    ofAddListener(ofEvents().mouseReleased, &control, &ctrls::mouseReleased);
//    ofAddListener(ofEvents().mouseScrolled, &control, &ctrls::mouseScrolled);

//    ofRegisterMouseEvents(control);

}

void ofApp::exit() {
    delete universe;
}

//--------------------------------------------------------------
void ofApp::update(){
    universe->update();
    control.update();
}

//--------------------------------------------------------------
void ofApp::draw(){
    ofBackgroundGradient(ofColor(64), ofColor(0));

    ofSetColor(255);

    ofEnableDepthTest();
    ofEnableLighting();
    pointLight2.enable();

    universe->draw();

    ofDisableLighting();
    ofDisableDepthTest();

    if(currentEditingObj != NULL) {
        control.draw();
    }
}

bool zDown = false;

#define KEY(k, f) if(key == (k)) { (f); }

void ofApp::createObject() {

    if(currentEditingObj != NULL) {
        //we are now going to turn off, this means that we need to place the object in
        currentEditingObj = NULL;
    }

    else {
        ECUBaseObject *obj = new ecuaObject(ofVec3f(universe->pos.x, universe->pos.y, universe->pos.z-1000));
        currentEditingObj = obj;
        universe->addObject(obj);
    }

//    creatingObject = !creatingObject;
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

    KEY('z', zDown = true)

    KEY('a', createObject())

//    KEY('s', currentEditingObj = NULL)

    cout << "current pos = " << universe->pos << endl;
    cout << "there are " << universe->objects.size() << " objects" << endl;

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){
    zDown = false;
}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
    control.mouseMoved(x, y);
}

ofVec3f downPosition;
ofQuaternion downOrientation;

float mouseRange = 0;

void ofApp::mouseDragged(int x, int y, int button) {

    control.mouseDragged(x, y, button);

    for (int i = 0; i < control.amnt; i++) {
        currentEditingObj->setParam(i, control.fadersPos[i]);

        //if we found an object, set the of the control to the object so there is no jump

    }

}

//--------------------------------------------------------------
void ofApp::mouseScrolled(float x, float y) {
    if (zDown) {
        universe->pos.z+= -y;
    }
    else {
        universe->pos.x-= x;
        universe->pos.y+= y;
    }

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
    mouseRange = mouseX;
    downPosition = universe->cam.getPosition(); // ofCamera::getGlobalPosition();
    cout << "cam pos = " << downPosition << endl;
    downOrientation = universe->cam.getOrientationQuat(); // ofCamera::getGlobalOrientation();

    control.mousePressed(x, y, button);

    if(currentEditingObj == NULL) {
        currentEditingObj = universe->findEditObject(x, y);

        if (currentEditingObj != NULL) {
            //if we found an object, set the of the control to the object so there is no jump
            for (int i = 0; i < control.amnt; i++) {
                control.fadersPos[i] = currentEditingObj->getParam(i);
            }
        }
    }
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
    control.mouseReleased(x, y, button);
}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<commit_msg>manual fix of conflict<commit_after>#include "ofApp.h"

//#include "ECURabbitObject.h"
#include "ecuaObject.h"

ofVec3f p;

//--------------------------------------------------------------
void ofApp::setup(){
    ofSetVerticalSync(true);
//    mesh.load("lofi-bunny.ply");

//    cout << cam.getTarget().getPosition() << endl;
    universe = new ECUUniverse();
    universe->addObject(new ecuaObject(ofVec3f(0, 0, -1000)));
    //    cam.disableMouseInput();

    //    cam.set

    ofSetSmoothLighting(true);
    pointLight2.setDiffuseColor( ofFloatColor(.3, .3, .3));
    pointLight2.setSpecularColor(ofFloatColor(10, 10, 10));
    pointLight2.setPosition(120, 80, 500);

    currentEditingObj = NULL;

//    ofAddListener(ofEvent::mousePressed, &control, control::mousePressed)
//    ofAddListener(ofEvents().mouseDragged , &control, &ctrls::mouseDragged);
//    ofAddListener(ofEvents().mousePressed, &control, &ctrls::mousePressed);
//    ofAddListener(ofEvents().mouseReleased, &control, &ctrls::mouseReleased);
//    ofAddListener(ofEvents().mouseScrolled, &control, &ctrls::mouseScrolled);

//    ofRegisterMouseEvents(control);

}

void ofApp::exit() {
    delete universe;
}

//--------------------------------------------------------------
void ofApp::update(){
    universe->update();
    control.update();
}

//--------------------------------------------------------------
void ofApp::draw(){
    ofBackgroundGradient(ofColor(64), ofColor(0));

    ofSetColor(255);

    ofEnableDepthTest();
    ofEnableLighting();
    pointLight2.enable();

    universe->draw();

    ofDisableLighting();
    ofDisableDepthTest();

    if(currentEditingObj != NULL) {
        control.draw();
    }
}

bool zDown = false;

#define KEY(k, f) if(key == (k)) { (f); }

void ofApp::createObject() {

    if(currentEditingObj != NULL) {
        //we are now going to turn off, this means that we need to place the object in
        currentEditingObj = NULL;
    }

    else {
        ECUBaseObject *obj = new ecuaObject(ofVec3f(universe->pos.x, universe->pos.y, universe->pos.z-1000));
        currentEditingObj = obj;
        universe->addObject(obj);
    }

//    creatingObject = !creatingObject;
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

    KEY('z', zDown = true)

    KEY('a', createObject())

//    KEY('s', currentEditingObj = NULL)

    cout << "current pos = " << universe->pos << endl;
    cout << "there are " << universe->objects.size() << " objects" << endl;

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){
    zDown = false;
}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
    control.mouseMoved(x, y);
}

ofVec3f downPosition;
ofQuaternion downOrientation;

float mouseRange = 0;

void ofApp::mouseDragged(int x, int y, int button) {

    control.mouseDragged(x, y, button);

    for (int i = 0; i < control.amnt; i++) {
        currentEditingObj->setParam(i, control.fadersPos[i]);

        //if we found an object, set the of the control to the object so there is no jump

    }

}

//--------------------------------------------------------------
void ofApp::mouseScrolled(float x, float y) {
    if (zDown) {
        universe->pos.z+= -y;
    }
    else {
        universe->pos.x-= x;
        universe->pos.y+= y;
    }

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
    mouseRange = mouseX;
    downPosition = universe->cam.getPosition(); // ofCamera::getGlobalPosition();
    cout << "cam pos = " << downPosition << endl;
    downOrientation = universe->cam.getOrientationQuat(); // ofCamera::getGlobalOrientation();

    control.mousePressed(x, y, button);

    if(currentEditingObj == NULL) {
        currentEditingObj = universe->findEditObject(x, y);

        if (currentEditingObj != NULL) {
            //if we found an object, set the of the control to the object so there is no jump
            for (int i = 0; i < control.amnt; i++) {
                control.fadersPos[i] = currentEditingObj->getParam(i);
            }
        }
    }
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
    control.mouseReleased(x, y, button);
}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkHistogramImageToImageMetricTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkGaussianImageSource.h"
#include "itkImage.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkMeanSquaresHistogramImageToImageMetric.h"
#include "itkTranslationTransform.h"

int itkHistogramImageToImageMetricTest(int , char*[] )
{
  // Create two simple images.
  const unsigned int ImageDimension = 2;
  typedef double PixelType;
  typedef double CoordinateRepresentationType;

  //Allocate Images
  typedef itk::Image<PixelType,ImageDimension> MovingImageType;
  typedef itk::Image<PixelType,ImageDimension> FixedImageType;

  // Declare Gaussian Sources
  typedef itk::GaussianImageSource<MovingImageType> MovingImageSourceType;
  typedef itk::GaussianImageSource<FixedImageType> FixedImageSourceType;
  typedef MovingImageSourceType::Pointer MovingImageSourcePointer;
  typedef FixedImageSourceType::Pointer FixedImageSourcePointer;

  // Note: the following declarations are classical arrays
  unsigned long fixedImageSize[] = {100,  100};
  unsigned long movingImageSize[] = {100,  100};

  float fixedImageSpacing[]  = {1.0f, 1.0f};
  float movingImageSpacing[] = {1.0f, 1.0f};

  float fixedImageOrigin[] = {0.0f, 0.0f};
  float movingImageOrigin[] = {0.0f, 0.0f};

  MovingImageSourceType::Pointer movingImageSource =
    MovingImageSourceType::New();
  FixedImageSourceType::Pointer  fixedImageSource  =
    FixedImageSourceType::New();

  movingImageSource->SetSize(movingImageSize);
  movingImageSource->SetOrigin(movingImageOrigin);
  movingImageSource->SetSpacing(movingImageSpacing);
  movingImageSource->SetNormalized(false);
  movingImageSource->SetScale(250.0f);

  fixedImageSource->SetSize(fixedImageSize);
  fixedImageSource->SetOrigin(fixedImageOrigin);
  fixedImageSource->SetSpacing(fixedImageSpacing);
  fixedImageSource->SetNormalized(false);
  fixedImageSource->SetScale(250.0f);

  movingImageSource->Update(); // Force the filter to run
  fixedImageSource->Update();  // Force the filter to run

  MovingImageType::Pointer movingImage = movingImageSource->GetOutput();
  FixedImageType::Pointer  fixedImage  = fixedImageSource->GetOutput();

  // Set up the metric.
  typedef itk::MeanSquaresHistogramImageToImageMetric<FixedImageType,
    MovingImageType> MetricType;
  typedef MetricType::TransformType TransformBaseType;
  typedef MetricType::ScalesType ScalesType;
  typedef MetricType::DerivativeType DerivativeType;
  typedef TransformBaseType::ParametersType ParametersType;

  MetricType::Pointer metric = MetricType::New();

  unsigned int nBins = 256;
  MetricType::HistogramType::SizeType histSize;
  histSize[0] = nBins;
  histSize[1] = nBins;
  metric->SetHistogramSize(histSize);

  // Plug the images into the metric.
  metric->SetFixedImage(fixedImage);
  metric->SetMovingImage(movingImage);

  // Set up a transform.
  typedef itk::TranslationTransform<CoordinateRepresentationType,
    ImageDimension> TransformType;

  TransformType::Pointer transform = TransformType::New();
  metric->SetTransform(transform.GetPointer());

  // Set up an interpolator.
  typedef itk::LinearInterpolateImageFunction<MovingImageType,
    double> InterpolatorType;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  interpolator->SetInputImage(movingImage.GetPointer());
  metric->SetInterpolator(interpolator.GetPointer());

  // Define the region over which the metric will be computed.
  metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());

  // Set up transform parameters.
  const unsigned int numberOfParameters = transform->GetNumberOfParameters();

  ParametersType parameters( numberOfParameters );
  for (unsigned int k = 0; k < numberOfParameters; k++)
    {
    parameters[k] = 0.0;
    }

  // Set scales for derivative calculation.
  ScalesType scales( numberOfParameters );
  for (unsigned int k = 0; k < numberOfParameters; k++)
    {
    scales[k] = 1;
    }

  const double STEP_LENGTH = 0.001;
  metric->SetDerivativeStepLength(STEP_LENGTH);
  metric->SetDerivativeStepLengthScales(scales);

  try
    {
    // Initialize the metric.
    metric->Initialize();

    // Test SetPaddingValue() and GetPaddingValue().
    metric->SetPaddingValue(-1);
    metric->SetUsePaddingValue(true);

    if (metric->GetPaddingValue() != -1)
      {
      std::cerr << "Incorrect padding value." << std::endl;
      return EXIT_FAILURE;
      }

    // Check to make sure the returned histogram size is the same as histSize.
    if (histSize != metric->GetHistogramSize())
      {
      std::cout << "Incorrect histogram size." << std::endl;
      return EXIT_FAILURE;
      }

    // Check GetDerivativeStepLength().
    if (metric->GetDerivativeStepLength() != STEP_LENGTH)
      {
      std::cout << "Incorrect derivative step length." << std::endl;
      return EXIT_FAILURE;
      }

    // Check GetDerivativeStepLengthScales().
    if (metric->GetDerivativeStepLengthScales() != scales)
      {
      std::cout << "Incorrect scales." << std::endl;
      return EXIT_FAILURE;
      }

    // Do some work
    DerivativeType derivatives( numberOfParameters );
    MetricType::MeasureType value;
    for (double y = -50.0; y <= 50.0; y += 25.0)
      {
      parameters[1] = y;
      for (double x = -50.0; x <= 50.0; x += 25.0)
        {
        parameters[0] = x;
        metric->GetValueAndDerivative (parameters, value, derivatives);
        std::cout << "Parameters: " << parameters
                  << ", Value: " << value
                  << ", Derivatives: " << derivatives << std::endl;
        }
      }

    // Exercise Print() method.
    metric->Print(std::cout);

    std::cout << "Test passed." << std::endl;
    }
  catch (itk::ExceptionObject& ex)
    {
    std::cerr << "Exception caught!" << std::endl;
    std::cerr << ex << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Exercise the SetLowerBound() and SetUpperBound() methods " << std::endl;

  MetricType::MeasurementVectorType lowerBound;
  MetricType::MeasurementVectorType upperBound;

  metric->SetLowerBound( lowerBound );
  metric->SetUpperBound( upperBound );

  try
    {
    // Initialize the metric.
    metric->Initialize();

    // Exercise Print() method.
    metric->Print(std::cout);

    std::cout << "Test passed." << std::endl;
    }
  catch (itk::ExceptionObject& ex)
    {
    std::cerr << "Exception caught!" << std::endl;
    std::cerr << ex << std::endl;
    return EXIT_FAILURE;
    }

  // Force an exception
  try
    {
    ParametersType parameters( 2 );
    DerivativeType derivatives( 2 );
    ScalesType badScales( 1 );
    metric->SetDerivativeStepLengthScales(badScales);
    metric->Initialize();
    metric->GetDerivative (parameters, derivatives);
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cerr << "Expected exception caught!" << std::endl;
    std::cerr << ex << std::endl;
    return EXIT_SUCCESS;
    }
  return EXIT_FAILURE;
}
<commit_msg>ENH: initialize upper and lower bound.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkHistogramImageToImageMetricTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkGaussianImageSource.h"
#include "itkImage.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkMeanSquaresHistogramImageToImageMetric.h"
#include "itkTranslationTransform.h"

int itkHistogramImageToImageMetricTest(int , char*[] )
{
  // Create two simple images.
  const unsigned int ImageDimension = 2;
  typedef double PixelType;
  typedef double CoordinateRepresentationType;

  //Allocate Images
  typedef itk::Image<PixelType,ImageDimension> MovingImageType;
  typedef itk::Image<PixelType,ImageDimension> FixedImageType;

  // Declare Gaussian Sources
  typedef itk::GaussianImageSource<MovingImageType> MovingImageSourceType;
  typedef itk::GaussianImageSource<FixedImageType> FixedImageSourceType;
  typedef MovingImageSourceType::Pointer MovingImageSourcePointer;
  typedef FixedImageSourceType::Pointer FixedImageSourcePointer;

  // Note: the following declarations are classical arrays
  unsigned long fixedImageSize[] = {100,  100};
  unsigned long movingImageSize[] = {100,  100};

  float fixedImageSpacing[]  = {1.0f, 1.0f};
  float movingImageSpacing[] = {1.0f, 1.0f};

  float fixedImageOrigin[] = {0.0f, 0.0f};
  float movingImageOrigin[] = {0.0f, 0.0f};

  MovingImageSourceType::Pointer movingImageSource =
    MovingImageSourceType::New();
  FixedImageSourceType::Pointer  fixedImageSource  =
    FixedImageSourceType::New();

  movingImageSource->SetSize(movingImageSize);
  movingImageSource->SetOrigin(movingImageOrigin);
  movingImageSource->SetSpacing(movingImageSpacing);
  movingImageSource->SetNormalized(false);
  movingImageSource->SetScale(250.0f);

  fixedImageSource->SetSize(fixedImageSize);
  fixedImageSource->SetOrigin(fixedImageOrigin);
  fixedImageSource->SetSpacing(fixedImageSpacing);
  fixedImageSource->SetNormalized(false);
  fixedImageSource->SetScale(250.0f);

  movingImageSource->Update(); // Force the filter to run
  fixedImageSource->Update();  // Force the filter to run

  MovingImageType::Pointer movingImage = movingImageSource->GetOutput();
  FixedImageType::Pointer  fixedImage  = fixedImageSource->GetOutput();

  // Set up the metric.
  typedef itk::MeanSquaresHistogramImageToImageMetric<FixedImageType,
    MovingImageType> MetricType;
  typedef MetricType::TransformType TransformBaseType;
  typedef MetricType::ScalesType ScalesType;
  typedef MetricType::DerivativeType DerivativeType;
  typedef TransformBaseType::ParametersType ParametersType;

  MetricType::Pointer metric = MetricType::New();

  unsigned int nBins = 256;
  MetricType::HistogramType::SizeType histSize;
  histSize[0] = nBins;
  histSize[1] = nBins;
  metric->SetHistogramSize(histSize);

  // Plug the images into the metric.
  metric->SetFixedImage(fixedImage);
  metric->SetMovingImage(movingImage);

  // Set up a transform.
  typedef itk::TranslationTransform<CoordinateRepresentationType,
    ImageDimension> TransformType;

  TransformType::Pointer transform = TransformType::New();
  metric->SetTransform(transform.GetPointer());

  // Set up an interpolator.
  typedef itk::LinearInterpolateImageFunction<MovingImageType,
    double> InterpolatorType;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();
  interpolator->SetInputImage(movingImage.GetPointer());
  metric->SetInterpolator(interpolator.GetPointer());

  // Define the region over which the metric will be computed.
  metric->SetFixedImageRegion(fixedImage->GetBufferedRegion());

  // Set up transform parameters.
  const unsigned int numberOfParameters = transform->GetNumberOfParameters();

  ParametersType parameters( numberOfParameters );
  for (unsigned int k = 0; k < numberOfParameters; k++)
    {
    parameters[k] = 0.0;
    }

  // Set scales for derivative calculation.
  ScalesType scales( numberOfParameters );
  for (unsigned int k = 0; k < numberOfParameters; k++)
    {
    scales[k] = 1;
    }

  const double STEP_LENGTH = 0.001;
  metric->SetDerivativeStepLength(STEP_LENGTH);
  metric->SetDerivativeStepLengthScales(scales);

  try
    {
    // Initialize the metric.
    metric->Initialize();

    // Test SetPaddingValue() and GetPaddingValue().
    metric->SetPaddingValue(-1);
    metric->SetUsePaddingValue(true);

    if (metric->GetPaddingValue() != -1)
      {
      std::cerr << "Incorrect padding value." << std::endl;
      return EXIT_FAILURE;
      }

    // Check to make sure the returned histogram size is the same as histSize.
    if (histSize != metric->GetHistogramSize())
      {
      std::cout << "Incorrect histogram size." << std::endl;
      return EXIT_FAILURE;
      }

    // Check GetDerivativeStepLength().
    if (metric->GetDerivativeStepLength() != STEP_LENGTH)
      {
      std::cout << "Incorrect derivative step length." << std::endl;
      return EXIT_FAILURE;
      }

    // Check GetDerivativeStepLengthScales().
    if (metric->GetDerivativeStepLengthScales() != scales)
      {
      std::cout << "Incorrect scales." << std::endl;
      return EXIT_FAILURE;
      }

    // Do some work
    DerivativeType derivatives( numberOfParameters );
    MetricType::MeasureType value;
    for (double y = -50.0; y <= 50.0; y += 25.0)
      {
      parameters[1] = y;
      for (double x = -50.0; x <= 50.0; x += 25.0)
        {
        parameters[0] = x;
        metric->GetValueAndDerivative (parameters, value, derivatives);
        std::cout << "Parameters: " << parameters
                  << ", Value: " << value
                  << ", Derivatives: " << derivatives << std::endl;
        }
      }

    // Exercise Print() method.
    metric->Print(std::cout);

    std::cout << "Test passed." << std::endl;
    }
  catch (itk::ExceptionObject& ex)
    {
    std::cerr << "Exception caught!" << std::endl;
    std::cerr << ex << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Exercise the SetLowerBound() and SetUpperBound() methods " << std::endl;

  MetricType::MeasurementVectorType lowerBound;
  lowerBound.Fill(0.0);
  MetricType::MeasurementVectorType upperBound;
  upperBound.Fill(0.0);

  metric->SetLowerBound( lowerBound );
  metric->SetUpperBound( upperBound );

  try
    {
    // Initialize the metric.
    metric->Initialize();

    // Exercise Print() method.
    metric->Print(std::cout);

    std::cout << "Test passed." << std::endl;
    }
  catch (itk::ExceptionObject& ex)
    {
    std::cerr << "Exception caught!" << std::endl;
    std::cerr << ex << std::endl;
    return EXIT_FAILURE;
    }

  // Force an exception
  try
    {
    ParametersType parameters( 2 );
    DerivativeType derivatives( 2 );
    ScalesType badScales( 1 );
    metric->SetDerivativeStepLengthScales(badScales);
    metric->Initialize();
    metric->GetDerivative (parameters, derivatives);
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cerr << "Expected exception caught!" << std::endl;
    std::cerr << ex << std::endl;
    return EXIT_SUCCESS;
    }
  return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#include "musicplayer.h"
#include "musicplaylist.h"
#include "musicsettingmanager.h"
#include "musicconnectionpool.h"
#include "soundcore.h"

#include <qmath.h>
#include <QDebug>
MusicPlayer::MusicPlayer(QObject *parent)
    : QObject(parent)
{
    m_playlist = 0;
    m_music = 0;
    m_state = StoppedState;
    m_musicEnhanced = EnhancedOff;
    m_music = new SoundCore(this);
    m_posOnCircle = 0;
    m_volumeMusic3D = 0;

    setEnaleEffect(false);

    connect(&m_timer, SIGNAL(timeout()), SLOT(setTimeOut()));
    M_CONNECTION->setValue("MusicPlayer", this);
}

MusicPlayer::~MusicPlayer()
{
    delete m_music;
}

MusicPlayer::State MusicPlayer::state() const
{
    return m_state;
}

MusicPlaylist *MusicPlayer::playlist() const
{
    return m_playlist;
}

qint64 MusicPlayer::duration() const
{
    return m_music->totalTime();
}

qint64 MusicPlayer::position() const
{
    return m_music->elapsed();
}

int MusicPlayer::volume() const
{
    return m_music->volume();
}

bool MusicPlayer::isMuted() const
{
    return m_music->isMuted();
}

void MusicPlayer::setMusicEnhanced(Enhanced type)
{
    m_musicEnhanced = type;

    if(m_musicEnhanced == Music3D)
    {
        m_volumeMusic3D = volume();
    }
    else
    {
        m_music->setVolume(m_volumeMusic3D, m_volumeMusic3D);
        setMusicEnhancedCase();
    }
}

MusicPlayer::Enhanced MusicPlayer::getMusicEnhanced() const
{
    return m_musicEnhanced;
}

QStringList MusicPlayer::supportFormatsString()
{
    return QStringList()<< "mp3" << "mp2" << "mp1" << "wav" << "ogg"
                        << "flac" << "ac3" << "aac" << "oga" << "pcm";
}

QStringList MusicPlayer::supportFormatsFilterString()
{
    return QStringList()<< "*.mp3" << "*.mp2" << "*.mp1" << "*.wav"
                        << "*.ogg" << "*.flac" << "*.ac3" << "*.aac"
                        << "*.oga" << "*.pcm";
}

QStringList MusicPlayer::supportFormatsFilterDialogString()
{
    return QStringList()<< "Mp3 File(*.mp3)" << "Mp2 File(*.mp2)" << "Mp1 File(*.mp1)"
                        << "Wav File(*.wav)" << "Ogg File(*.ogg)" << "Flac File(*.flac)"
                        << "Ac3 File(*.ac3)" << "Aac File(*.aac)" << "Oga File(*.oga)"
                        << "Pcm File(*.pcm)";
}

void MusicPlayer::play()
{
    if(m_playlist->isEmpty())
    {
        m_state = StoppedState;
        return;
    }

    m_state = PlayingState;
    Qmmp::State state = m_music->state(); ///Get the current state of play
    if(m_currentMedia == m_playlist->currentMediaString() && state == Qmmp::Paused)
    {
        m_music->pause(); ///When the pause time for recovery
        m_timer.start(1000);
        return;
    }

    m_currentMedia = m_playlist->currentMediaString();
    ///The current playback path
    if(!m_music->play(m_currentMedia))
    {
        m_state = StoppedState;
        return;
    }

    m_timer.start(1000);
    ///Every second emits a signal change information
    emit positionChanged(0);
    emit durationChanged( duration() );

    ////////////////////////////////////////////////
    ///Read the configuration settings for the sound
    int volumn = M_SETTING->value(MusicSettingManager::VolumeChoiced).toInt();
    if(volumn != -1)
    {
        setVolume(volumn);
    }
    ////////////////////////////////////////////////
}

void MusicPlayer::playNext()
{
    int index = m_playlist->currentIndex();
    m_playlist->setCurrentIndex((++index >= m_playlist->mediaCount()) ? 0 : index);
}

void MusicPlayer::playPrivious()
{
    int index = m_playlist->currentIndex();
    m_playlist->setCurrentIndex((--index < 0) ? 0 : index );
}

void MusicPlayer::pause()
{
    m_music->pause();
    m_timer.stop();
    m_state = PausedState;
}

void MusicPlayer::stop()
{
    m_music->stop();
    m_timer.stop();
    m_state = StoppedState;
}

void MusicPlayer::setPosition(qint64 position)
{
    m_music->seek(position);
}

void MusicPlayer::setVolume(int volume)
{
    m_music->setVolume(volume);
}

void MusicPlayer::setMuted(bool muted)
{
    m_music->setMuted(muted);
}

void MusicPlayer::setPlaylist(MusicPlaylist *playlist)
{
    m_playlist = playlist;
    connect(m_playlist, SIGNAL(removeCurrentMedia()), SLOT(removeCurrentMedia()));
}

void MusicPlayer::setTimeOut()
{
    emit positionChanged( position() );

    if(m_musicEnhanced == Music3D)
    {
        ///3D music settings
        setEnaleEffect(false);
        m_posOnCircle += 0.5f;
        m_music->setVolume(abs(100 * cosf(m_posOnCircle)), abs(100 * sinf(m_posOnCircle * 0.5f)));
    }

    Qmmp::State state = m_music->state();
    if(state != Qmmp::Playing && state != Qmmp::Paused)
    {
        m_timer.stop();
        if(m_playlist->playbackMode() == MusicObject::MC_PlayOnce)
        {
            m_music->stop();
            emit positionChanged(0);
            emit stateChanged(StoppedState);
            return;
        }
        m_playlist->setCurrentIndex();
        if(m_playlist->playbackMode() == MusicObject::MC_PlayOrder &&
           m_playlist->currentIndex() == -1)
        {
            m_music->stop();
            emit positionChanged(0);
            emit stateChanged(StoppedState);
            return;
        }
        play();
    }
}

void MusicPlayer::setMusicEnhancedCase()
{
    switch(m_musicEnhanced)
    {
        case EnhancedOff:
            setEqEffect(MIntList()<<  0<<  0<<  0<<  0<<  0<<  0<<  0<<  0<<  0<<  0<<  0);
            break;
        case MusicVocal:
            setEqEffect(MIntList()<<  0<<  0<<  4<<  1<< -5<< -1<<  2<< -2<< -4<< -4<<  0);
            break;
        case MusicNICAM:
            setEqEffect(MIntList()<<  6<<-12<<-12<< -9<< -6<< -3<<-12<< -9<< -6<< -3<<-12);
            break;
        case MusicSubwoofer:
            setEqEffect(MIntList()<<  6<<  6<<-10<<-10<<  0<<  0<< -3<< -5<< -7<< -9<<-11);
            break;
        default:
            break;
    }
}

void MusicPlayer::removeCurrentMedia()
{
    if(m_music)
    {
        m_timer.stop();
        m_music->stop();
    }
}

void MusicPlayer::setEqEffect(const MIntList &hz)
{
    if(hz.count() != 11)
    {
        return;
    }

    EqSettings eq = m_music->eqSettings();
    eq.setPreamp(hz[0]);
    eq.setEnabled(true);
    for(int i=0; i<EqSettings::EQ_BANDS_10; ++i)
    {
        eq.setGain(i, hz[i + 1]);
    }
    m_music->setEqSettings(eq);
}

void MusicPlayer::setEnaleEffect(bool enable)
{
    if(enable == false)
    {
        setEqEffect(MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);
    }
}

void MusicPlayer::setEqInformation()
{
    ///Read the equalizer parameters from a configuration file
    if(M_SETTING->value(MusicSettingManager::EqualizerEnableChoiced).toInt())
    {
        setEnaleEffect(true);
        QStringList eqValue = M_SETTING->value(MusicSettingManager::EqualizerValueChoiced).toString().split(',');
        if(eqValue.count() == 11)
        {
            MIntList hz;
            hz<<eqValue[0].toInt()<<eqValue[1].toInt()<<eqValue[2].toInt()
              <<eqValue[3].toInt()<<eqValue[4].toInt()<<eqValue[5].toInt()
              <<eqValue[6].toInt()<<eqValue[7].toInt()<<eqValue[8].toInt()
              <<eqValue[9].toInt()<<eqValue[10].toInt();
            setEqEffect(hz);
        }
    }
}

<commit_msg>fix set volume error in new core[785412]<commit_after>#include "musicplayer.h"
#include "musicplaylist.h"
#include "musicsettingmanager.h"
#include "musicconnectionpool.h"
#include "soundcore.h"

#include <qmath.h>
#include <QDebug>
MusicPlayer::MusicPlayer(QObject *parent)
    : QObject(parent)
{
    m_playlist = 0;
    m_music = 0;
    m_state = StoppedState;
    m_musicEnhanced = EnhancedOff;
    m_music = new SoundCore(this);
    m_posOnCircle = 0;
    m_volumeMusic3D = 0;

    setEnaleEffect(false);

    connect(&m_timer, SIGNAL(timeout()), SLOT(setTimeOut()));
    M_CONNECTION->setValue("MusicPlayer", this);
}

MusicPlayer::~MusicPlayer()
{
    delete m_music;
}

MusicPlayer::State MusicPlayer::state() const
{
    return m_state;
}

MusicPlaylist *MusicPlayer::playlist() const
{
    return m_playlist;
}

qint64 MusicPlayer::duration() const
{
    return m_music->totalTime();
}

qint64 MusicPlayer::position() const
{
    return m_music->elapsed();
}

int MusicPlayer::volume() const
{
    return m_music->volume();
}

bool MusicPlayer::isMuted() const
{
    return m_music->isMuted();
}

void MusicPlayer::setMusicEnhanced(Enhanced type)
{
    m_musicEnhanced = type;

    if(m_musicEnhanced == Music3D)
    {
        m_volumeMusic3D = volume();
    }
    else
    {
        m_music->setVolume(m_volumeMusic3D, m_volumeMusic3D);
        setMusicEnhancedCase();
    }
}

MusicPlayer::Enhanced MusicPlayer::getMusicEnhanced() const
{
    return m_musicEnhanced;
}

QStringList MusicPlayer::supportFormatsString()
{
    return QStringList()<< "mp3" << "mp2" << "mp1" << "wav" << "ogg"
                        << "flac" << "ac3" << "aac" << "oga" << "pcm";
}

QStringList MusicPlayer::supportFormatsFilterString()
{
    return QStringList()<< "*.mp3" << "*.mp2" << "*.mp1" << "*.wav"
                        << "*.ogg" << "*.flac" << "*.ac3" << "*.aac"
                        << "*.oga" << "*.pcm";
}

QStringList MusicPlayer::supportFormatsFilterDialogString()
{
    return QStringList()<< "Mp3 File(*.mp3)" << "Mp2 File(*.mp2)" << "Mp1 File(*.mp1)"
                        << "Wav File(*.wav)" << "Ogg File(*.ogg)" << "Flac File(*.flac)"
                        << "Ac3 File(*.ac3)" << "Aac File(*.aac)" << "Oga File(*.oga)"
                        << "Pcm File(*.pcm)";
}

void MusicPlayer::play()
{
    if(m_playlist->isEmpty())
    {
        m_state = StoppedState;
        return;
    }

    m_state = PlayingState;
    Qmmp::State state = m_music->state(); ///Get the current state of play
    if(m_currentMedia == m_playlist->currentMediaString() && state == Qmmp::Paused)
    {
        m_music->pause(); ///When the pause time for recovery
        m_timer.start(1000);
        return;
    }

    m_currentMedia = m_playlist->currentMediaString();
    ///The current playback path
    if(!m_music->play(m_currentMedia))
    {
        m_state = StoppedState;
        return;
    }

    m_timer.start(1000);
    ///Every second emits a signal change information
    emit positionChanged(0);
    emit durationChanged( duration() );

    ////////////////////////////////////////////////
    ///Read the configuration settings for the sound
    int volumn = M_SETTING->value(MusicSettingManager::VolumeChoiced).toInt();
    if(volumn != -1)
    {
        setVolume(volumn);
    }
    ////////////////////////////////////////////////
}

void MusicPlayer::playNext()
{
    int index = m_playlist->currentIndex();
    m_playlist->setCurrentIndex((++index >= m_playlist->mediaCount()) ? 0 : index);
}

void MusicPlayer::playPrivious()
{
    int index = m_playlist->currentIndex();
    m_playlist->setCurrentIndex((--index < 0) ? 0 : index );
}

void MusicPlayer::pause()
{
    m_music->pause();
    m_timer.stop();
    m_state = PausedState;
}

void MusicPlayer::stop()
{
    m_music->stop();
    m_timer.stop();
    m_state = StoppedState;
}

void MusicPlayer::setPosition(qint64 position)
{
    m_music->seek(position);
}

void MusicPlayer::setVolume(int volume)
{
    m_volumeMusic3D = volume;
    m_music->setVolume(volume);
}

void MusicPlayer::setMuted(bool muted)
{
    m_volumeMusic3D = muted ? 0 : m_music->volume();
    m_music->setMuted(muted);
}

void MusicPlayer::setPlaylist(MusicPlaylist *playlist)
{
    m_playlist = playlist;
    connect(m_playlist, SIGNAL(removeCurrentMedia()), SLOT(removeCurrentMedia()));
}

void MusicPlayer::setTimeOut()
{
    emit positionChanged( position() );

    if(m_musicEnhanced == Music3D && !m_music->isMuted())
    {
        ///3D music settings
        setEnaleEffect(false);
        m_posOnCircle += 0.5f;
        m_music->setVolume(abs(100 * cosf(m_posOnCircle)), abs(100 * sinf(m_posOnCircle * 0.5f)));
    }

    Qmmp::State state = m_music->state();
    if(state != Qmmp::Playing && state != Qmmp::Paused)
    {
        m_timer.stop();
        if(m_playlist->playbackMode() == MusicObject::MC_PlayOnce)
        {
            m_music->stop();
            emit positionChanged(0);
            emit stateChanged(StoppedState);
            return;
        }
        m_playlist->setCurrentIndex();
        if(m_playlist->playbackMode() == MusicObject::MC_PlayOrder &&
           m_playlist->currentIndex() == -1)
        {
            m_music->stop();
            emit positionChanged(0);
            emit stateChanged(StoppedState);
            return;
        }
        play();
    }
}

void MusicPlayer::setMusicEnhancedCase()
{
    switch(m_musicEnhanced)
    {
        case EnhancedOff:
            setEqEffect(MIntList()<<  0<<  0<<  0<<  0<<  0<<  0<<  0<<  0<<  0<<  0<<  0);
            break;
        case MusicVocal:
            setEqEffect(MIntList()<<  0<<  0<<  4<<  1<< -5<< -1<<  2<< -2<< -4<< -4<<  0);
            break;
        case MusicNICAM:
            setEqEffect(MIntList()<<  6<<-12<<-12<< -9<< -6<< -3<<-12<< -9<< -6<< -3<<-12);
            break;
        case MusicSubwoofer:
            setEqEffect(MIntList()<<  6<<  6<<-10<<-10<<  0<<  0<< -3<< -5<< -7<< -9<<-11);
            break;
        default:
            break;
    }
}

void MusicPlayer::removeCurrentMedia()
{
    if(m_music)
    {
        m_timer.stop();
        m_music->stop();
    }
}

void MusicPlayer::setEqEffect(const MIntList &hz)
{
    if(hz.count() != 11)
    {
        return;
    }

    EqSettings eq = m_music->eqSettings();
    eq.setPreamp(hz[0]);
    eq.setEnabled(true);
    for(int i=0; i<EqSettings::EQ_BANDS_10; ++i)
    {
        eq.setGain(i, hz[i + 1]);
    }
    m_music->setEqSettings(eq);
}

void MusicPlayer::setEnaleEffect(bool enable)
{
    if(enable == false)
    {
        setEqEffect(MIntList()<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0<< 0);
    }
}

void MusicPlayer::setEqInformation()
{
    ///Read the equalizer parameters from a configuration file
    if(M_SETTING->value(MusicSettingManager::EqualizerEnableChoiced).toInt())
    {
        setEnaleEffect(true);
        QStringList eqValue = M_SETTING->value(MusicSettingManager::EqualizerValueChoiced).toString().split(',');
        if(eqValue.count() == 11)
        {
            MIntList hz;
            hz<<eqValue[0].toInt()<<eqValue[1].toInt()<<eqValue[2].toInt()
              <<eqValue[3].toInt()<<eqValue[4].toInt()<<eqValue[5].toInt()
              <<eqValue[6].toInt()<<eqValue[7].toInt()<<eqValue[8].toInt()
              <<eqValue[9].toInt()<<eqValue[10].toInt();
            setEqEffect(hz);
        }
    }
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkQuadEdgeTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkQuadEdge.h"
#include <iostream>

int itkQuadEdgeTest1( int , char* [] )
{
  typedef itk::QuadEdge        QuadEdgeType;

  // Tests for the GetRot() SetRot() methods
  { // create a local scope for these tests
  QuadEdgeType * quadEdge1 = new QuadEdgeType;
  QuadEdgeType * quadEdge2 = new QuadEdgeType;
  QuadEdgeType * quadEdge3 = new QuadEdgeType;

  quadEdge1->GetRot();

  // Verify that it can be set.
  quadEdge1->SetRot( quadEdge2 );
  if( quadEdge1->GetRot() != quadEdge2 )
    {
    std::cerr << "Error in SetRot() / GetRot() " << std::endl;
    return EXIT_FAILURE;
    }

  // Verify that it can be changed.
  quadEdge1->SetRot( quadEdge3 );
  if( quadEdge1->GetRot() != quadEdge3 )
    {
    std::cerr << "Error in SetRot() / GetRot() " << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed" << std::endl;

  delete quadEdge1;
  delete quadEdge2;
  delete quadEdge3;
  } // end of local scope for tests

  // Tests for the GetOnext() SetOnext() methods
  { // create a local scope for these tests
  QuadEdgeType * quadEdge1 = new QuadEdgeType;
  QuadEdgeType * quadEdge2 = new QuadEdgeType;
  QuadEdgeType * quadEdge3 = new QuadEdgeType;

  quadEdge1->GetOnext();

  // Verify that it can be set.
  quadEdge1->SetOnext( quadEdge2 );
  if( quadEdge1->GetOnext() != quadEdge2 )
    {
    std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
    return EXIT_FAILURE;
    }

  // Verify that it can be changed.
  quadEdge1->SetOnext( quadEdge3 );
  if( quadEdge1->GetOnext() != quadEdge3 )
    {
    std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed" << std::endl;

  delete quadEdge1;
  delete quadEdge2;
  delete quadEdge3;
  } // end of local scope for tests

  // Tests for the IsEdgeIn*() methods
  { // create a local scope for these tests
  QuadEdgeType * quadEdge1 = new QuadEdgeType;
  QuadEdgeType * quadEdge2 = new QuadEdgeType;

  bool itis = quadEdge1->IsEdgeInOnextRing( quadEdge2 );
  if( itis )
    {

    }

  delete quadEdge1;
  delete quadEdge2;
  } // end of local scope for tests

  return EXIT_SUCCESS;
}

<commit_msg>ENH: Adding tests for const versions of GetRot() and GetOnext().<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkQuadEdgeTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkQuadEdge.h"
#include <iostream>

int itkQuadEdgeTest1( int , char* [] )
{
  typedef itk::QuadEdge        QuadEdgeType;

  // Tests for the GetRot() SetRot() methods
  { // create a local scope for these tests
  QuadEdgeType * quadEdge1 = new QuadEdgeType;
  QuadEdgeType * quadEdge2 = new QuadEdgeType;
  QuadEdgeType * quadEdge3 = new QuadEdgeType;
  const QuadEdgeType * quadEdge1c = quadEdge1;

  quadEdge1->GetRot();

  // Verify that it can be set.
  quadEdge1->SetRot( quadEdge2 );
  if( quadEdge1->GetRot() != quadEdge2 )
    {
    std::cerr << "Error in SetRot() / GetRot() " << std::endl;
    return EXIT_FAILURE;
    }
  // Test the const version
  if( quadEdge1c->GetRot() != quadEdge2 )
    {
    std::cerr << "Error in SetRot() / GetRot() " << std::endl;
    return EXIT_FAILURE;
    }

  // Verify that it can be changed.
  quadEdge1->SetRot( quadEdge3 );
  if( quadEdge1->GetRot() != quadEdge3 )
    {
    std::cerr << "Error in SetRot() / GetRot() " << std::endl;
    return EXIT_FAILURE;
    }
  // Test the const version
  if( quadEdge1c->GetRot() != quadEdge2 )
    {
    std::cerr << "Error in SetRot() / GetRot() " << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed" << std::endl;

  delete quadEdge1;
  delete quadEdge2;
  delete quadEdge3;
  } // end of local scope for tests

  // Tests for the GetOnext() SetOnext() methods
  { // create a local scope for these tests
  QuadEdgeType * quadEdge1 = new QuadEdgeType;
  QuadEdgeType * quadEdge2 = new QuadEdgeType;
  QuadEdgeType * quadEdge3 = new QuadEdgeType;
  const QuadEdgeType * quadEdge1c = quadEdge1;

  quadEdge1->GetOnext();

  // Verify that it can be set.
  quadEdge1->SetOnext( quadEdge2 );
  if( quadEdge1->GetOnext() != quadEdge2 )
    {
    std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
    return EXIT_FAILURE;
    }
  // Test the const version
  if( quadEdge1c->GetOnext() != quadEdge2 )
    {
    std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
    return EXIT_FAILURE;
    }

  // Verify that it can be changed.
  quadEdge1->SetOnext( quadEdge3 );
  if( quadEdge1->GetOnext() != quadEdge3 )
    {
    std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
    return EXIT_FAILURE;
    }
  // Test the const version
  if( quadEdge1c->GetOnext() != quadEdge2 )
    {
    std::cerr << "Error in SetOnext() / GetOnext() " << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed" << std::endl;

  delete quadEdge1;
  delete quadEdge2;
  delete quadEdge3;
  } // end of local scope for tests

  // Tests for the IsEdgeIn*() methods
  { // create a local scope for these tests
  QuadEdgeType * quadEdge1 = new QuadEdgeType;
  QuadEdgeType * quadEdge2 = new QuadEdgeType;

  bool itis = quadEdge1->IsEdgeInOnextRing( quadEdge2 );
  if( itis )
    {

    }

  delete quadEdge1;
  delete quadEdge2;
  } // end of local scope for tests

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "CinderImGui.h"
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
#include "imgui_user.h"

#include "Choreograph.h"
#include "Channel.hpp"

using namespace ci;
using namespace ci::app;
using namespace std;

void drawChannelGui(ch::Channel<float> &channel) {
  ImDrawList* draw_list = ImGui::GetWindowDrawList();

  for (auto i = 0; i < channel.keys().size(); i += 1) {

    ui::SliderFloat(("Value " + to_string(i)).c_str(), &channel.mutableKeys()[i].value, -100.0f, 100.0f);

    if (i > 0 && i < channel.keys().size() - 1) {
      auto *previous = &channel.mutableKeys()[i - 1];
      auto *current = &channel.mutableKeys()[i];
      auto *next = &channel.mutableKeys()[i + 1];
      auto timef = (float)current->time;
      if (ui::SliderFloat(("Time " + to_string(i)).c_str(), &timef, previous->time, next->time)) {
        current->time = timef;
      }
    }
  }

  auto const outer_size = vec2(ui::GetWindowWidth(), 100.0f);
  auto const padding = vec2(20, 10);
  auto const top_left = vec2(0);
  auto const bottom_right = outer_size - padding;
  auto const value_range = vec2(-100.0f, 100.0f);
  auto const time_range = vec2(0, channel.duration());
  auto const cursor_position = vec2(ui::GetCursorScreenPos());
  auto color = vec4(1.0f,1.0f,0.4f,1.0f);
  auto color32 = ImColor(color);
  auto background_color = ImColor(vec4(0.3, 0.3, 0.3f, 1.0f));

  auto const value_to_space = [=] (const ci::vec2 &values) {
    auto x = values.x / channel.duration();
    auto y = (values.y - value_range.x) / (value_range.y - value_range.x);
    return mix(top_left, bottom_right, vec2(x, y)) + cursor_position;
  };

  auto const space_to_value = [=] (const ci::vec2 &space) {
    auto pos = space - cursor_position;
    auto normalized = pos / (bottom_right - top_left);
    return mix(vec2(time_range.x, value_range.x), vec2(time_range.y, value_range.y), normalized);
  };

  draw_list->AddRectFilled(cursor_position + top_left, cursor_position + bottom_right, background_color);
  auto id = 0;
  for (auto &key: channel.mutableKeys()) {
    auto pos = value_to_space(vec2(key.time, key.value));
    auto radius = 12.0f;

    // Use an invisible button to handle interaction with circles.
    ui::SetCursorScreenPos(pos - vec2(radius));
    ui::PushID("temp_key");
    ui::InvisibleButton("", vec2(radius * 2.0f));
    ui::SetCursorScreenPos(cursor_position);
    if (ui::IsItemHovered()) {
      // Maybe use DragBehavior to handle changing value? Mapping back from space to value
//      ui::DragBehavior(<#const ImRect &frame_bb#>, <#ImGuiID id#>, <#float *v#>, <#float v_speed#>, <#float v_min#>, <#float v_max#>, <#int decimal_precision#>, <#float power#>)
      // Or use is mouse dragging and handle change more directly?

      if (ui::IsMouseDragging()) {
        auto delta = vec2(ui::GetIO().MouseDelta);
        auto value = space_to_value(pos + delta);
        console() << "Changing value of " << id << " with deltas: " << delta << ", new value: " << value << " mouse: " << vec2(ui::GetMousePos()) << endl;
        key.time = value.x;
        key.value = value.y;
      }
    }

    ui::PopID();
    id += 1;
    draw_list->AddCircle(pos, radius, color32);
  }
  ui::Dummy(outer_size);
}

class TimelineEditorApp : public App {
public:
  void setup() override;
  void mouseDown( MouseEvent event ) override;
  void update() override;
  void draw() override;
private:
  ch::Channel<float> _channel;
};

void TimelineEditorApp::setup()
{
	ui::initialize();

  _channel.insertKey(10.0f, 0);
  _channel.insertKey(20.0f, 1);
  _channel.insertKey(30.0f, 3);

  CI_ASSERT(_channel.duration() == 3);
}

void TimelineEditorApp::mouseDown( MouseEvent event )
{
}

void TimelineEditorApp::update()
{
  ui::Text("Hello");
  drawChannelGui(_channel);
}

void TimelineEditorApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );

  auto t = std::fmod(getElapsedSeconds(), _channel.duration());
  gl::drawSolidCircle(getWindowCenter() + vec2(0, _channel.value(t)), 24.0f);
}

CINDER_APP( TimelineEditorApp, RendererGl )
<commit_msg>Better dragging using ui::IsItemActive.<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "CinderImGui.h"
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
#include "imgui_user.h"

#include "Choreograph.h"
#include "Channel.hpp"

using namespace ci;
using namespace ci::app;
using namespace std;

void drawChannelGui(ch::Channel<float> &channel) {
  ImDrawList* draw_list = ImGui::GetWindowDrawList();

  for (auto i = 0; i < channel.keys().size(); i += 1) {

    ui::SliderFloat(("Value " + to_string(i)).c_str(), &channel.mutableKeys()[i].value, -100.0f, 100.0f);

    if (i > 0 && i < channel.keys().size() - 1) {
      auto *previous = &channel.mutableKeys()[i - 1];
      auto *current = &channel.mutableKeys()[i];
      auto *next = &channel.mutableKeys()[i + 1];
      auto timef = (float)current->time;
      if (ui::SliderFloat(("Time " + to_string(i)).c_str(), &timef, previous->time, next->time)) {
        current->time = timef;
      }
    }
  }

  auto const outer_size = vec2(ui::GetWindowWidth(), 100.0f);
  auto const padding = vec2(20, 10);
  auto const top_left = vec2(0);
  auto const bottom_right = outer_size - padding;
  auto const value_range = vec2(-100.0f, 100.0f);
  auto const time_range = vec2(0, channel.duration());
  auto const cursor_position = vec2(ui::GetCursorScreenPos());
  auto color = vec4(1.0f,1.0f,0.4f,1.0f);
  auto color32 = ImColor(color);
  auto background_color = ImColor(vec4(0.3, 0.3, 0.3f, 1.0f));

  auto const value_to_space = [=] (const ci::vec2 &values) {
    auto x = values.x / channel.duration();
    auto y = (values.y - value_range.x) / (value_range.y - value_range.x);
    return mix(top_left, bottom_right, vec2(x, y)) + cursor_position;
  };

  auto const space_to_value = [=] (const ci::vec2 &space) {
    auto pos = space - cursor_position;
    auto normalized = pos / (bottom_right - top_left);
    return mix(vec2(time_range.x, value_range.x), vec2(time_range.y, value_range.y), normalized);
  };

  draw_list->AddRectFilled(cursor_position + top_left, cursor_position + bottom_right, background_color);
  auto id = 0;
  for (auto &key: channel.mutableKeys()) {
    auto pos = value_to_space(vec2(key.time, key.value));
    auto radius = 12.0f;

    // Use an invisible button to handle interaction with circles.
    ui::SetCursorScreenPos(pos - vec2(radius));
    ui::PushID(("temp_key" + to_string(id)).c_str());
    ui::InvisibleButton("", vec2(radius * 2.0f));
    ui::SetCursorScreenPos(cursor_position);
    if (ui::IsItemActive()) {
      if (ui::IsMouseDown(0)) {
        auto value = space_to_value(ui::GetMousePos());
        console() << "Changing value of " << id << ", new value: " << value << " mouse: " << vec2(ui::GetMousePos()) << endl;
        key.time = value.x;
        key.value = value.y;
      }
    }

    ui::PopID();
    id += 1;
    draw_list->AddCircle(pos, radius, color32);
  }
  ui::Dummy(outer_size);
}

class TimelineEditorApp : public App {
public:
  void setup() override;
  void mouseDown( MouseEvent event ) override;
  void update() override;
  void draw() override;
private:
  ch::Channel<float> _channel;
};

void TimelineEditorApp::setup()
{
	ui::initialize();

  _channel.insertKey(10.0f, 0);
  _channel.insertKey(20.0f, 1);
  _channel.insertKey(30.0f, 3);

  CI_ASSERT(_channel.duration() == 3);
}

void TimelineEditorApp::mouseDown( MouseEvent event )
{
}

void TimelineEditorApp::update()
{
  ui::Text("Hello");
  drawChannelGui(_channel);
}

void TimelineEditorApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );

  auto t = std::fmod(getElapsedSeconds(), _channel.duration());
  gl::drawSolidCircle(getWindowCenter() + vec2(0, _channel.value(t)), 24.0f);
}

CINDER_APP( TimelineEditorApp, RendererGl )
<|endoftext|>