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

#include "sim/SimCharacter.h"
#include "util/FileUtil.h"

const std::string gPDControllersKey = "PDControllers";
const std::string gPDParamKeys[cPDController::eParamMax] =
{
	"JointID",
	"Kp",
	"Kd",
	"TorqueLim",
	"TargetTheta",
	"TargetVel",
	"UseWorldCoord"
};

bool cPDController::LoadParams(const std::string& file, Eigen::MatrixXd& out_buffer)
{
	std::ifstream f_stream(file);
	Json::Reader reader;
	Json::Value root;
	bool succ = reader.parse(f_stream, root);
	f_stream.close();

	if (succ)
	{
		if (!root[gPDControllersKey].isNull())
		{
			const Json::Value& pd_controllers = root[gPDControllersKey];
			int num_ctrls = pd_controllers.size();
			out_buffer.resize(num_ctrls, eParamMax);

			for (int i = 0; i < num_ctrls; ++i)
			{
				tParams curr_params;
				Json::Value json_pd_ctrl = pd_controllers.get(i, 0);
				bool succ_def = ParsePDParams(json_pd_ctrl, curr_params);
				if (succ_def)
				{
					int joint_id = i;
					curr_params[eParamJointID] = i;
					out_buffer.row(i) = curr_params;
				}
				else
				{
					succ = false;
					break;
				}
			}
		}

	}
	else
	{
		printf("Failed to load PD controller parameters from %s\n", file.c_str());
	}

	return succ;
}

bool cPDController::ParsePDParams(const Json::Value& root, tParams& out_params)
{
	bool succ = true;

	out_params.setZero();
	for (int i = 0; i < eParamMax; ++i)
	{
		const std::string& curr_key = gPDParamKeys[i];
		if (!root[curr_key].isNull() && root[curr_key].isNumeric())
		{
			Json::Value json_val = root[curr_key];
			double val = json_val.asDouble();
			out_params[i] = val;
		}
	}

	return succ;
}

cPDController::cPDController()
	: cController()
{
	Clear();
}

cPDController::~cPDController()
{
}

void cPDController::Init(cSimCharacter* character, const tParams& params)
{
	cController::Init(character);
	mParams = params;
	mValid = true;

	cJoint& joint = GetJoint();
	double torque_lim = GetTorqueLimit();
	joint.SetTorqueLimit(torque_lim);
}

void cPDController::Clear()
{
	cController::Clear();

	mParams[eParamJointID] = static_cast<double>(cKinTree::gInvalidJointID);
	mParams[eParamKp] = 0;
	mParams[eParamKd] = 0;
	mParams[eParamTorqueLim] = std::numeric_limits<double>::infinity();
	mParams[eParamTargetTheta] = 0;
	mParams[eParamTargetVel] = 0;
	mParams[eParamUseWorldCoord] = 0;
}

void cPDController::Update(double time_step)
{
	if (IsActive())
	{
		cJoint& joint = GetJoint();
		tVector torque = CalcTorque();
		joint.AddTorque(torque);
	}
}

cJoint& cPDController::GetJoint()
{
	return mChar->GetJoint(GetJointID());
}

const cJoint& cPDController::GetJoint() const
{
	return mChar->GetJoint(GetJointID());
}

void cPDController::SetKp(double kp)
{
	mParams[eParamKp] = kp;
}

double cPDController::GetKp() const
{
	return mParams[eParamKp];
}

double cPDController::GetTorqueLimit() const
{
	return mParams[eParamTorqueLim];
}

void cPDController::SetKd(double kd)
{
	mParams[eParamKd] = kd;
}

double cPDController::GetKd() const
{
	return mParams[eParamKd];
}

void cPDController::SetTargetTheta(double theta)
{
	mParams[eParamTargetTheta] = theta;
}

void cPDController::SetTargetVel(double vel)
{
	mParams[eParamTargetVel] = vel;
}

void cPDController::SetUseWorldCoord(bool use)
{
	mParams[eParamUseWorldCoord] = (use) ? 1 : 0;
}

bool cPDController::UseWorldCoord() const
{
	return mParams[eParamUseWorldCoord] != 0;
}

double cPDController::CalcTheta() const
{
	const cJoint& joint = GetJoint();
	tVector rot_axis;
	double theta = 0;
	if (UseWorldCoord())
	{
		joint.GetChildRotation(rot_axis, theta);
		tVector axis_world = joint.CalcAxisWorld();
		theta *= rot_axis.dot(axis_world);
	}
	else
	{
		joint.CalcRotation(rot_axis, theta);
	}

	return theta;
}

{
	const cJoint& joint = GetJoint();
	const tVector& axis_rel = joint.GetAxisRel();

	tVector joint_vel = joint.CalcJointVelRel();
	double vel = joint_vel.dot(axis_rel);
	return vel;
}

double cPDController::CalcThetaErr() const
{
	double theta = CalcTheta();
	double tar_theta = GetTargetTheta();
	double theta_err = tar_theta - theta;
	return theta_err;
}

double cPDController::CalcVelErr() const
{
	double vel = CalcVel();
	double tar_vel = GetTargetVel();
	double vel_err = tar_vel - vel;
	return vel_err;
}

double cPDController::CalcTargetTheta(double torque) const
{
	double theta = CalcTheta();
	double vel = CalcVel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double tar_vel = GetTargetVel();
	double tar_theta = theta + 1 / kp * (torque - kd * (tar_vel - vel));
	return tar_theta;
}

double cPDController::CalcTargetVel(double torque) const
{
	double theta = CalcTheta();
	double vel = CalcVel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double tar_theta = GetTargetTheta();
	double tar_vel = vel + 1 / kd * (torque - kp * (tar_theta - theta));
	return tar_vel;
}

double cPDController::GetTargetTheta() const
{
	return mParams[eParamTargetTheta];
}

double cPDController::GetTargetVel() const
{
	return mParams[eParamTargetVel];
}

bool cPDController::IsActive() const
{
	bool active = cController::IsActive();
	return active;
}

tVector cPDController::CalcTorque() const
{
	const cJoint& joint = GetJoint();
	const tVector& axis_rel = joint.GetAxisRel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double theta_err = CalcThetaErr();
	double vel_err = CalcVelErr();
	double t = kp * theta_err + kd * vel_err;
	tVector torque = axis_rel * t;

	return torque;
}

int cPDController::GetJointID() const
{
	return static_cast<int>(mParams[eParamJointID]);
}


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

#include "sim/SimCharacter.h"
#include "util/FileUtil.h"

const std::string gPDControllersKey = "PDControllers";
const std::string gPDParamKeys[cPDController::eParamMax] =
{
	"JointID",
	"Kp",
	"Kd",
	"TorqueLim",
	"TargetTheta",
	"TargetVel",
	"UseWorldCoord"
};

bool cPDController::LoadParams(const std::string& file, Eigen::MatrixXd& out_buffer)
{
	std::ifstream f_stream(file);
	Json::Reader reader;
	Json::Value root;
	bool succ = reader.parse(f_stream, root);
	f_stream.close();

	if (succ)
	{
		if (!root[gPDControllersKey].isNull())
		{
			const Json::Value& pd_controllers = root[gPDControllersKey];
			int num_ctrls = pd_controllers.size();
			out_buffer.resize(num_ctrls, eParamMax);

			for (int i = 0; i < num_ctrls; ++i)
			{
				tParams curr_params;
				Json::Value json_pd_ctrl = pd_controllers.get(i, 0);
				bool succ_def = ParsePDParams(json_pd_ctrl, curr_params);
				if (succ_def)
				{
					int joint_id = i;
					curr_params[eParamJointID] = i;
					out_buffer.row(i) = curr_params;
				}
				else
				{
					succ = false;
					break;
				}
			}
		}

	}
	else
	{
		printf("Failed to load PD controller parameters from %s\n", file.c_str());
	}

	return succ;
}

bool cPDController::ParsePDParams(const Json::Value& root, tParams& out_params)
{
	bool succ = true;

	out_params.setZero();
	for (int i = 0; i < eParamMax; ++i)
	{
		const std::string& curr_key = gPDParamKeys[i];
		if (!root[curr_key].isNull() && root[curr_key].isNumeric())
		{
			Json::Value json_val = root[curr_key];
			double val = json_val.asDouble();
			out_params[i] = val;
		}
	}

	return succ;
}

cPDController::cPDController()
	: cController()
{
	Clear();
}

cPDController::~cPDController()
{
}

void cPDController::Init(cSimCharacter* character, const tParams& params)
{
	cController::Init(character);
	mParams = params;
	mValid = true;

	cJoint& joint = GetJoint();
	double torque_lim = GetTorqueLimit();
	joint.SetTorqueLimit(torque_lim);
}

void cPDController::Clear()
{
	cController::Clear();

	mParams[eParamJointID] = static_cast<double>(cKinTree::gInvalidJointID);
	mParams[eParamKp] = 0;
	mParams[eParamKd] = 0;
	mParams[eParamTorqueLim] = std::numeric_limits<double>::infinity();
	mParams[eParamTargetTheta] = 0;
	mParams[eParamTargetVel] = 0;
	mParams[eParamUseWorldCoord] = 0;
}

void cPDController::Update(double time_step)
{
	if (IsActive())
	{
		cJoint& joint = GetJoint();
		tVector torque = CalcTorque();
		joint.AddTorque(torque);
	}
}

cJoint& cPDController::GetJoint()
{
	return mChar->GetJoint(GetJointID());
}

const cJoint& cPDController::GetJoint() const
{
	return mChar->GetJoint(GetJointID());
}

void cPDController::SetKp(double kp)
{
	mParams[eParamKp] = kp;
}

double cPDController::GetKp() const

double cPDController::GetTorqueLimit() const
{
	return mParams[eParamTorqueLim];
}

void cPDController::SetKd(double kd)
{
	mParams[eParamKd] = kd;
}

double cPDController::GetKd() const
{
	return mParams[eParamKd];
}

void cPDController::SetTargetTheta(double theta)
{
	mParams[eParamTargetTheta] = theta;
}

void cPDController::SetTargetVel(double vel)
{
	mParams[eParamTargetVel] = vel;
}

void cPDController::SetUseWorldCoord(bool use)
{
	mParams[eParamUseWorldCoord] = (use) ? 1 : 0;
}

bool cPDController::UseWorldCoord() const
{
	return mParams[eParamUseWorldCoord] != 0;
}

double cPDController::CalcTheta() const
{
	const cJoint& joint = GetJoint();
	tVector rot_axis;
	double theta = 0;
	if (UseWorldCoord())
	{
		joint.GetChildRotation(rot_axis, theta);
		tVector axis_world = joint.CalcAxisWorld();
		theta *= rot_axis.dot(axis_world);
	}
	else
	{
		joint.CalcRotation(rot_axis, theta);
	}

	return theta;
}

double cPDController::CalcVel() const
{
	const cJoint& joint = GetJoint();
	const tVector& axis_rel = joint.GetAxisRel();

	tVector joint_vel = joint.CalcJointVelRel();
	double vel = joint_vel.dot(axis_rel);
	return vel;
}

double cPDController::CalcThetaErr() const
{
	double theta = CalcTheta();
	double tar_theta = GetTargetTheta();
	double theta_err = tar_theta - theta;
	return theta_err;
}

double cPDController::CalcVelErr() const
{
	double vel = CalcVel();
	double tar_vel = GetTargetVel();
	double vel_err = tar_vel - vel;
	return vel_err;
}

double cPDController::CalcTargetTheta(double torque) const
{
	double theta = CalcTheta();
	double vel = CalcVel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double tar_vel = GetTargetVel();
	double tar_theta = theta + 1 / kp * (torque - kd * (tar_vel - vel));
	return tar_theta;
}

double cPDController::CalcTargetVel(double torque) const
{
	double theta = CalcTheta();
	double vel = CalcVel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double tar_theta = GetTargetTheta();
	double tar_vel = vel + 1 / kd * (torque - kp * (tar_theta - theta));
	return tar_vel;
}

double cPDController::GetTargetTheta() const
{
	return mParams[eParamTargetTheta];
}

double cPDController::GetTargetVel() const
{
	return mParams[eParamTargetVel];
}

bool cPDController::IsActive() const
{
	bool active = cController::IsActive();
	return active;
}

tVector cPDController::CalcTorque() const
{
	const cJoint& joint = GetJoint();
	const tVector& axis_rel = joint.GetAxisRel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double theta_err = CalcThetaErr();
	double vel_err = CalcVelErr();
	double t = kp * theta_err + kd * vel_err;
	tVector torque = axis_rel * t;

	return torque;
}

int cPDController::GetJointID() const
{
	return static_cast<int>(mParams[eParamJointID]);
}


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

#include "sim/SimCharacter.h"
#include "util/FileUtil.h"

const std::string gPDControllersKey = "PDControllers";
const std::string gPDParamKeys[cPDController::eParamMax] =
{
	"JointID",
	"Kp",
	"Kd",
	"TorqueLim",
	"TargetTheta",
	"TargetVel",
	"UseWorldCoord"
};

bool cPDController::LoadParams(const std::string& file, Eigen::MatrixXd& out_buffer)
{
	std::ifstream f_stream(file);
	Json::Reader reader;
	Json::Value root;
	bool succ = reader.parse(f_stream, root);
	f_stream.close();

	if (succ)
	{
		if (!root[gPDControllersKey].isNull())
		{
			const Json::Value& pd_controllers = root[gPDControllersKey];
			int num_ctrls = pd_controllers.size();
			out_buffer.resize(num_ctrls, eParamMax);

			for (int i = 0; i < num_ctrls; ++i)
			{
				tParams curr_params;
				Json::Value json_pd_ctrl = pd_controllers.get(i, 0);
				bool succ_def = ParsePDParams(json_pd_ctrl, curr_params);
				if (succ_def)
				{
					int joint_id = i;
					curr_params[eParamJointID] = i;
					out_buffer.row(i) = curr_params;
				}
				else
				{
					succ = false;
					break;
				}
			}
		}

	}
	else
	{
		printf("Failed to load PD controller parameters from %s\n", file.c_str());
	}

	return succ;
}

bool cPDController::ParsePDParams(const Json::Value& root, tParams& out_params)
{
	bool succ = true;

	out_params.setZero();
	for (int i = 0; i < eParamMax; ++i)
	{
		const std::string& curr_key = gPDParamKeys[i];
		if (!root[curr_key].isNull() && root[curr_key].isNumeric())
		{
			Json::Value json_val = root[curr_key];
			double val = json_val.asDouble();
			out_params[i] = val;
		}
	}

	return succ;
}

cPDController::cPDController()
	: cController()
{
	Clear();
}

cPDController::~cPDController()
{
}

void cPDController::Init(cSimCharacter* character, const tParams& params)
{
	cController::Init(character);
	mParams = params;
	mValid = true;

	cJoint& joint = GetJoint();
	double torque_lim = GetTorqueLimit();
	joint.SetTorqueLimit(torque_lim);
}

void cPDController::Clear()
{
	cController::Clear();

	mParams[eParamJointID] = static_cast<double>(cKinTree::gInvalidJointID);
	mParams[eParamKp] = 0;
	mParams[eParamKd] = 0;
	mParams[eParamTorqueLim] = std::numeric_limits<double>::infinity();
	mParams[eParamTargetTheta] = 0;
	mParams[eParamTargetVel] = 0;
	mParams[eParamUseWorldCoord] = 0;
}

void cPDController::Update(double time_step)
{
	if (IsActive())
	{
		cJoint& joint = GetJoint();
		tVector torque = CalcTorque();
		joint.AddTorque(torque);
	}
}

cJoint& cPDController::GetJoint()
{
	return mChar->GetJoint(GetJointID());
}

const cJoint& cPDController::GetJoint() const
{
	return mChar->GetJoint(GetJointID());
}

void cPDController::SetKp(double kp)
{
	mParams[eParamKp] = kp;
}

double cPDController::GetKp() const
{
	return mParams[eParamKp];
}

double cPDController::GetTorqueLimit() const
{
	return mParams[eParamTorqueLim];
}

void cPDController::SetKd(double kd)
{
	mParams[eParamKd] = kd;
}

double cPDController::GetKd() const
{
	return mParams[eParamKd];
}

void cPDController::SetTargetTheta(double theta)
{
	mParams[eParamTargetTheta] = theta;
}

void cPDController::SetTargetVel(double vel)
{
	mParams[eParamTargetVel] = vel;
}

void cPDController::SetUseWorldCoord(bool use)
{
	mParams[eParamUseWorldCoord] = (use) ? 1 : 0;
}

bool cPDController::UseWorldCoord() const
{
	return mParams[eParamUseWorldCoord] != 0;
}

double cPDController::CalcTheta() const
{
	const cJoint& joint = GetJoint();
	tVector rot_axis;
	double theta = 0;
	if (UseWorldCoord())
	{
		joint.GetChildRotation(rot_axis, theta);
		tVector axis_world = joint.CalcAxisWorld();
		theta *= rot_axis.dot(axis_world);
	}
	else
	{
		joint.CalcRotation(rot_axis, theta);
	}

	return theta;
}

double cPDController::CalcVel() const
{
	const cJoint& joint = GetJoint();
	const tVector& axis_rel = joint.GetAxisRel();

	tVector joint_vel = joint.CalcJointVelRel();
	double vel = joint_vel.dot(axis_rel);
	return vel;
}

double cPDController::CalcThetaErr() const
{
	double theta = CalcTheta();
	double tar_theta = GetTargetTheta();
	double theta_err = tar_theta - theta;
	return theta_err;
}

double cPDController::CalcVelErr() const
{
	double vel = CalcVel();
	double tar_vel = GetTargetVel();
	double vel_err = tar_vel - vel;
	return vel_err;
}

double cPDController::CalcTargetTheta(double torque) const
{
	double theta = CalcTheta();
	double vel = CalcVel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double tar_vel = GetTargetVel();
	double tar_theta = theta + 1 / kp * (torque - kd * (tar_vel - vel));
	return tar_theta;
}

double cPDController::CalcTargetVel(double torque) const
{
	double theta = CalcTheta();
	double vel = CalcVel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double tar_theta = GetTargetTheta();
	double tar_vel = vel + 1 / kd * (torque - kp * (tar_theta - theta));
	return tar_vel;
}

double cPDController::GetTargetTheta() const
{
	return mParams[eParamTargetTheta];
}

double cPDController::GetTargetVel() const
{
	return mParams[eParamTargetVel];
}

bool cPDController::IsActive() const
{
	bool active = cController::IsActive();
	return active;
}

tVector cPDController::CalcTorque() const
{
	const cJoint& joint = GetJoint();
	const tVector& axis_rel = joint.GetAxisRel();

	double kp = mParams[eParamKp];
	double

	double theta_err = CalcThetaErr();
	double vel_err = CalcVelErr();
	double t = kp * theta_err + kd * vel_err;
	tVector torque = axis_rel * t;

	return torque;
}

int cPDController::GetJointID() const
{
	return static_cast<int>(mParams[eParamJointID]);
}


for (int i = 0; i < num_ctrls; ++i)
			{
				tParams curr_params;
				Json::Value json_pd_ctrl = pd_controllers.get(i, 0);
				bool succ_def = ParsePDParams(json_pd_ctrl, curr_params);
				if (succ_def)
				{
					int joint_id = i;
					curr_params[eParamJointID] = i;
					out_buffer.row(i) = curr_params;
				}
				else
				{
					succ = false;
					break;
				}
			}

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

#include "sim/SimCharacter.h"
#include "util/FileUtil.h"

const std::string gPDControllersKey = "PDControllers";
const std::string gPDParamKeys[cPDController::eParamMax] =
{
	"JointID",
	"Kp",
	"Kd",
	"TorqueLim",
	"TargetTheta",
	"TargetVel",
	"UseWorldCoord"
};

bool cPDController::LoadParams(const std::string& file, Eigen::MatrixXd& out_buffer)
{
	std::ifstream f_stream(file);
	Json::Reader reader;
	Json::Value root;
	bool succ = reader.parse(f_stream, root);
	f_stream.close();

	if (succ)
	{
		if (!root[gPDControllersKey].isNull())
		{
			const Json::Value& pd_controllers = root[gPDControllersKey];
			int num_ctrls = pd_controllers.size();
			out_buffer.resize(num_ctrls, eParamMax);

		}

	}
	else
	{
		printf("Failed to load PD controller parameters from %s\n", file.c_str());
	}

	return succ;
}

bool cPDController::ParsePDParams(const Json::Value& root, tParams& out_params)
{
	bool succ = true;

	out_params.setZero();
	for (int i = 0; i < eParamMax; ++i)
	{
		const std::string& curr_key = gPDParamKeys[i];
		if (!root[curr_key].isNull() && root[curr_key].isNumeric())
		{
			Json::Value json_val = root[curr_key];
			double val = json_val.asDouble();
			out_params[i] = val;
		}
	}

	return succ;
}

cPDController::cPDController()
	: cController()
{
	Clear();
}

cPDController::~cPDController()
{
}

void cPDController::Init(cSimCharacter* character, const tParams& params)
{
	cController::Init(character);
	mParams = params;
	mValid = true;

	cJoint& joint = GetJoint();
	double torque_lim = GetTorqueLimit();
	joint.SetTorqueLimit(torque_lim);
}

void cPDController::Clear()
{
	cController::Clear();

	mParams[eParamJointID] = static_cast<double>(cKinTree::gInvalidJointID);
	mParams[eParamKp] = 0;
	mParams[eParamKd] = 0;
	mParams[eParamTorqueLim] = std::numeric_limits<double>::infinity();
	mParams[eParamTargetTheta] = 0;
	mParams[eParamTargetVel] = 0;
	mParams[eParamUseWorldCoord] = 0;
}

void cPDController::Update(double time_step)
{
	if (IsActive())
	{
		cJoint& joint = GetJoint();
		tVector torque = CalcTorque();
		joint.AddTorque(torque);
	}
}

cJoint& cPDController::GetJoint()
{
	return mChar->GetJoint(GetJointID());
}

const cJoint& cPDController::GetJoint() const
{
	return mChar->GetJoint(GetJointID());
}

void cPDController::SetKp(double kp)
{
	mParams[eParamKp] = kp;
}

double cPDController::GetKp() const
{
	return mParams[eParamKp];
}

double cPDController::GetTorqueLimit() const
{
	return mParams[eParamTorqueLim];
}

void cPDController::SetKd(double kd)
{
	mParams[eParamKd] = kd;
}

double cPDController::GetKd() const
{
	return mParams[eParamKd];
}

void cPDController::SetTargetTheta(double theta)
{
	mParams[eParamTargetTheta] = theta;
}

void cPDController::SetTargetVel(double vel)
{
	mParams[eParamTargetVel] = vel;
}

void cPDController::SetUseWorldCoord(bool use)
{
	mParams[eParamUseWorldCoord] = (use) ? 1 : 0;
}

bool cPDController::UseWorldCoord() const
{
	return mParams[eParamUseWorldCoord] != 0;
}

double cPDController::CalcTheta() const
{
	const cJoint& joint = GetJoint();
	tVector rot_axis;
	double theta = 0;
	if (UseWorldCoord())
	{
		joint.GetChildRotation(rot_axis, theta);
		tVector axis_world = joint.CalcAxisWorld();
		theta *= rot_axis.dot(axis_world);
	}
	else
	{
		joint.CalcRotation(rot_axis, theta);
	}

	return theta;
}

double cPDController::CalcVel() const
{
	const cJoint& joint = GetJoint();
	const tVector& axis_rel = joint.GetAxisRel();

	tVector joint_vel = joint.CalcJointVelRel();
	double vel = joint_vel.dot(axis_rel);
	return vel;
}

double cPDController::CalcThetaErr() const
{
	double theta = CalcTheta();
	double tar_theta = GetTargetTheta();
	double theta_err = tar_theta - theta;
	return theta_err;
}

double cPDController::CalcVelErr() const
{
	double vel = CalcVel();
	double tar_vel = GetTargetVel();
	double vel_err = tar_vel - vel;
	return vel_err;
}

double cPDController::CalcTargetTheta(double torque) const
{
	double theta = CalcTheta();
	double vel = CalcVel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double tar_vel = GetTargetVel();
	double tar_theta = theta + 1 / kp * (torque - kd * (tar_vel - vel));
	return tar_theta;
}

double cPDController::CalcTargetVel(double torque) const
{
	double theta = CalcTheta();
	double vel = CalcVel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double tar_theta = GetTargetTheta();
	double tar_vel = vel + 1 / kd * (torque - kp * (tar_theta - theta));
	return tar_vel;
}

double cPDController::GetTargetTheta() const
{
	return mParams[eParamTargetTheta];
}

double cPDController::GetTargetVel() const
{
	return mParams[eParamTargetVel];
}

bool cPDController::IsActive() const
{
	bool active = cController::IsActive();
	return active;
}

tVector cPDController::CalcTorque() const
{
	const cJoint& joint = GetJoint();
	const tVector& axis_rel = joint.GetAxisRel();

	double kp = mParams[eParamKp];
	double kd = mParams[eParamKd];

	double theta_err = CalcThetaErr();
	double vel_err = CalcVelErr();
	double t = kp * theta_err + kd * vel_err;
	tVector torque = axis_rel * t;

	return torque;
}

int cPDController::GetJointID() const
{
	return static_cast<int>(mParams[eParamJointID]);
}


HRESULT FxAttributeFiller::EnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoPost)

#include "pch.h"

HRESULT FxAttributeFiller::Run(FxInternal* myShader, LPDXCCSHADERPROPERTIES pRestoreProps, LPCSTR RestoreMsg)
{
	HRESULT hr= S_OK;

	Shader= myShader;
	Restore= NULL;
	if(pRestoreProps)
	{
		if(RestoreMsg == NULL
		|| IDYES == MessageBoxA((HWND)M3dView::applicationShell(), RestoreMsg , "DirectX Effect Conversion", MB_YESNO|MB_ICONQUESTION) )
		{
			pRestoreProps->GetProperties( &Restore );
		}
	}

	{//ScriptGen
		Script= "";
	}//ScriptGen

	hr= DXCCEnumEffectParameters(Shader->Effect, this);

	{//ScriptGen
		MPlug plugScript(Shader->GetSite(), DirectXShader::aScript);
		plugScript.setValue(Script.GetString());
#ifdef DEBUG
#endif
		Script= "";
	}//ScriptGen

	return hr;
}

HRESULT FxAttributeFiller::PreEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoEnum, BOOL& DoPost)
{
	SasUiLabel = FxParameterGetUiLabel(pEffect, parameter);

	if( parameter.End->Description.Class == D3DXPC_OBJECT)
	{
		switch( parameter.End->Description.Type )
		{
		case D3DXPT_STRING:
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			break;
		default:
			{
				GoDeeper= FALSE;
				DoEnum= FALSE;
				DoPost= FALSE;
				return S_OK;
			}
			break;
		}
	}

	if(parameter.Length == 1)
	{
		SasUiVisible = FxParameterGetUiVisible(pEffect, parameter);
		if(SasUiVisible == TRUE)
		{
			SasUiControl = FxParameterGetUiControl(pEffect, parameter);

			if(0 == lstrcmpiA( SasUiControl.asChar(), "None"))
				SasUiVisible= FALSE;
		}

		if(SasUiVisible == FALSE)
		{
			GoDeeper= FALSE;
			DoEnum= FALSE;
			DoPost= FALSE;
			return S_OK;
		}

		if(0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
		{
			bool validSlider= true;

			D3DXHANDLE hMin= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMin");
			D3DXHANDLE hMax= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMax");

			if(	hMin != NULL
				&& hMax != NULL
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMin, &SasUiMin))
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMax, &SasUiMax)) )
			{
				SasUiSteps= 100;
				D3DXHANDLE hSteps= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiSteps");
				if(hSteps != NULL)
					pEffect->GetInt(hSteps, &SasUiSteps);
			}
			else //FAILED TO GET VALID SLIDER
			{
				SasUiControl = "Any";
			}
		}
	}

	Script.AppendFormat("dxfxStackUp( \"%s\", %d );\n", SasUiLabel.asChar(), (parameter.End->NumChildren() == 0) );

	if(parameter.End->NumChildren() != 0)
	{
		DoEnum= FALSE;
		return S_OK;
	}

	return S_OK;

}

{
	HRESULT hr= S_OK;
	MStatus stat= MS::kSuccess;

	MFnDependencyNode depNode(Shader->GetSite());
	MPlug Plug;

	Plug= Shader->DecodePlug( Shader->TranscodeHandleToPlug( CStringA(parameter.End->LongPathName) ) );
	if(Plug.isNull())
		return E_FAIL;

	FillPlug(parameter, Plug);
	FillScript(parameter, Plug);

	return hr;

}

bool FxAttributeFiller::FillScript( DXCCEffectPath& parameter, MPlug& plug )

{
	MString plugName= Shader->EncodePlug(plug);

	MString MELPlugName= MFnDependencyNode(plug.node()).name() + MString(".") + plugName;

	switch(parameter.End->Description.Class)
	{
	case D3DXPC_SCALAR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
			{
				Script.AppendFormat("\tdxfxControlSliderCreate(\"float\", \"%s\", \"%f\", \"%f\", \"%d\", \"%s\");\n", SasUiLabel.asChar(), SasUiMin, SasUiMax, SasUiSteps, MELPlugName.asChar() );
			}
			else
			{
				Script.AppendFormat("\tdxfxControlScalarCreate(\"float\", \"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
		}
		break;
	case D3DXPC_VECTOR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "ColorPicker")
				&& parameter.End->Description.Columns >= 3)
			{//COLOR
				Script.AppendFormat("\tdxfxControlColorCreate(\"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
			else
			{//VECTOR
				Script.AppendFormat("\tdxfxControlVectorCreate(\"float\", \"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
		}
		break;
	case D3DXPC_MATRIX_ROWS:
	case D3DXPC_MATRIX_COLUMNS:
		{
			Script.AppendFormat("\tdxfxControlMatrixCreate(\"float\", \"%s\", \"%s\", %d, %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Rows, parameter.End->Description.Columns);
		}
		break;
	case D3DXPC_OBJECT:
		switch(parameter.End->Description.Type)
		{
		case D3DXPT_STRING:
			{
				Script.AppendFormat("\tdxfxControlStringCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			{
				Script.AppendFormat("\tdxfxControlTextureCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		default:
			break;
		};
		break;
	default:
		break;
	};

	return true;
}

bool FxAttributeFiller::FillPlug( DXCCEffectPath& parameter, MPlug& plug )
{
	HRESULT hr= S_OK;
	LPDXCCRESOURCE pResource= NULL;
	LPDIRECT3DBASETEXTURE9 pTexture= NULL;
	D3DXPARAMETER_DESC desc= parameter.End->Description;
	float NumericVals[16]= {0.0f};
	MString StringVal;
	LPCSTR StringValStr= "";

	bool RestoreFound= false;
	LPCVOID pRestoreData= NULL;
	size_t RestoreSize= 0;
	CComPtr<IDXCCPropertyCollection> pCollection;
	DXCCPROPERTY_KEY key= 0;

	if(Restore)
	{
		if( DXCC_SUCCEEDED( Restore->GetPath( parameter.End->LongPathName, &pCollection, &key) ) )
		{
			pCollection->GetPropertyValueAsData(key, &pRestoreData);
			DXCCPROPERTY_DESC desc= pCollection->GetPropertyDesc(key);

			if(desc == DXCCPD_STRING)
			{
				StringVal= (LPCSTR)pRestoreData;
				StringValStr= (LPCSTR)pRestoreData;

				RestoreFound= true;
			}
			else
			{
				size_t RestoreSize= DXCCPropertySize( desc, pRestoreData );
				memcpy( NumericVals, pRestoreData, RestoreSize);

				RestoreFound= true;
			}
		}
	}

	if((desc.Type == D3DXPT_BOOL)
	||(desc.Type == D3DXPT_INT)
	||(desc.Type == D3DXPT_FLOAT))
	{

		if(!RestoreFound)
		{

			if(plug.isArray())
			{
				hr=  Shader->Effect->GetFloatArray(parameter.End->Handle, NumericVals, 16);
					if(DXCC_FAILED(hr))
						DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
			else
			{
				hr=  Shader->Effect->GetFloat(parameter.End->Handle, NumericVals);
				if(DXCC_FAILED(hr))
					DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
		}

		if(plug.isArray())
		{
			int count= desc.Rows * desc.Columns;
			for(int i= 0; i < count; i++)
			{
				MPlug subPlug= plug.elementByLogicalIndex(i);
				DXCHECK_MSTATUS(subPlug.setValue( NumericVals[i] ));
			}
		}
		else
		{
			DXCHECK_MSTATUS(plug.setValue( NumericVals[0] ));
		}
	}
	else if((desc.Type == D3DXPT_TEXTURE)
	||(desc.Type == D3DXPT_TEXTURE1D)
	||(desc.Type == D3DXPT_TEXTURE2D)
	||(desc.Type == D3DXPT_TEXTURE3D)
	||(desc.Type == D3DXPT_TEXTURECUBE))
	{

		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetTexture(parameter.End->Handle, &pTexture);
			if(DXCC_SUCCEEDED(hr) && pTexture != NULL)
			{
				hr= g_PreviewPipeline.AccessManager()->FindResourceByPointer(
						(LPUNKNOWN)pTexture,
						NULL,
						&pResource);
				if(DXCC_SUCCEEDED(hr))
				{
					StringVal= pResource->GetResourcePath();
				}
			}
			else
			{
				D3DXHANDLE hResourceAddy= Shader->Effect->GetAnnotationByName( parameter.End->Handle, "SasResourceAddress");
				if(hResourceAddy)
				{
					LPCSTR resourceAddressStr= NULL;
					Shader->Effect->GetString(hResourceAddy, &resourceAddressStr);

					StringVal= resourceAddressStr;
				}
			}
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else if(desc.Type == D3DXPT_STRING)
	{
		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetString(parameter.End->Handle, &StringValStr);
			StringVal= StringValStr;
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else
	{
		DXCC_STATUS_EXIT(hr, E_FAIL, e_Exit, TRUE);
	}

e_Exit:
	DXCC_RELEASE(pResource);
	DXCC_RELEASE(pTexture);

	return DXCC_SUCCEEDED(hr);
}

HRESULT FxAttributeFiller::PostEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter)
{
	Script += "dxfxStackDown( -1 );\n";
	return S_OK;
}


{
	Script += "dxfxStackDown( -1 );\n";
	return S_OK;
}

#include "pch.h"

HRESULT FxAttributeFiller::Run(FxInternal* myShader, LPDXCCSHADERPROPERTIES pRestoreProps, LPCSTR RestoreMsg)
{
	HRESULT hr= S_OK;

	Shader= myShader;
	Restore= NULL;
	if(pRestoreProps)
	{
		if(RestoreMsg == NULL
		|| IDYES == MessageBoxA((HWND)M3dView::applicationShell(), RestoreMsg , "DirectX Effect Conversion", MB_YESNO|MB_ICONQUESTION) )
		{
			pRestoreProps->GetProperties( &Restore );
		}
	}

	{//ScriptGen
		Script= "";
	}//ScriptGen

	hr= DXCCEnumEffectParameters(Shader->Effect, this);

	{//ScriptGen
		MPlug plugScript(Shader->GetSite(), DirectXShader::aScript);
		plugScript.setValue(Script.GetString());
#ifdef DEBUG
#endif
		Script= "";
	}//ScriptGen

	return hr;
}

HRESULT FxAttributeFiller::PreEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoEnum, BOOL& DoPost)
{
	SasUiLabel = FxParameterGetUiLabel(pEffect, parameter);

	if( parameter.End->Description.Class == D3DXPC_OBJECT)
	{
		switch( parameter.End->Description.Type )
		{
		case D3DXPT_STRING:
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			break;
		default:
			{
				GoDeeper= FALSE;
				DoEnum= FALSE;
				DoPost= FALSE;
				return S_OK;
			}
			break;
		}
	}

	if(parameter.Length == 1)
	{
		SasUiVisible = FxParameterGetUiVisible(pEffect, parameter);
		if(SasUiVisible == TRUE)
		{
			SasUiControl = FxParameterGetUiControl(pEffect, parameter);

			if(0 == lstrcmpiA( SasUiControl.asChar(), "None"))
				SasUiVisible= FALSE;
		}

		if(SasUiVisible == FALSE)
		{
			GoDeeper= FALSE;
			DoEnum= FALSE;
			DoPost= FALSE;
			return S_OK;
		}

		if(0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
		{
			bool validSlider= true;

			D3DXHANDLE hMin= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMin");
			D3DXHANDLE hMax= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMax");

			if(	hMin != NULL
				&& hMax != NULL
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMin, &SasUiMin))
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMax, &SasUiMax)) )
			{
				SasUiSteps= 100;
				D3DXHANDLE hSteps= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiSteps");
				if(hSteps != NULL)
					pEffect->GetInt(hSteps, &SasUiSteps);
			}
			else //FAILED TO GET VALID SLIDER
			{
				SasUiControl = "Any";
			}
		}
	}

	Script.AppendFormat("dxfxStackUp( \"%s\", %d );\n", SasUiLabel.asChar(), (parameter.End->NumChildren() == 0) );

	if(parameter.End->NumChildren() != 0)
	{
		DoEnum= FALSE;
		return S_OK;
	}

	return S_OK;

}

HRESULT FxAttributeFiller::EnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoPost)
{
	HRESULT hr= S_OK;
	MStatus stat= MS::kSuccess;

	MFnDependencyNode depNode(Shader->GetSite());
	MPlug Plug;

	Plug= Shader->DecodePlug( Shader->TranscodeHandleToPlug( CStringA(parameter.End->LongPathName) ) );
	if(Plug.isNull())
		return E_FAIL;

	FillPlug(parameter, Plug);
	FillScript(parameter, Plug);

	return hr;

}

bool FxAttributeFiller::FillScript( DXCCEffectPath& parameter, MPlug& plug )

{
	MString plugName= Shader->EncodePlug(plug);

	MString MELPlugName= MFnDependencyNode(plug.node()).name() + MString(".") + plugName;

	switch(parameter.End->Description.Class)
	{
	case D3DXPC_SCALAR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
			{
				Script.AppendFormat("\tdxfxControlSliderCreate(\"float\", \"%s\", \"%f\", \"%f\", \"%d\", \"%s\");\n", SasUiLabel.asChar(), SasUiMin, SasUiMax, SasUiSteps, MELPlugName.asChar() );
			}
			else
			{
				Script.AppendFormat("\tdxfxControlScalarCreate(\"float\", \"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
		}
		break;
	case D3DXPC_VECTOR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "ColorPicker")
				&& parameter.End->Description.Columns >= 3)
			{//COLOR
				Script.AppendFormat("\tdxfxControlColorCreate(\"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
			else
			{//VECTOR
				Script.AppendFormat("\tdxfxControlVectorCreate(\"float\", \"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
		}
		break;
	case D3DXPC_MATRIX_ROWS:
	case D3DXPC_MATRIX_COLUMNS:
		{
			Script.AppendFormat("\tdxfxControlMatrixCreate(\"float\", \"%s\", \"%s\", %d, %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Rows, parameter.End->Description.Columns);
		}
		break;
	case D3DXPC_OBJECT:
		switch(parameter.End->Description.Type)
		{
		case D3DXPT_STRING:
			{
				Script.AppendFormat("\tdxfxControlStringCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			{
				Script.AppendFormat("\tdxfxControlTextureCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		default:
			break;
		};
		break;
	default:
		break;
	};

	return true;
}

bool FxAttributeFiller::FillPlug( DXCCEffectPath& parameter, MPlug& plug )
{
	HRESULT hr= S_OK;
	LPDXCCRESOURCE pResource= NULL;
	LPDIRECT3DBASETEXTURE9 pTexture= NULL;
	D3DXPARAMETER_DESC desc= parameter.End->Description;
	float NumericVals[16]= {0.0f};
	MString StringVal;
	LPCSTR StringValStr= "";

	bool RestoreFound= false;
	LPCVOID pRestoreData= NULL;
	size_t RestoreSize= 0;
	CComPtr<IDXCCPropertyCollection> pCollection;
	DXCCPROPERTY_KEY key= 0;

	if(Restore)
	{
		if( DXCC_SUCCEEDED( Restore->GetPath( parameter.End->LongPathName, &pCollection, &key) ) )
		{
			pCollection->GetPropertyValueAsData(key, &pRestoreData);
			DXCCPROPERTY_DESC desc= pCollection->GetPropertyDesc(key);

			if(desc == DXCCPD_STRING)
			{
				StringVal= (LPCSTR)pRestoreData;
				StringValStr= (LPCSTR)pRestoreData;

				RestoreFound= true;
			}
			else
			{
				size_t RestoreSize= DXCCPropertySize( desc, pRestoreData );
				memcpy( NumericVals, pRestoreData, RestoreSize);

				RestoreFound= true;
			}
		}
	}

	if((desc.Type == D3DXPT_BOOL)
	||(desc.Type == D3DXPT_INT)
	||(desc.Type == D3DXPT_FLOAT))
	{

		if(!RestoreFound)
		{

			if(plug.isArray())
			{
				hr=  Shader->Effect->GetFloatArray(parameter.End->Handle, NumericVals, 16);
					if(DXCC_FAILED(hr))
						DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
			else
			{
				hr=  Shader->Effect->GetFloat(parameter.End->Handle, NumericVals);
				if(DXCC_FAILED(hr))
					DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
		}

		if(plug.isArray())
		{
			int count= desc.Rows * desc.Columns;
			for(int i= 0; i < count; i++)
			{
				MPlug subPlug= plug.elementByLogicalIndex(i);
				DXCHECK_MSTATUS(subPlug.setValue( NumericVals[i] ));
			}
		}
		else
		{
			DXCHECK_MSTATUS(plug.setValue( NumericVals[0] ));
		}
	}
	else if((desc.Type == D3DXPT_TEXTURE)
	||(desc.Type == D3DXPT_TEXTURE1D)
	||(desc.Type == D3DXPT_TEXTURE2D)
	||(desc.Type == D3DXPT_TEXTURE3D)
	||(desc.Type == D3DXPT_TEXTURECUBE))
	{

		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetTexture(parameter.End->Handle, &pTexture);
			if(DXCC_SUCCEEDED(hr) && pTexture != NULL)
			{
				hr= g_PreviewPipeline.AccessManager()->FindResourceByPointer(
						(LPUNKNOWN)pTexture,
						NULL,
						&pResource);
				if(DXCC_SUCCEEDED(hr))
				{
					StringVal= pResource->GetResourcePath();
				}
			}
			else
			{
				D3DXHANDLE hResourceAddy= Shader->Effect->GetAnnotationByName( parameter.End->Handle, "SasResourceAddress");
				if(hResourceAddy)
				{
					LPCSTR resourceAddressStr= NULL;
					Shader->Effect->GetString(hResourceAddy, &resourceAddressStr);

					StringVal= resourceAddressStr;
				}
			}
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else if(desc.Type == D3DXPT_STRING)
	{
		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetString(parameter.End->Handle, &StringValStr);
			StringVal= StringValStr;
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else
	{
		DXCC_STATUS_EXIT(hr, E_FAIL, e_Exit, TRUE);
	}

e_Exit:
	DXCC_RELEASE(pResource);
	DXCC_RELEASE(pTexture);

	return DXCC_SUCCEEDED(hr);
}

HRESULT FxAttributeFiller::PostEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter)


#include "pch.h"

HRESULT FxAttributeFiller::Run(FxInternal* myShader, LPDXCCSHADERPROPERTIES pRestoreProps, LPCSTR RestoreMsg)
{
	HRESULT hr= S_OK;

	Shader= myShader;
	Restore= NULL;
	if(pRestoreProps)
	{
		if(RestoreMsg == NULL
		|| IDYES == MessageBoxA((HWND)M3dView::applicationShell(), RestoreMsg , "DirectX Effect Conversion", MB_YESNO|MB_ICONQUESTION) )
		{
			pRestoreProps->GetProperties( &Restore );
		}
	}

	{//ScriptGen
		Script= "";
	}//ScriptGen

	hr= DXCCEnumEffectParameters(Shader->Effect, this);

	{//ScriptGen
		MPlug plugScript(Shader->GetSite(), DirectXShader::aScript);
		plugScript.setValue(Script.GetString());
#ifdef DEBUG
#endif
		Script= "";
	}//ScriptGen

	return hr;
}

HRESULT FxAttributeFiller::PreEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoEnum, BOOL& DoPost)
{
	SasUiLabel = FxParameterGetUiLabel(pEffect, parameter);

	if( parameter.End->Description.Class == D3DXPC_OBJECT)
	{
		switch( parameter.End->Description.Type )
		{
		case D3DXPT_STRING:
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			break;
		default:
			{
				GoDeeper= FALSE;
				DoEnum= FALSE;
				DoPost= FALSE;
				return S_OK;
			}
			break;
		}
	}

	if(parameter.Length == 1)
	{
		SasUiVisible = FxParameterGetUiVisible(pEffect, parameter);
		if(SasUiVisible == TRUE)
		{
			SasUiControl = FxParameterGetUiControl(pEffect, parameter);

			if(0 == lstrcmpiA( SasUiControl.asChar(), "None"))
				SasUiVisible= FALSE;
		}

		if(SasUiVisible == FALSE)
		{
			GoDeeper= FALSE;
			DoEnum= FALSE;
			DoPost= FALSE;
			return S_OK;
		}

		if(0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
		{
			bool validSlider= true;

			D3DXHANDLE hMin= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMin");
			D3DXHANDLE hMax= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMax");

			if(	hMin != NULL
				&& hMax != NULL
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMin, &SasUiMin))
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMax, &SasUiMax)) )
			{
				SasUiSteps= 100;
				D3DXHANDLE hSteps= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiSteps");
				if(hSteps != NULL)
					pEffect->GetInt(hSteps, &SasUiSteps);
			}
			else //FAILED TO GET VALID SLIDER
			{
				SasUiControl = "Any";
			}
		}
	}

	Script.AppendFormat("dxfxStackUp( \"%s\", %d );\n", SasUiLabel.asChar(), (parameter.End->NumChildren() == 0) );

	if(parameter.End->NumChildren() != 0)
	{
		DoEnum= FALSE;
		return S_OK;
	}

	return S_OK;

}

HRESULT FxAttributeFiller::EnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoPost)
{
	HRESULT hr= S_OK;
	MStatus stat= MS::kSuccess;

	MFnDependencyNode depNode(Shader->GetSite());
	MPlug Plug;

	Plug= Shader->DecodePlug( Shader->TranscodeHandleToPlug( CStringA(parameter.End->LongPathName) ) );
	if(Plug.isNull())
		return E_FAIL;

	FillPlug(parameter, Plug);
	FillScript(parameter, Plug);

	return hr;

}

bool FxAttributeFiller::FillScript( DXCCEffectPath& parameter, MPlug& plug )

{
	MString plugName= Shader->EncodePlug(plug);

	MString MELPlugName= MFnDependencyNode(plug.node()).name() + MString(".") + plugName;

	switch(parameter.End->Description.Class)
	{
	case D3DXPC_SCALAR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
			{
				Script.AppendFormat("\tdxfxControlSliderCreate(\"float\", \"%s\", \"%f\", \"%f\", \"%d\", \"%s\");\n", SasUiLabel.asChar(), SasUiMin, SasUiMax, SasUiSteps, MELPlugName.asChar() );
			}
			else
			{
				Script.AppendFormat("\tdxfxControlScalarCreate(\"float\", \"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
		}
		break;
	case D3DXPC_VECTOR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "ColorPicker")
				&& parameter.End->Description.Columns >= 3)
			{//COLOR
				Script.AppendFormat("\tdxfxControlColorCreate(\"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
			else
			{//VECTOR
				Script.AppendFormat("\tdxfxControlVectorCreate(\"float\", \"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
		}
		break;
	case D3DXPC_MATRIX_ROWS:
	case D3DXPC_MATRIX_COLUMNS:
		{
			Script.AppendFormat("\tdxfxControlMatrixCreate(\"float\", \"%s\", \"%s\", %d, %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Rows, parameter.End->Description.Columns);
		}
		break;
	case D3DXPC_OBJECT:
		switch(parameter.End->Description.Type)
		{
		case D3DXPT_STRING:
			{
				Script.AppendFormat("\tdxfxControlStringCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			{
				Script.AppendFormat("\tdxfxControlTextureCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		default:
			break;
		};
		break;
	default:
		break;
	};

	return true;
}

bool FxAttributeFiller::FillPlug( DXCCEffectPath& parameter, MPlug& plug )
{
	HRESULT hr= S_OK;
	LPDXCCRESOURCE pResource= NULL;
	LPDIRECT3DBASETEXTURE9 pTexture= NULL;
	D3DXPARAMETER_DESC desc= parameter.End->Description;
	float NumericVals[16]= {0.0f};
	MString StringVal;
	LPCSTR StringValStr= "";

	bool RestoreFound= false;
	LPCVOID pRestoreData= NULL;
	size_t RestoreSize= 0;
	CComPtr<IDXCCPropertyCollection> pCollection;
	DXCCPROPERTY_KEY key= 0;

	if(Restore)
	{
		if( DXCC_SUCCEEDED( Restore->GetPath( parameter.End->LongPathName, &pCollection, &key) ) )
		{
			pCollection->GetPropertyValueAsData(key, &pRestoreData);
			DXCCPROPERTY_DESC desc= pCollection->GetPropertyDesc(key);

			if(desc == DXCCPD_STRING)
			{
				StringVal= (LPCSTR)pRestoreData;
				StringValStr= (LPCSTR)pRestoreData;

				RestoreFound= true;
			}
			else
			{
				size_t RestoreSize= DXCCPropertySize( desc, pRestoreData );
				memcpy( NumericVals, pRestoreData, RestoreSize);

				RestoreFound= true;
			}
		}
	}

	if((desc.Type == D3DXPT_BOOL)
	||(desc.Type == D3DXPT_INT)
	||(desc.Type == D3DXPT_FLOAT))
	{

		if(!RestoreFound)
		{

			if(plug.isArray())
			{
				hr=  Shader->Effect->GetFloatArray(parameter.End->Handle, NumericVals, 16);
					if(DXCC_FAILED(hr))
						DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
			else
			{
				hr=  Shader->Effect->GetFloat(parameter.End->Handle, NumericVals);
				if(DXCC_FAILED(hr))
					DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
		}

		if(plug.isArray())
		{
			int count= desc.Rows * desc.Columns;
			for(int i= 0; i < count; i++)
			{
				MPlug subPlug= plug.elementByLogicalIndex(i);
				DXCHECK_MSTATUS(subPlug.setValue( NumericVals[i] ));
			}
		}
		else
		{
			DXCHECK_MSTATUS(plug.setValue( NumericVals[0] ));
		}
	}
	else if((desc.Type == D3DXPT_TEXTURE)
	||(desc.Type == D3DXPT_TEXTURE1D)
	||(desc.Type == D3DXPT_TEXTURE2D)
	||(desc.Type == D3DXPT_TEXTURE3D)
	||(desc.Type == D3DXPT_TEXTURECUBE))
	{

		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetTexture(parameter.End->Handle, &pTexture);
			if(DXCC_SUCCEEDED(hr) && pTexture != NULL)
			{
				hr= g_PreviewPipeline.AccessManager()->FindResourceByPointer(
						(LPUNKNOWN)pTexture,
						NULL,
						&pResource);
				if(DXCC_SUCCEEDED(hr))
				{
					StringVal= pResource->GetResourcePath();
				}
			}
			else
			{
				D3DXHANDLE hResourceAddy= Shader->Effect->GetAnnotationByName( parameter.End->Handle, "SasResourceAddress");
				if(hResourceAddy)
				{
					LPCSTR resourceAddressStr= NULL;
					Shader->Effect->GetString(hResourceAddy, &resourceAddressStr);

					StringVal= resourceAddressStr;
				}
			}
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else if(desc.Type == D3DXPT_STRING)
	{
		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetString(parameter.End->Handle, &StringValStr);
			StringVal= StringValStr;
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else
	{
		DXCC_STATUS_EXIT(hr, E_FAIL, e_Exit, TRUE);
	}

e_Exit:
	DXCC_RELEASE(pResource);
	DXCC_RE

	return DXCC_SUCCEEDED(hr);
}

HRESULT FxAttributeFiller::PostEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter)
{
	Script += "dxfxStackDown( -1 );\n";
	return S_OK;
}


switch(parameter.End->Description.Type)
		{
		case D3DXPT_STRING:
			{
				Script.AppendFormat("\tdxfxControlStringCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			{
				Script.AppendFormat("\tdxfxControlTextureCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		default:
			break;
		}

#include "pch.h"

HRESULT FxAttributeFiller::Run(FxInternal* myShader, LPDXCCSHADERPROPERTIES pRestoreProps, LPCSTR RestoreMsg)
{
	HRESULT hr= S_OK;

	Shader= myShader;
	Restore= NULL;
	if(pRestoreProps)
	{
		if(RestoreMsg == NULL
		|| IDYES == MessageBoxA((HWND)M3dView::applicationShell(), RestoreMsg , "DirectX Effect Conversion", MB_YESNO|MB_ICONQUESTION) )
		{
			pRestoreProps->GetProperties( &Restore );
		}
	}

	{//ScriptGen
		Script= "";
	}//ScriptGen

	hr= DXCCEnumEffectParameters(Shader->Effect, this);

	{//ScriptGen
		MPlug plugScript(Shader->GetSite(), DirectXShader::aScript);
		plugScript.setValue(Script.GetString());
#ifdef DEBUG
#endif
		Script= "";
	}//ScriptGen

	return hr;
}

HRESULT FxAttributeFiller::PreEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoEnum, BOOL& DoPost)
{
	SasUiLabel = FxParameterGetUiLabel(pEffect, parameter);

	if( parameter.End->Description.Class == D3DXPC_OBJECT)
	{
		switch( parameter.End->Description.Type )
		{
		case D3DXPT_STRING:
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			break;
		default:
			{
				GoDeeper= FALSE;
				DoEnum= FALSE;
				DoPost= FALSE;
				return S_OK;
			}
			break;
		}
	}

	if(parameter.Length == 1)
	{
		SasUiVisible = FxParameterGetUiVisible(pEffect, parameter);
		if(SasUiVisible == TRUE)
		{
			SasUiControl = FxParameterGetUiControl(pEffect, parameter);

			if(0 == lstrcmpiA( SasUiControl.asChar(), "None"))
				SasUiVisible= FALSE;
		}

		if(SasUiVisible == FALSE)
		{
			GoDeeper= FALSE;
			DoEnum= FALSE;
			DoPost= FALSE;
			return S_OK;
		}

		if(0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
		{
			bool validSlider= true;

			D3DXHANDLE hMin= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMin");
			D3DXHANDLE hMax= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMax");

			if(	hMin != NULL
				&& hMax != NULL
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMin, &SasUiMin))
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMax, &SasUiMax)) )
			{
				SasUiSteps= 100;
				D3DXHANDLE hSteps= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiSteps");
				if(hSteps != NULL)
					pEffect->GetInt(hSteps, &SasUiSteps);
			}
			else //FAILED TO GET VALID SLIDER
			{
				SasUiControl = "Any";
			}
		}
	}

	Script.AppendFormat("dxfxStackUp( \"%s\", %d );\n", SasUiLabel.asChar(), (parameter.End->NumChildren() == 0) );

	if(parameter.End->NumChildren() != 0)
	{
		DoEnum= FALSE;
		return S_OK;
	}

	return S_OK;

}

HRESULT FxAttributeFiller::EnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoPost)
{
	HRESULT hr= S_OK;
	MStatus stat= MS::kSuccess;

	MFnDependencyNode depNode(Shader->GetSite());
	MPlug Plug;

	Plug= Shader->DecodePlug( Shader->TranscodeHandleToPlug( CStringA(parameter.End->LongPathName) ) );
	if(Plug.isNull())
		return E_FAIL;

	FillPlug(parameter, Plug);
	FillScript(parameter, Plug);

	return hr;

}

bool FxAttributeFiller::FillScript( DXCCEffectPath& parameter, MPlug& plug )

{
	MString plugName= Shader->EncodePlug(plug);

	MString MELPlugName= MFnDependencyNode(plug.node()).name() + MString(".") + plugName;

	switch(parameter.End->Description.Class)
	{
	case D3DXPC_SCALAR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
			{
				Script.AppendFormat("\tdxfxControlSliderCreate(\"float\", \"%s\", \"%f\", \"%f\", \"%d\", \"%s\");\n", SasUiLabel.asChar(), SasUiMin, SasUiMax, SasUiSteps, MELPlugName.asChar() );
			}
			else
			{
				Script.AppendFormat("\tdxfxControlScalarCreate(\"float\", \"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
		}
		break;
	case D3DXPC_VECTOR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "ColorPicker")
				&& parameter.End->Description.Columns >= 3)
			{//COLOR
				Script.AppendFormat("\tdxfxControlColorCreate(\"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
			else
			{//VECTOR
				Script.AppendFormat("\tdxfxControlVectorCreate(\"float\", \"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
		}
		break;
	case D3DXPC_MATRIX_ROWS:
	case D3DXPC_MATRIX_COLUMNS:
		{
			Script.AppendFormat("\tdxfxControlMatrixCreate(\"float\", \"%s\", \"%s\", %d, %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Rows, parameter.End->Description.Columns);
		}
		break;
	case D3DXPC_OBJECT:

;
		break;
	default:
		break;
	};

	return true;
}

bool FxAttributeFiller::FillPlug( DXCCEffectPath& parameter, MPlug& plug )
{
	HRESULT hr= S_OK;
	LPDXCCRESOURCE pResource= NULL;
	LPDIRECT3DBASETEXTURE9 pTexture= NULL;
	D3DXPARAMETER_DESC desc= parameter.End->Description;
	float NumericVals[16]= {0.0f};
	MString StringVal;
	LPCSTR StringValStr= "";

	bool RestoreFound= false;
	LPCVOID pRestoreData= NULL;
	size_t RestoreSize= 0;
	CComPtr<IDXCCPropertyCollection> pCollection;
	DXCCPROPERTY_KEY key= 0;

	if(Restore)
	{
		if( DXCC_SUCCEEDED( Restore->GetPath( parameter.End->LongPathName, &pCollection, &key) ) )
		{
			pCollection->GetPropertyValueAsData(key, &pRestoreData);
			DXCCPROPERTY_DESC desc= pCollection->GetPropertyDesc(key);

			if(desc == DXCCPD_STRING)
			{
				StringVal= (LPCSTR)pRestoreData;
				StringValStr= (LPCSTR)pRestoreData;

				RestoreFound= true;
			}
			else
			{
				size_t RestoreSize= DXCCPropertySize( desc, pRestoreData );
				memcpy( NumericVals, pRestoreData, RestoreSize);

				RestoreFound= true;
			}
		}
	}

	if((desc.Type == D3DXPT_BOOL)
	||(desc.Type == D3DXPT_INT)
	||(desc.Type == D3DXPT_FLOAT))
	{

		if(!RestoreFound)
		{

			if(plug.isArray())
			{
				hr=  Shader->Effect->GetFloatArray(parameter.End->Handle, NumericVals, 16);
					if(DXCC_FAILED(hr))
						DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
			else
			{
				hr=  Shader->Effect->GetFloat(parameter.End->Handle, NumericVals);
				if(DXCC_FAILED(hr))
					DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
		}

		if(plug.isArray())
		{
			int count= desc.Rows * desc.Columns;
			for(int i= 0; i < count; i++)
			{
				MPlug subPlug= plug.elementByLogicalIndex(i);
				DXCHECK_MSTATUS(subPlug.setValue( NumericVals[i] ));
			}
		}
		else
		{
			DXCHECK_MSTATUS(plug.setValue( NumericVals[0] ));
		}
	}
	else if((desc.Type == D3DXPT_TEXTURE)
	||(desc.Type == D3DXPT_TEXTURE1D)
	||(desc.Type == D3DXPT_TEXTURE2D)
	||(desc.Type == D3DXPT_TEXTURE3D)
	||(desc.Type == D3DXPT_TEXTURECUBE))
	{

		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetTexture(parameter.End->Handle, &pTexture);
			if(DXCC_SUCCEEDED(hr) && pTexture != NULL)
			{
				hr= g_PreviewPipeline.AccessManager()->FindResourceByPointer(
						(LPUNKNOWN)pTexture,
						NULL,
						&pResource);
				if(DXCC_SUCCEEDED(hr))
				{
					StringVal= pResource->GetResourcePath();
				}
			}
			else
			{
				D3DXHANDLE hResourceAddy= Shader->Effect->GetAnnotationByName( parameter.End->Handle, "SasResourceAddress");
				if(hResourceAddy)
				{
					LPCSTR resourceAddressStr= NULL;
					Shader->Effect->GetString(hResourceAddy, &resourceAddressStr);

					StringVal= resourceAddressStr;
				}
			}
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else if(desc.Type == D3DXPT_STRING)
	{
		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetString(parameter.End->Handle, &StringValStr);
			StringVal= StringValStr;
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else
	{
		DXCC_STATUS_EXIT(hr, E_FAIL, e_Exit, TRUE);
	}

e_Exit:
	DXCC_RELEASE(pResource);
	DXCC_RELEASE(pTexture);

	return DXCC_SUCCEEDED(hr);
}

HRESULT FxAttributeFiller::PostEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter)
{
	Script += "dxfxStackDown( -1 );\n";
	return S_OK;
}


for(int i= 0; i < count; i++)
			{
				MPlug subPlug= plug.elementByLogicalIndex(i);
				DXCHECK_MSTATUS(subPlug.setValue( NumericVals[i] ));
			}

#include "pch.h"

HRESULT FxAttributeFiller::Run(FxInternal* myShader, LPDXCCSHADERPROPERTIES pRestoreProps, LPCSTR RestoreMsg)
{
	HRESULT hr= S_OK;

	Shader= myShader;
	Restore= NULL;
	if(pRestoreProps)
	{
		if(RestoreMsg == NULL
		|| IDYES == MessageBoxA((HWND)M3dView::applicationShell(), RestoreMsg , "DirectX Effect Conversion", MB_YESNO|MB_ICONQUESTION) )
		{
			pRestoreProps->GetProperties( &Restore );
		}
	}

	{//ScriptGen
		Script= "";
	}//ScriptGen

	hr= DXCCEnumEffectParameters(Shader->Effect, this);

	{//ScriptGen
		MPlug plugScript(Shader->GetSite(), DirectXShader::aScript);
		plugScript.setValue(Script.GetString());
#ifdef DEBUG
#endif
		Script= "";
	}//ScriptGen

	return hr;
}

HRESULT FxAttributeFiller::PreEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoEnum, BOOL& DoPost)
{
	SasUiLabel = FxParameterGetUiLabel(pEffect, parameter);

	if( parameter.End->Description.Class == D3DXPC_OBJECT)
	{
		switch( parameter.End->Description.Type )
		{
		case D3DXPT_STRING:
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			break;
		default:
			{
				GoDeeper= FALSE;
				DoEnum= FALSE;
				DoPost= FALSE;
				return S_OK;
			}
			break;
		}
	}

	if(parameter.Length == 1)
	{
		SasUiVisible = FxParameterGetUiVisible(pEffect, parameter);
		if(SasUiVisible == TRUE)
		{
			SasUiControl = FxParameterGetUiControl(pEffect, parameter);

			if(0 == lstrcmpiA( SasUiControl.asChar(), "None"))
				SasUiVisible= FALSE;
		}

		if(SasUiVisible == FALSE)
		{
			GoDeeper= FALSE;
			DoEnum= FALSE;
			DoPost= FALSE;
			return S_OK;
		}

		if(0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
		{
			bool validSlider= true;

			D3DXHANDLE hMin= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMin");
			D3DXHANDLE hMax= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiMax");

			if(	hMin != NULL
				&& hMax != NULL
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMin, &SasUiMin))
				&& DXCC_SUCCEEDED( pEffect->GetFloat(hMax, &SasUiMax)) )
			{
				SasUiSteps= 100;
				D3DXHANDLE hSteps= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiSteps");
				if(hSteps != NULL)
					pEffect->GetInt(hSteps, &SasUiSteps);
			}
			else //FAILED TO GET VALID SLIDER
			{
				SasUiControl = "Any";
			}
		}
	}

	Script.AppendFormat("dxfxStackUp( \"%s\", %d );\n", SasUiLabel.asChar(), (parameter.End->NumChildren() == 0) );

	if(parameter.End->NumChildren() != 0)
	{
		DoEnum= FALSE;
		return S_OK;
	}

	return S_OK;

}

HRESULT FxAttributeFiller::EnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter, BOOL& GoDeeper, BOOL& DoPost)
{
	HRESULT hr= S_OK;
	MStatus stat= MS::kSuccess;

	MFnDependencyNode depNode(Shader->GetSite());
	MPlug Plug;

	Plug= Shader->DecodePlug( Shader->TranscodeHandleToPlug( CStringA(parameter.End->LongPathName) ) );
	if(Plug.isNull())
		return E_FAIL;

	FillPlug(parameter, Plug);
	FillScript(parameter, Plug);

	return hr;

}

bool FxAttributeFiller::FillScript( DXCCEffectPath& parameter, MPlug& plug )

{
	MString plugName= Shader->EncodePlug(plug);

	MString MELPlugName= MFnDependencyNode(plug.node()).name() + MString(".") + plugName;

	switch(parameter.End->Description.Class)
	{
	case D3DXPC_SCALAR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "Slider"))
			{
				Script.AppendFormat("\tdxfxControlSliderCreate(\"float\", \"%s\", \"%f\", \"%f\", \"%d\", \"%s\");\n", SasUiLabel.asChar(), SasUiMin, SasUiMax, SasUiSteps, MELPlugName.asChar() );
			}
			else
			{
				Script.AppendFormat("\tdxfxControlScalarCreate(\"float\", \"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
		}
		break;
	case D3DXPC_VECTOR:
		{
			if( 0 == lstrcmpiA( SasUiControl.asChar(), "ColorPicker")
				&& parameter.End->Description.Columns >= 3)
			{//COLOR
				Script.AppendFormat("\tdxfxControlColorCreate(\"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
			else
			{//VECTOR
				Script.AppendFormat("\tdxfxControlVectorCreate(\"float\", \"%s\", \"%s\", %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Columns);
			}
		}
		break;
	case D3DXPC_MATRIX_ROWS:
	case D3DXPC_MATRIX_COLUMNS:
		{
			Script.AppendFormat("\tdxfxControlMatrixCreate(\"float\", \"%s\", \"%s\", %d, %d);\n", SasUiLabel.asChar(), MELPlugName.asChar(), parameter.End->Description.Rows, parameter.End->Description.Columns);
		}
		break;
	case D3DXPC_OBJECT:
		switch(parameter.End->Description.Type)
		{
		case D3DXPT_STRING:
			{
				Script.AppendFormat("\tdxfxControlStringCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		case D3DXPT_TEXTURE:
		case D3DXPT_TEXTURE1D:
		case D3DXPT_TEXTURE2D:
		case D3DXPT_TEXTURE3D:
		case D3DXPT_TEXTURECUBE:
			{
				Script.AppendFormat("\tdxfxControlTextureCreate(\"%s\", \"%s\");\n", SasUiLabel.asChar(), MELPlugName.asChar());
			}
			break;
		default:
			break;
		};
		break;
	default:
		break;
	};

	return true;
}

bool FxAttributeFiller::FillPlug( DXCCEffectPath& parameter, MPlug& plug )
{
	HRESULT hr= S_OK;
	LPDXCCRESOURCE pResource= NULL;
	LPDIRECT3DBASETEXTURE9 pTexture= NULL;
	D3DXPARAMETER_DESC desc= parameter.End->Description;
	float NumericVals[16]= {0.0f};
	MString StringVal;
	LPCSTR StringValStr= "";

	bool RestoreFound= false;
	LPCVOID pRestoreData= NULL;
	size_t RestoreSize= 0;
	CComPtr<IDXCCPropertyCollection> pCollection;
	DXCCPROPERTY_KEY key= 0;

	if(Restore)
	{
		if( DXCC_SUCCEEDED( Restore->GetPath( parameter.End->LongPathName, &pCollection, &key) ) )
		{
			pCollection->GetPropertyValueAsData(key, &pRestoreData);
			DXCCPROPERTY_DESC desc= pCollection->GetPropertyDesc(key);

			if(desc == DXCCPD_STRING)
			{
				StringVal= (LPCSTR)pRestoreData;
				StringValStr= (LPCSTR)pRestoreData;

				RestoreFound= true;
			}
			else
			{
				size_t RestoreSize= DXCCPropertySize( desc, pRestoreData );
				memcpy( NumericVals, pRestoreData, RestoreSize);

				RestoreFound= true;
			}
		}
	}

	if((desc.Type == D3DXPT_BOOL)
	||(desc.Type == D3DXPT_INT)
	||(desc.Type == D3DXPT_FLOAT))
	{

		if(!RestoreFound)
		{

			if(plug.isArray())
			{
				hr=  Shader->Effect->GetFloatArray(parameter.End->Handle, NumericVals, 16);
					if(DXCC_FAILED(hr))
						DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
			else
			{
				hr=  Shader->Effect->GetFloat(parameter.End->Handle, NumericVals);
				if(DXCC_FAILED(hr))
					DXCC_GOTO_EXIT(e_Exit, TRUE);
			}
		}

		if(plug.isArray())
		{
			int count= desc.Rows * desc.Columns;

		}
		else
		{
			DXCHECK_MSTATUS(plug.setValue( NumericVals[0] ));
		}
	}
	else if((desc.Type == D3DXPT_TEXTURE)
	||(desc.Type == D3DXPT_TEXTURE1D)
	||(desc.Type == D3DXPT_TEXTURE2D)
	||(desc.Type == D3DXPT_TEXTURE3D)
	||(desc.Type == D3DXPT_TEXTURECUBE))
	{

		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetTexture(parameter.End->Handle, &pTexture);
			if(DXCC_SUCCEEDED(hr) && pTexture != NULL)
			{
				hr= g_PreviewPipeline.AccessManager()->FindResourceByPointer(
						(LPUNKNOWN)pTexture,
						NULL,
						&pResource);
				if(DXCC_SUCCEEDED(hr))
				{
					StringVal= pResource->GetResourcePath();
				}
			}
			else
			{
				D3DXHANDLE hResourceAddy= Shader->Effect->GetAnnotationByName( parameter.End->Handle, "SasResourceAddress");
				if(hResourceAddy)
				{
					LPCSTR resourceAddressStr= NULL;
					Shader->Effect->GetString(hResourceAddy, &resourceAddressStr);

					StringVal= resourceAddressStr;
				}
			}
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else if(desc.Type == D3DXPT_STRING)
	{
		if(!RestoreFound)
		{
			hr=  Shader->Effect->GetString(parameter.End->Handle, &StringValStr);
			StringVal= StringValStr;
		}

		DXCHECK_MSTATUS(plug.setValue( StringVal ));
	}
	else
	{
		DXCC_STATUS_EXIT(hr, E_FAIL, e_Exit, TRUE);
	}

e_Exit:
	DXCC_RELEASE(pResource);
	DXCC_RELEASE(pTexture);

	return DXCC_SUCCEEDED(hr);
}

HRESULT FxAttributeFiller::PostEnumParameter(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter)
{
	Script += "dxfxStackDown( -1 );\n";
	return S_OK;
}


/*
 *
 */

#include "config.h"
#include "HTMLAppletElement.h"

#include "Attribute.h"
#include "HTMLDocument.h"
#include "HTMLNames.h"
#include "RenderApplet.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "Widget.h"

namespace WebCore {

using namespace HTMLNames;

inline HTMLAppletElement::HTMLAppletElement(const QualifiedName& tagName, Document* document)
    : HTMLPlugInElement(tagName, document)
{
    ASSERT(hasTagName(appletTag));
}

PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new HTMLAppletElement(tagName, document));
}

void HTMLAppletElement::parseMappedAttribute(Attribute* attr)
{
    if (attr->name() == altAttr ||
        attr->name() == archiveAttr ||
        attr->name() == codeAttr ||
        attr->name() == codebaseAttr ||
        attr->name() == mayscriptAttr ||
        attr->name() == objectAttr) {
        // Do nothing.
    } else if (attr->name() == nameAttr) {
        const AtomicString& newName = attr->value();
        if (inDocument() && document()->isHTMLDocument()) {
            HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
            document->removeNamedItem(m_name);
            document->addNamedItem(newName);
        }
        m_name = newName;
    } else if (isIdAttributeName(attr->name())) {
        const AtomicString& newId = attr->value();
        if (inDocument() && document()->isHTMLDocument()) {
            HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
            document->removeExtraNamedItem(m_id);
            document->addExtraNamedItem(newId);
        }
        m_id = newId;
        HTMLPlugInElement::parseMappedAttribute(attr);
    } else
        HTMLPlugInElement::parseMappedAttribute(attr);
}

void HTMLAppletElement::insertedIntoDocument()
{
    if (document()->isHTMLDocument()) {
        HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
        document->addNamedItem(m_name);
        document->addExtraNamedItem(m_id);
    }

    HTMLPlugInElement::insertedIntoDocument();
}

void HTMLAppletElement::removedFromDocument()
{
    if (document()->isHTMLDocument()) {
        HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
        document->removeNamedItem(m_name);
        document->removeExtraNamedItem(m_id);
    }

    HTMLPlugInElement::removedFromDocument();
}

bool HTMLAppletElement::rendererIsNeeded(RenderStyle* style)
{
    if (!fastHasAttribute(codeAttr))
        return false;

    return HTMLPlugInElement::rendererIsNeeded(style);
}

RenderObject* HTMLAppletElement::createRenderer(RenderArena*, RenderStyle* style)
{
    if (canEmbedJava()) {
        HashMap<String, String> args;

        args.set("code", getAttribute(codeAttr));

        const AtomicString& codeBase = getAttribute(codebaseAttr);
        if (!codeBase.isNull())
            args.set("codeBase", codeBase);

        const AtomicString& name = document()->isHTMLDocument() ? getAttribute(nameAttr) : getIdAttribute();
        if (!name.isNull())
            args.set("name", name);
        const AtomicString& archive = getAttribute(archiveAttr);
        if (!archive.isNull())
            args.set("archive", archive);

        args.set("baseURL", document()->baseURL().string());

        const AtomicString& mayScript = getAttribute(mayscriptAttr);
        if (!mayScript.isNull())
            args.set("mayScript", mayScript);

        // Other arguments (from <PARAM> tags) are added later.

        return new (document()->renderArena()) RenderApplet(this, args);
    }

    return RenderObject::createObject(this, style);
}

{
    RenderObject* r = renderer();
    if (!r || !r->isWidget())
        return;
    Widget* widget = toRenderWidget(r)->widget();
    if (!widget)
        return;
    widget->handleEvent(event);
}

RenderWidget* HTMLAppletElement::renderWidgetForJSBindings() const
{
    if (!canEmbedJava())
        return 0;

    RenderApplet* applet = toRenderApplet(renderer());
    if (applet)
        applet->createWidgetIfNecessary();

    return applet;
}

bool HTMLAppletElement::canEmbedJava() const
{
    if (document()->securityOrigin()->isSandboxed(SandboxPlugins))
        return false;

    Settings* settings = document()->settings();
    return settings && settings->isJavaEnabled();
}

void HTMLAppletElement::finishParsingChildren()
{
    // The parser just reached </applet>, so all the params are available now.
    HTMLPlugInElement::finishParsingChildren();
    if (renderer())
        renderer()->setNeedsLayout(true); // This will cause it to create its widget & the Java applet
}

}


{
    if (document()->isHTMLDocument()) {
        HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
        document->removeNamedItem(m_name);
        document->removeExtraNamedItem(m_id);
    }

    HTMLPlugInElement::removedFromDocument();
}

/*
 *
 */

#include "config.h"
#include "HTMLAppletElement.h"

#include "Attribute.h"
#include "HTMLDocument.h"
#include "HTMLNames.h"
#include "RenderApplet.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "Widget.h"

namespace WebCore {

using namespace HTMLNames;

inline HTMLAppletElement::HTMLAppletElement(const QualifiedName& tagName, Document* document)
    : HTMLPlugInElement(tagName, document)
{
    ASSERT(hasTagName(appletTag));
}

PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new HTMLAppletElement(tagName, document));
}

void HTMLAppletElement::parseMappedAttribute(Attribute* attr)
{
    if (attr->name() == altAttr ||
        attr->name() == archiveAttr ||
        attr->name() == codeAttr ||
        attr->name() == codebaseAttr ||
        attr->name() == mayscriptAttr ||
        attr->name() == objectAttr) {
        // Do nothing.
    } else if (attr->name() == nameAttr) {
        const AtomicString& newName = attr->value();
        if (inDocument() && document()->isHTMLDocument()) {
            HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
            document->removeNamedItem(m_name);
            document->addNamedItem(newName);
        }
        m_name = newName;
    } else if (isIdAttributeName(attr->name())) {
        const AtomicString& newId = attr->value();
        if (inDocument() && document()->isHTMLDocument()) {
            HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
            document->removeExtraNamedItem(m_id);
            document->addExtraNamedItem(newId);
        }
        m_id = newId;
        HTMLPlugInElement::parseMappedAttribute(attr);
    } else
        HTMLPlugInElement::parseMappedAttribute(attr);
}

void HTMLAppletElement::insertedIntoDocument()
{
    if (document()->isHTMLDocument()) {
        HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
        document->addNamedItem(m_name);
        document->addExtraNamedItem(m_id);
    }

    HTMLPlugInElement::insertedIntoDocument();
}

void HTMLAppletElement::removedFromDocument()

bool HTMLAppletElement::rendererIsNeeded(RenderStyle* style)
{
    if (!fastHasAttribute(codeAttr))
        return false;

    return HTMLPlugInElement::rendererIsNeeded(style);
}

RenderObject* HTMLAppletElement::createRenderer(RenderArena*, RenderStyle* style)
{
    if (canEmbedJava()) {
        HashMap<String, String> args;

        args.set("code", getAttribute(codeAttr));

        const AtomicString& codeBase = getAttribute(codebaseAttr);
        if (!codeBase.isNull())
            args.set("codeBase", codeBase);

        const AtomicString& name = document()->isHTMLDocument() ? getAttribute(nameAttr) : getIdAttribute();
        if (!name.isNull())
            args.set("name", name);
        const AtomicString& archive = getAttribute(archiveAttr);
        if (!archive.isNull())
            args.set("archive", archive);

        args.set("baseURL", document()->baseURL().string());

        const AtomicString& mayScript = getAttribute(mayscriptAttr);
        if (!mayScript.isNull())
            args.set("mayScript", mayScript);

        // Other arguments (from <PARAM> tags) are added later.

        return new (document()->renderArena()) RenderApplet(this, args);
    }

    return RenderObject::createObject(this, style);
}

void HTMLAppletElement::defaultEventHandler(Event* event)
{
    RenderObject* r = renderer();
    if (!r || !r->isWidget())
        return;
    Widget* widget = toRenderWidget(r)->widget();
    if (!widget)
        return;
    widget->handleEvent(event);
}

RenderWidget* HTMLAppletElement::renderWidgetForJSBindings() const
{
    if (!canEmbedJava())
        return 0;

    RenderApplet* applet = toRenderApplet(renderer());
    if (applet)
        applet->createWidgetIfNecessary();

    return applet;
}

bool HTMLAppletElement::canEmbedJava() const
{
    if (document()->securityOrigin()->isSandboxed(SandboxPlugins))
        return false;

    Settings* settings = document()->settings();
    return settings && settings->isJavaEnabled();
}

void HTMLAppletElement::finishParsingChildren()
{
    // The parser just reached </applet>, so all the params are available now.
    HTMLPlugInElement::finishParsingChildren();
    if (renderer())
        renderer()->setNeedsLayout(true); // This will cause it to create its widget & the Java applet
}

}


ettings* settings = document()->settings();

/*
 *
 */

#include "config.h"
#include "HTMLAppletElement.h"

#include "Attribute.h"
#include "HTMLDocument.h"
#include "HTMLNames.h"
#include "RenderApplet.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "Widget.h"

namespace WebCore {

using namespace HTMLNames;

inline HTMLAppletElement::HTMLAppletElement(const QualifiedName& tagName, Document* document)
    : HTMLPlugInElement(tagName, document)
{
    ASSERT(hasTagName(appletTag));
}

PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new HTMLAppletElement(tagName, document));
}

void HTMLAppletElement::parseMappedAttribute(Attribute* attr)
{
    if (attr->name() == altAttr ||
        attr->name() == archiveAttr ||
        attr->name() == codeAttr ||
        attr->name() == codebaseAttr ||
        attr->name() == mayscriptAttr ||
        attr->name() == objectAttr) {
        // Do nothing.
    } else if (attr->name() == nameAttr) {
        const AtomicString& newName = attr->value();
        if (inDocument() && document()->isHTMLDocument()) {
            HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
            document->removeNamedItem(m_name);
            document->addNamedItem(newName);
        }
        m_name = newName;
    } else if (isIdAttributeName(attr->name())) {
        const AtomicString& newId = attr->value();
        if (inDocument() && document()->isHTMLDocument()) {
            HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
            document->removeExtraNamedItem(m_id);
            document->addExtraNamedItem(newId);
        }
        m_id = newId;
        HTMLPlugInElement::parseMappedAttribute(attr);
    } else
        HTMLPlugInElement::parseMappedAttribute(attr);
}

void HTMLAppletElement::insertedIntoDocument()
{
    if (document()->isHTMLDocument()) {
        HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
        document->addNamedItem(m_name);
        document->addExtraNamedItem(m_id);
    }

    HTMLPlugInElement::insertedIntoDocument();
}

void HTMLAppletElement::removedFromDocument()
{
    if (document()->isHTMLDocument()) {
        HTMLDocument* document = static_cast<HTMLDocument*>(this->document());
        document->removeNamedItem(m_name);
        document->removeExtraNamedItem(m_id);
    }

    HTMLPlugInElement::removedFromDocument();
}

bool HTMLAppletElement::rendererIsNeeded(RenderStyle* style)
{
    if (!fastHasAttribute(codeAttr))
        return false;

    return HTMLPlugInElement::rendererIsNeeded(style);
}

RenderObject* HTMLAppletElement::createRenderer(RenderArena*, RenderStyle* style)
{
    if (canEmbedJava()) {
        HashMap<String, String> args;

        args.set("code", getAttribute(codeAttr));

        const AtomicString& codeBase = getAttribute(codebaseAttr);
        if (!codeBase.isNull())
            args.set("codeBase", codeBase);

        const AtomicString& name = document()->isHTMLDocument() ? getAttribute(nameAttr) : getIdAttribute();
        if (!name.isNull())
            args.set("name", name);
        const AtomicString& archive = getAttribute(archiveAttr);
        if (!archive.isNull())
            args.set("archive", archive);

        args.set("baseURL", document()->baseURL().string());

        const AtomicString& mayScript = getAttribute(mayscriptAttr);
        if (!mayScript.isNull())
            args.set("mayScript", mayScript);

        // Other arguments (from <PARAM> tags) are added later.

        return new (document()->renderArena()) RenderApplet(this, args);
    }

    return RenderObject::createObject(this, style);
}

void HTMLAppletElement::defaultEventHandler(Event* event)
{
    RenderObject* r = renderer();
    if (!r || !r->isWidget())
        return;
    Widget* widget = toRenderWidget(r)->widget();
    if (!widget)
        return;
    widget->handleEvent(event);
}

RenderWidget* HTMLAppletElement::renderWidgetForJSBindings() const
{
    if (!canEmbedJava())
        return 0;

    RenderApplet* applet = toRenderApplet(renderer());
    if (applet)
        applet->createWidgetIfNecessary();

    return applet;
}

bool HTMLAppletElement::canEmbedJava() const
{
    if (document()->securityOrigin()->isSandboxed(SandboxPlugins))
        return false;

    S

    return settings && settings->isJavaEnabled();
}

void HTMLAppletElement::finishParsingChildren()
{
    // The parser just reached </applet>, so all the params are available now.
    HTMLPlugInElement::finishParsingChildren();
    if (renderer())
        renderer()->setNeedsLayout(true); // This will cause it to create its widget & the Java applet
}

}