<commit_before>#include "ComponentTransform.h"
#include "GameObject.h"
#include "Glew/include/glew.h"
#include "SDL/include/SDL_opengl.h"
#include "Application.h"
#include "ModuleRenderer3D.h"
#include "ModuleCamera3D.h"
#include "Serializer.h"

// Constructors =================================
ComponentTransform::ComponentTransform() : Component(COMP_TRANSFORMATION)
{
}

ComponentTransform::ComponentTransform(const ComponentTransform & cpy) : Component(cpy), position(cpy.position), scale(cpy.scale), rotation_euler_angles(cpy.rotation_euler_angles), transform_matrix(cpy.transform_matrix), inherited_transform(cpy.inherited_transform)
{
}

// Destructors ==================================
ComponentTransform::~ComponentTransform()
{
}

// Game Loop ====================================
bool ComponentTransform::Update(float dt)
{
	if (draw_axis && parent->IsSelectedObject())
	{
		DrawOrientationAxis();
	}

	if (has_been_modified)
	{
		UpdateTransform();
	}

	if (!parent->GetParent()->IsRoot())
	{
		ComponentTransform* tmp = ((ComponentTransform*)parent->GetParent()->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION));
		inherited_transform = transform_matrix.Transposed() * tmp->inherited_transform;
	}

	return true;
}

// Set Methods ==================================
void ComponentTransform::SetTransformation(aiMatrix4x4 trans)
{
	//Set the mathgeolib matrix from assim matrix
	float values[16] =
	{
		trans.a1, trans.a2, trans.a3, trans.a4,
		trans.b1, trans.b2, trans.b3, trans.b4,
		trans.c1, trans.c2, trans.c3, trans.c4,
		trans.d1, trans.d2, trans.d3, trans.d4
	};

	transform_matrix.Set(values);

	//Set the variables that will be shown in the UI
	transform_matrix.Decompose(position, rotation_quaternion, scale);
	rotation_euler_angles = (rotation_quaternion.ToEulerXYZ() * RADTODEG);

	//Set the inherited transform
	if (!(parent->GetParent()->IsRoot()))
	{
		ComponentTransform* tmp = ((ComponentTransform*)parent->GetParent()->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION));
		inherited_transform = transform_matrix.Transposed() * tmp->inherited_transform;
	}
	else
	{
		inherited_transform = transform_matrix.Transposed();
	}
}

void ComponentTransform::SetTransformation(math::float4x4 trans)
{
	transform_matrix = trans;

	transform_matrix.Decompose(position, rotation_quaternion, scale);
	rotation_euler_angles = rotation_quaternion.ToEulerXYZ();

	//Set the inherited transform
	if (!(parent->GetParent()->IsRoot()))
	{
		ComponentTransform* tmp = ((ComponentTransform*)parent->GetParent()->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION));
		inherited_transform = transform_matrix.Transposed() * tmp->inherited_transform;
	}
	else
	{
		inherited_transform = transform_matrix.Transposed();
	}
}

// Get Methods ==================================
math::float3 ComponentTransform::GetPosition() const
{
	return position;
}

math::float3 ComponentTransform::GetRotationEuler() const
{
	return rotation_euler_angles;
}

math::Quat ComponentTransform::GetRotationQuat() const
{
	return rotation_quaternion;
}

math::float3 ComponentTransform::GetScale() const
{
	return scale;
}

math::float4x4 ComponentTransform::GetTransform() const
{
	return transform_matrix;
}

math::float4x4 ComponentTransform::GetInheritedTransform() const
{
	return inherited_transform;
}

const float* ComponentTransform::GetTransformMatrixRows() const
{
	return transform_matrix.ptr();
}

const float* ComponentTransform::GetTransformMatrixColumns() const
{
	return transform_matrix.Transposed().ptr();
}

// Functionality ================================
void ComponentTransform::BlitComponentInspector()
{
	ImGui::Separator();

	ImGui::Checkbox("##transform_comp", &actived);
	ImGui::SameLine();
	ImGui::TextColored(ImVec4(1.0f, 0.64f, 0.0f, 1.0f), "Transform");
	ImGui::SameLine();
	ImGui::Checkbox("Draw Axis##transform", &draw_axis);

	//Transform Position
	ImGui::Text("Position ");
	ImGui::SameLine();
	ImGui::PushItemWidth(50);
	if (ImGui::DragFloat("X##position", &position.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Y##position", &position.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Z##position", &position.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;

	//Transform rotation
	bool has_rotate = false;
	ImGui::Text("Rotation ");
	ImGui::SameLine();
	if (ImGui::DragFloat("X##rotation", &rotation_euler_angles.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Y##rotation", &rotation_euler_angles.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Z##rotation", &rotation_euler_angles.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;

	//Transform scale
	ImGui::Text("Scale    ");
	ImGui::SameLine();
	if (ImGui::DragFloat("X##scale", &scale.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Y##scale", &scale.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Z##scale", &scale.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::PopItemWidth();

	ImGui::Text("Normalized Scale");
	float norm = (scale.x + scale.y + scale.z) / 3.0f;
	if (ImGui::DragFloat("Normalized Scale", &norm, 0.2f, 0.1f))
	{
		if (norm < 0.01f)norm = 0.01f;
		scale.SetFromScalar(norm);
		has_been_modified = true;
	}
}

void ComponentTransform::UpdateTransform()
{
	rotation_quaternion = math::Quat::FromEulerXYZ(rotation_euler_angles.x * DEGTORAD, rotation_euler_angles.y  * DEGTORAD, rotation_euler_angles.z  * DEGTORAD);

	transform_matrix = math::float4x4::FromQuat(rotation_quaternion);
	transform_matrix = math::float4x4::Scale(scale, math::float3(0, 0, 0)) * transform_matrix;
	transform_matrix.SetTranslatePart(position.x, position.y, position.z);
	//If its parent is scene update inherited matrix

	if (parent->GetParent()->IsRoot())
	{
		inherited_transform = transform_matrix.Transposed();
		parent->GetBoundingBox()->Scale(parent->GetBoundingBox()->CenterPoint(),scale);
	}

	has_been_modified = false;
}

void ComponentTransform::SetMatrixToDraw()
{
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();

	glMultMatrixf(inherited_transform.ptr());
}

void ComponentTransform::QuitMatrixToDraw()
{
	glPopMatrix();
}

void ComponentTransform::DrawOrientationAxis()
{

	if (App->renderer3D->GetGizmo())
	{
		App->renderer3D->GetGizmo()->SetEditMatrix(inherited_transform.ptr());
	}

}

void ComponentTransform::UpdateRotationPositionScale()
{

	if (parent->GetParent()->IsRoot())
	{
		transform_matrix = inherited_transform.Transposed();
		transform_matrix.Decompose(position, rotation_quaternion, scale);
		rotation_euler_angles = rotation_quaternion.ToEulerXYZ() * RADTODEG;
	}
	else
	{
		ComponentTransform* tmp = ((ComponentTransform*)parent->GetParent()->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION));

		if (tmp)
		{
			transform_matrix = inherited_transform * tmp->inherited_transform.Inverted();
			transform_matrix.Transpose();
			transform_matrix.Decompose(position, rotation_quaternion, scale);
			rotation_euler_angles = rotation_quaternion.ToEulerXYZ() * RADTODEG;
		}
	}
}

bool ComponentTransform::Save(Serializer & array_root) const
{
	bool ret = false;

	//Serializer where all the data of the component is built
	Serializer comp_data;

	//Insert Component Type
	ret = comp_data.InsertString("type", ComponentTypeToStr(type));
	//Insert component id
	ret = comp_data.InsertInt("id", id);
	//Insert actived
	ret = comp_data.InsertBool("actived", actived);

	//Insert transform matrix
	Serializer trans_matrix_array = comp_data.InsertArray("transform_matrix");
	for (uint k = 0; k < 16; k++)trans_matrix_array.InsertArrayFloat(transform_matrix.ptr()[k]);
	//Insert position
	Serializer position_array = comp_data.InsertArray("position");
	for (uint k = 0; k < 3; k++)position_array.InsertArrayFloat(position.ptr()[k]);
	//Insert inherited transform matrix
	Serializer inherited_trans_array = comp_data.InsertArray("inherited_transform");
	for (uint k = 0; k < 16; k++)inherited_trans_array.InsertArrayFloat(inherited_transform.Transposed().ptr()[k]);

	//Insert scale
	Serializer scale_array = comp_data.InsertArray("scale");
	for (uint k = 0; k < 3; k++)scale_array.InsertArrayFloat(scale.ptr()[k]);
	//Insert euler angles
	Serializer euler_angles_array = comp_data.InsertArray("euler_angles");
	for (uint k = 0; k < 3; k++)euler_angles_array.InsertArrayFloat(rotation_euler_angles.ptr()[k]);

	//Save the built data in the components array
	ret = array_root.InsertArrayElement(comp_data);

	return ret;
}

bool ComponentTransform::Load(Serializer & data, std::vector<std::pair<Component*, uint>>& links)
{
	bool ret = true;

	//Get component id
	id = data.GetInt("id");
	//Get actived
	actived = data.GetBool("actived");

	//Get transform matrix
	Serializer trans_matrix_array = data.GetArray("transform_matrix");
	for (uint k = 0; k < 16; k++)transform_matrix.ptr()[k] = trans_matrix_array.GetArrayFloat(k);
	//Get position
	Serializer position_array = data.GetArray("position");
	for (uint k = 0; k < 3; k++)position.ptr()[k] = position_array.GetArrayFloat(k);
	//Get inherited transform matrix
	Serializer inherited_trans_array = data.GetArray("inherited_transform");
	for (uint k = 0; k < 16; k++)inherited_transform.ptr()[k] = inherited_trans_array.GetArrayFloat(k);
	//Get scale
	Serializer scale_array = data.GetArray("scale");
	for (uint k = 0; k < 3; k++)scale.ptr()[k] = scale_array.GetArrayFloat(k);
	//Get euler angles
	Serializer euler_angles_array = data.GetArray("euler_angles");
	for (uint k = 0; k < 3; k++)rotation_euler_angles.ptr()[k] = euler_angles_array.GetArrayFloat(k);

	//Calculate the resulting transform with the loaded data
	UpdateTransform();

	return ret;
}
<commit_msg>Scale and rotating bug Bixed [Still appears with gizmo]<commit_after>#include "ComponentTransform.h"
#include "GameObject.h"
#include "Glew/include/glew.h"
#include "SDL/include/SDL_opengl.h"
#include "Application.h"
#include "ModuleRenderer3D.h"
#include "ModuleCamera3D.h"
#include "Serializer.h"

// Constructors =================================
ComponentTransform::ComponentTransform() : Component(COMP_TRANSFORMATION)
{
}

ComponentTransform::ComponentTransform(const ComponentTransform & cpy) : Component(cpy), position(cpy.position), scale(cpy.scale), rotation_euler_angles(cpy.rotation_euler_angles), transform_matrix(cpy.transform_matrix), inherited_transform(cpy.inherited_transform)
{
}

// Destructors ==================================
ComponentTransform::~ComponentTransform()
{
}

// Game Loop ====================================
bool ComponentTransform::Update(float dt)
{
	if (draw_axis && parent->IsSelectedObject())
	{
		DrawOrientationAxis();
	}

	if (has_been_modified)
	{
		UpdateTransform();
	}

	if (!parent->GetParent()->IsRoot())
	{
		ComponentTransform* tmp = ((ComponentTransform*)parent->GetParent()->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION));
		inherited_transform = transform_matrix.Transposed() * tmp->inherited_transform;
	}

	return true;
}

// Set Methods ==================================
void ComponentTransform::SetTransformation(aiMatrix4x4 trans)
{
	//Set the mathgeolib matrix from assim matrix
	float values[16] =
	{
		trans.a1, trans.a2, trans.a3, trans.a4,
		trans.b1, trans.b2, trans.b3, trans.b4,
		trans.c1, trans.c2, trans.c3, trans.c4,
		trans.d1, trans.d2, trans.d3, trans.d4
	};

	transform_matrix.Set(values);

	//Set the variables that will be shown in the UI
	transform_matrix.Decompose(position, rotation_quaternion, scale);
	rotation_euler_angles = (rotation_quaternion.ToEulerXYZ() * RADTODEG);

	//Set the inherited transform
	if (!(parent->GetParent()->IsRoot()))
	{
		ComponentTransform* tmp = ((ComponentTransform*)parent->GetParent()->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION));
		inherited_transform = transform_matrix.Transposed() * tmp->inherited_transform;
	}
	else
	{
		inherited_transform = transform_matrix.Transposed();
	}
}

void ComponentTransform::SetTransformation(math::float4x4 trans)
{
	transform_matrix = trans;

	transform_matrix.Decompose(position, rotation_quaternion, scale);
	rotation_euler_angles = rotation_quaternion.ToEulerXYZ();

	//Set the inherited transform
	if (!(parent->GetParent()->IsRoot()))
	{
		ComponentTransform* tmp = ((ComponentTransform*)parent->GetParent()->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION));
		inherited_transform = transform_matrix.Transposed() * tmp->inherited_transform;
	}
	else
	{
		inherited_transform = transform_matrix.Transposed();
	}
}

// Get Methods ==================================
math::float3 ComponentTransform::GetPosition() const
{
	return position;
}

math::float3 ComponentTransform::GetRotationEuler() const
{
	return rotation_euler_angles;
}

math::Quat ComponentTransform::GetRotationQuat() const
{
	return rotation_quaternion;
}

math::float3 ComponentTransform::GetScale() const
{
	return scale;
}

math::float4x4 ComponentTransform::GetTransform() const
{
	return transform_matrix;
}

math::float4x4 ComponentTransform::GetInheritedTransform() const
{
	return inherited_transform;
}

const float* ComponentTransform::GetTransformMatrixRows() const
{
	return transform_matrix.ptr();
}

const float* ComponentTransform::GetTransformMatrixColumns() const
{
	return transform_matrix.Transposed().ptr();
}

// Functionality ================================
void ComponentTransform::BlitComponentInspector()
{
	ImGui::Separator();

	ImGui::Checkbox("##transform_comp", &actived);
	ImGui::SameLine();
	ImGui::TextColored(ImVec4(1.0f, 0.64f, 0.0f, 1.0f), "Transform");
	ImGui::SameLine();
	ImGui::Checkbox("Draw Axis##transform", &draw_axis);

	//Transform Position
	ImGui::Text("Position ");
	ImGui::SameLine();
	ImGui::PushItemWidth(50);
	if (ImGui::DragFloat("X##position", &position.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Y##position", &position.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Z##position", &position.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;

	//Transform rotation
	bool has_rotate = false;
	ImGui::Text("Rotation ");
	ImGui::SameLine();
	if (ImGui::DragFloat("X##rotation", &rotation_euler_angles.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Y##rotation", &rotation_euler_angles.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Z##rotation", &rotation_euler_angles.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;

	//Transform scale
	ImGui::Text("Scale    ");
	ImGui::SameLine();
	if (ImGui::DragFloat("X##scale", &scale.x, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Y##scale", &scale.y, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::SameLine();
	if (ImGui::DragFloat("Z##scale", &scale.z, 0.5f, 0.0f, 0.0f, "%.2f")) has_been_modified = true;
	ImGui::PopItemWidth();

	ImGui::Text("Normalized Scale");
	float norm = (scale.x + scale.y + scale.z) / 3.0f;
	if (ImGui::DragFloat("Normalized Scale", &norm, 0.2f, 0.1f))
	{
		if (norm < 0.01f)norm = 0.01f;
		scale.SetFromScalar(norm);
		has_been_modified = true;
	}
}

void ComponentTransform::UpdateTransform()
{
	rotation_quaternion = math::Quat::FromEulerXYZ(rotation_euler_angles.x * DEGTORAD, rotation_euler_angles.y  * DEGTORAD, rotation_euler_angles.z  * DEGTORAD);

	transform_matrix = math::float4x4::Scale(scale, math::float3(0, 0, 0));
	transform_matrix = math::float4x4::FromQuat(rotation_quaternion)  * transform_matrix;

	transform_matrix.SetTranslatePart(position.x, position.y, position.z);
	//If its parent is scene update inherited matrix

	if (parent->GetParent()->IsRoot())
	{
		inherited_transform = transform_matrix.Transposed();
		parent->GetBoundingBox()->Scale(parent->GetBoundingBox()->CenterPoint(),scale);
	}

	has_been_modified = false;
}

void ComponentTransform::SetMatrixToDraw()
{
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();

	glMultMatrixf(inherited_transform.ptr());
}

void ComponentTransform::QuitMatrixToDraw()
{
	glPopMatrix();
}

void ComponentTransform::DrawOrientationAxis()
{

	if (App->renderer3D->GetGizmo())
	{
		App->renderer3D->GetGizmo()->SetEditMatrix(inherited_transform.ptr());
	}

}

void ComponentTransform::UpdateRotationPositionScale()
{

	if (parent->GetParent()->IsRoot())
	{
		transform_matrix = inherited_transform.Transposed();
		transform_matrix.Decompose(position, rotation_quaternion, scale);
		rotation_euler_angles = rotation_quaternion.ToEulerXYZ() * RADTODEG;
	}
	else
	{
		ComponentTransform* tmp = ((ComponentTransform*)parent->GetParent()->FindComponent(COMPONENT_TYPE::COMP_TRANSFORMATION));

		if (tmp)
		{
			transform_matrix = inherited_transform * tmp->inherited_transform.Inverted();
			transform_matrix.Transpose();
			transform_matrix.Decompose(position, rotation_quaternion, scale);
			rotation_euler_angles = rotation_quaternion.ToEulerXYZ() * RADTODEG;
		}
	}
}

bool ComponentTransform::Save(Serializer & array_root) const
{
	bool ret = false;

	//Serializer where all the data of the component is built
	Serializer comp_data;

	//Insert Component Type
	ret = comp_data.InsertString("type", ComponentTypeToStr(type));
	//Insert component id
	ret = comp_data.InsertInt("id", id);
	//Insert actived
	ret = comp_data.InsertBool("actived", actived);

	//Insert transform matrix
	Serializer trans_matrix_array = comp_data.InsertArray("transform_matrix");
	for (uint k = 0; k < 16; k++)trans_matrix_array.InsertArrayFloat(transform_matrix.ptr()[k]);
	//Insert position
	Serializer position_array = comp_data.InsertArray("position");
	for (uint k = 0; k < 3; k++)position_array.InsertArrayFloat(position.ptr()[k]);
	//Insert inherited transform matrix
	Serializer inherited_trans_array = comp_data.InsertArray("inherited_transform");
	for (uint k = 0; k < 16; k++)inherited_trans_array.InsertArrayFloat(inherited_transform.Transposed().ptr()[k]);

	//Insert scale
	Serializer scale_array = comp_data.InsertArray("scale");
	for (uint k = 0; k < 3; k++)scale_array.InsertArrayFloat(scale.ptr()[k]);
	//Insert euler angles
	Serializer euler_angles_array = comp_data.InsertArray("euler_angles");
	for (uint k = 0; k < 3; k++)euler_angles_array.InsertArrayFloat(rotation_euler_angles.ptr()[k]);

	//Save the built data in the components array
	ret = array_root.InsertArrayElement(comp_data);

	return ret;
}

bool ComponentTransform::Load(Serializer & data, std::vector<std::pair<Component*, uint>>& links)
{
	bool ret = true;

	//Get component id
	id = data.GetInt("id");
	//Get actived
	actived = data.GetBool("actived");

	//Get transform matrix
	Serializer trans_matrix_array = data.GetArray("transform_matrix");
	for (uint k = 0; k < 16; k++)transform_matrix.ptr()[k] = trans_matrix_array.GetArrayFloat(k);
	//Get position
	Serializer position_array = data.GetArray("position");
	for (uint k = 0; k < 3; k++)position.ptr()[k] = position_array.GetArrayFloat(k);
	//Get inherited transform matrix
	Serializer inherited_trans_array = data.GetArray("inherited_transform");
	for (uint k = 0; k < 16; k++)inherited_transform.ptr()[k] = inherited_trans_array.GetArrayFloat(k);
	//Get scale
	Serializer scale_array = data.GetArray("scale");
	for (uint k = 0; k < 3; k++)scale.ptr()[k] = scale_array.GetArrayFloat(k);
	//Get euler angles
	Serializer euler_angles_array = data.GetArray("euler_angles");
	for (uint k = 0; k < 3; k++)rotation_euler_angles.ptr()[k] = euler_angles_array.GetArrayFloat(k);

	//Calculate the resulting transform with the loaded data
	UpdateTransform();

	return ret;
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2009 Torus Knot Software Ltd

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

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

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

namespace Ogre {

    D3D9GpuProgram::CmdColumnMajorMatrices D3D9GpuProgram::msCmdColumnMajorMatrices;
	D3D9GpuProgram::CmdExternalMicrocode D3D9GpuProgram::msCmdExternalMicrocode;

   //-----------------------------------------------------------------------
    String D3D9GpuProgram::CmdColumnMajorMatrices::doGet(const void *target) const
    {
        return StringConverter::toString(static_cast<const D3D9GpuProgram*>(target)->getColumnMajorMatrices());
    }
    void D3D9GpuProgram::CmdColumnMajorMatrices::doSet(void *target, const String& val)
    {
        static_cast<D3D9GpuProgram*>(target)->setColumnMajorMatrices(StringConverter::parseBool(val));
    }
    //-----------------------------------------------------------------------
    String D3D9GpuProgram::CmdExternalMicrocode::doGet(const void *target) const
    {
		//D3D9GpuProgram* program=const_cast<D3D9GpuProgram*>(static_cast<const D3D9GpuProgram*>(target));
		//LPD3DXBUFFER ptr=program->getExternalMicrocode();
		//nothing to do
		return String();
    }
    void D3D9GpuProgram::CmdExternalMicrocode::doSet(void *target, const String& val)
    {
		D3D9GpuProgram* program = const_cast<D3D9GpuProgram*>(static_cast<const D3D9GpuProgram*>(target));
		const void* buffer = val.data();
		program->setExternalMicrocode(buffer, val.size());
    }

    //-----------------------------------------------------------------------------
    D3D9GpuProgram::D3D9GpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle,
        const String& group, bool isManual, ManualResourceLoader* loader)
        : GpuProgram(creator, name, handle, group, isManual, loader), mpExternalMicrocode(NULL), mColumnMajorMatrices(true)
    {
        if (createParamDictionary("D3D9GpuProgram"))
        {
            setupBaseParamDictionary();

            ParamDictionary* dict = getParamDictionary();
            dict->addParameter(ParameterDef("column_major_matrices",
                "Whether matrix packing in column-major order.",
                PT_BOOL),&msCmdColumnMajorMatrices);
			dict->addParameter(ParameterDef("external_micro_code",
				"the cached external micro code data.",
				PT_STRING),&msCmdExternalMicrocode);
        }
    }

	//-----------------------------------------------------------------------------
	D3D9GpuProgram::~D3D9GpuProgram()
	{

	}

	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::setExternalMicrocode(const void* pMicrocode, size_t size)
	{
		LPD3DXBUFFER pBuffer=0;
		HRESULT hr=D3DXCreateBuffer(size, &pBuffer);
		if(pBuffer)
		{
			memcpy(pBuffer->GetBufferPointer(), pMicrocode, size);
			this->setExternalMicrocode(pBuffer);
			SAFE_RELEASE(pBuffer);
		}
	}
	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::setExternalMicrocode(ID3DXBuffer* pMicrocode)
	{
		SAFE_RELEASE(mpExternalMicrocode);
		mpExternalMicrocode = pMicrocode;
		if(mpExternalMicrocode)
		{
			mpExternalMicrocode->AddRef();
		}
	}
    //-----------------------------------------------------------------------------
	LPD3DXBUFFER D3D9GpuProgram::getExternalMicrocode(void)
	{
		return mpExternalMicrocode;
	}

	//-----------------------------------------------------------------------------
    void D3D9GpuProgram::loadImpl(void)
    {
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		for (uint i = 0; i < D3D9RenderSystem::getResourceCreationDeviceCount(); ++i)
		{
			IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getResourceCreationDevice(i);

			loadImpl(d3d9Device);
		}
    }

	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::loadImpl(IDirect3DDevice9* d3d9Device)
	{
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		if (mpExternalMicrocode)
		{
			loadFromMicrocode(d3d9Device, mpExternalMicrocode);
		}
		else
		{
			// Normal load-from-source approach
			if (mLoadFromFile)
			{
				// find & load source code
				DataStreamPtr stream =
					ResourceGroupManager::getSingleton().openResource(
					mFilename, mGroup, true, this);
				mSource = stream->getAsString();
			}

			// Call polymorphic load
			loadFromSource(d3d9Device);
		}
	}
	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::unloadImpl(void)
	{
		SAFE_RELEASE(mpExternalMicrocode);
	}
	//-----------------------------------------------------------------------------
    void D3D9GpuProgram::loadFromSource(void)
    {
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		for (uint i = 0; i < D3D9RenderSystem::getResourceCreationDeviceCount(); ++i)
		{
			IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getResourceCreationDevice(i);

			loadFromSource(d3d9Device);
		}
    }

	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::loadFromSource(IDirect3DDevice9* d3d9Device)
	{
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		// Populate compile flags
        DWORD compileFlags = 0;

		// Create the shader
		// Assemble source into microcode
		LPD3DXBUFFER microcode;
		LPD3DXBUFFER errors;
		HRESULT hr = D3DXAssembleShader(
			mSource.c_str(),
			static_cast<UINT>(mSource.length()),
			NULL,               // no #define support
			NULL,               // no #include support
			compileFlags,       // standard compile options
			&microcode,
			&errors);

		if (FAILED(hr))
		{
			String message = "Cannot assemble D3D9 shader " + mName + " Errors:\n" +
				static_cast<const char*>(errors->GetBufferPointer());
			errors->Release();
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, message,
				"D3D9GpuProgram::loadFromSource");
		}

		loadFromMicrocode(d3d9Device, microcode);

		SAFE_RELEASE(microcode);
		SAFE_RELEASE(errors);
	}
    //-----------------------------------------------------------------------
    GpuProgramParametersSharedPtr D3D9GpuProgram::createParameters(void)
    {
        // Call superclass
        GpuProgramParametersSharedPtr params = GpuProgram::createParameters();

        // Need to transpose matrices if compiled with column-major matrices
        params->setTransposeMatrices(mColumnMajorMatrices);

        return params;
    }
	//-----------------------------------------------------------------------------
    D3D9GpuVertexProgram::D3D9GpuVertexProgram(ResourceManager* creator,
        const String& name, ResourceHandle handle, const String& group,
        bool isManual, ManualResourceLoader* loader)
        : D3D9GpuProgram(creator, name, handle, group, isManual, loader)
    {
        mType = GPT_VERTEX_PROGRAM;
    }
	//-----------------------------------------------------------------------------
	D3D9GpuVertexProgram::~D3D9GpuVertexProgram()
	{
		// have to call this here reather than in Resource destructor
		// since calling virtual methods in base destructors causes crash
		unload();
	}
	//-----------------------------------------------------------------------------
    void D3D9GpuVertexProgram::loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode)
    {
		DeviceToVertexShaderIterator it = mMapDeviceToVertexShader.find(d3d9Device);

		if (it != mMapDeviceToVertexShader.end())
			SAFE_RELEASE(it->second);

		if (isSupported())
		{
			// Create the shader
			IDirect3DVertexShader9* pVertexShader;
			HRESULT hr;

			hr = d3d9Device->CreateVertexShader(
				static_cast<DWORD*>(microcode->GetBufferPointer()),
				&pVertexShader);

			if (FAILED(hr))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
					"Cannot create D3D9 vertex shader " + mName + " from microcode",
					"D3D9GpuVertexProgram::loadFromMicrocode");

			}

			mMapDeviceToVertexShader[d3d9Device] = pVertexShader;
		}
		else
		{
			LogManager::getSingleton().logMessage(
				"Unsupported D3D9 vertex shader '" + mName + "' was not loaded.");

			mMapDeviceToVertexShader[d3d9Device] = NULL;
		}
    }
	//-----------------------------------------------------------------------------
    void D3D9GpuVertexProgram::unloadImpl(void)
    {
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

        DeviceToVertexShaderIterator it = mMapDeviceToVertexShader.begin();

		while (it != mMapDeviceToVertexShader.end())
		{
			SAFE_RELEASE(it->second);
			++it;
		}
		mMapDeviceToVertexShader.clear();
		D3D9GpuProgram::unloadImpl();
    }

	//-----------------------------------------------------------------------------
	void D3D9GpuVertexProgram::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device)
	{

	}

	//-----------------------------------------------------------------------------
	void D3D9GpuVertexProgram::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device)
	{
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		DeviceToVertexShaderIterator it;

		// Find the shader of this device.
		it = mMapDeviceToVertexShader.find(d3d9Device);

		// Case shader found -> release it and erase from map.
		if (it != mMapDeviceToVertexShader.end())
		{
			SAFE_RELEASE(it->second);
			mMapDeviceToVertexShader.erase(it);
		}
	}

	//-----------------------------------------------------------------------------
	IDirect3DVertexShader9* D3D9GpuVertexProgram::getVertexShader( void )
	{
		IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device();
		DeviceToVertexShaderIterator it;

		// Find the shader of this device.
		it = mMapDeviceToVertexShader.find(d3d9Device);

		// Shader was not found -> load it.
		if (it == mMapDeviceToVertexShader.end())
		{
			loadImpl(d3d9Device);
			it = mMapDeviceToVertexShader.find(d3d9Device);
		}

		return it->second;
	}

	//-----------------------------------------------------------------------------
	//-----------------------------------------------------------------------------
    D3D9GpuFragmentProgram::D3D9GpuFragmentProgram(ResourceManager* creator,
        const String& name, ResourceHandle handle, const String& group,
        bool isManual, ManualResourceLoader* loader)
        : D3D9GpuProgram(creator, name, handle, group, isManual, loader)
    {
        mType = GPT_FRAGMENT_PROGRAM;
    }
	//-----------------------------------------------------------------------------
	D3D9GpuFragmentProgram::~D3D9GpuFragmentProgram()
	{
		// have to call this here reather than in Resource destructor
		// since calling virtual methods in base destructors causes crash
		unload();
	}
	//-----------------------------------------------------------------------------
    void D3D9GpuFragmentProgram::loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode)
    {
		DeviceToPixelShaderIterator it = mMapDeviceToPixelShader.find(d3d9Device);

		if (it != mMapDeviceToPixelShader.end())
			SAFE_RELEASE(it->second);

		if (isSupported())
		{
			// Create the shader
			IDirect3DPixelShader9* pPixelShader;
			HRESULT hr;

			hr = d3d9Device->CreatePixelShader(
				static_cast<DWORD*>(microcode->GetBufferPointer()),
				&pPixelShader);

			if (FAILED(hr))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
					"Cannot create D3D9 pixel shader " + mName + " from microcode.",
					"D3D9GpuFragmentProgram::loadFromMicrocode");

			}

			mMapDeviceToPixelShader[d3d9Device] = pPixelShader;
		}
		else
		{
			LogManager::getSingleton().logMessage(
				"Unsupported D3D9 pixel shader '" + mName + "' was not loaded.");

			mMapDeviceToPixelShader[d3d9Device] = NULL;
		}
    }
	//-----------------------------------------------------------------------------
    void D3D9GpuFragmentProgram::unloadImpl(void)
    {
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		DeviceToPixelShaderIterator it = mMapDeviceToPixelShader.begin();

		while (it != mMapDeviceToPixelShader.end())
		{
			SAFE_RELEASE(it->second);
			++it;
		}
		mMapDeviceToPixelShader.clear();
		D3D9GpuProgram::unloadImpl();
    }
	//-----------------------------------------------------------------------------
	void D3D9GpuFragmentProgram::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device)
	{

	}

	//-----------------------------------------------------------------------------
	void D3D9GpuFragmentProgram::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device)
	{
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		DeviceToPixelShaderIterator it;

		// Find the shader of this device.
		it = mMapDeviceToPixelShader.find(d3d9Device);

		// Case shader found -> release it and erase from map.
		if (it != mMapDeviceToPixelShader.end())
		{
			SAFE_RELEASE(it->second);
			mMapDeviceToPixelShader.erase(it);
		}
	}

	//-----------------------------------------------------------------------------
	IDirect3DPixelShader9* D3D9GpuFragmentProgram::getPixelShader( void )
	{
		IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device();
		DeviceToPixelShaderIterator it;

		// Find the shader of this device.
		it = mMapDeviceToPixelShader.find(d3d9Device);

		// Shader was not found -> load it.
		if (it == mMapDeviceToPixelShader.end())
		{
			loadImpl(d3d9Device);
			it = mMapDeviceToPixelShader.find(d3d9Device);
		}

		return it->second;
	}
	//-----------------------------------------------------------------------------

}

<commit_msg>Fix GPU-extruded stencil shadows on Dx9 - Patch that introduced the option to use column-major matrices in r9363 had the default the wrong way around<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2009 Torus Knot Software Ltd

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

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

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

namespace Ogre {

    D3D9GpuProgram::CmdColumnMajorMatrices D3D9GpuProgram::msCmdColumnMajorMatrices;
	D3D9GpuProgram::CmdExternalMicrocode D3D9GpuProgram::msCmdExternalMicrocode;

   //-----------------------------------------------------------------------
    String D3D9GpuProgram::CmdColumnMajorMatrices::doGet(const void *target) const
    {
        return StringConverter::toString(static_cast<const D3D9GpuProgram*>(target)->getColumnMajorMatrices());
    }
    void D3D9GpuProgram::CmdColumnMajorMatrices::doSet(void *target, const String& val)
    {
        static_cast<D3D9GpuProgram*>(target)->setColumnMajorMatrices(StringConverter::parseBool(val));
    }
    //-----------------------------------------------------------------------
    String D3D9GpuProgram::CmdExternalMicrocode::doGet(const void *target) const
    {
		//D3D9GpuProgram* program=const_cast<D3D9GpuProgram*>(static_cast<const D3D9GpuProgram*>(target));
		//LPD3DXBUFFER ptr=program->getExternalMicrocode();
		//nothing to do
		return String();
    }
    void D3D9GpuProgram::CmdExternalMicrocode::doSet(void *target, const String& val)
    {
		D3D9GpuProgram* program = const_cast<D3D9GpuProgram*>(static_cast<const D3D9GpuProgram*>(target));
		const void* buffer = val.data();
		program->setExternalMicrocode(buffer, val.size());
    }

    //-----------------------------------------------------------------------------
    D3D9GpuProgram::D3D9GpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle,
        const String& group, bool isManual, ManualResourceLoader* loader)
        : GpuProgram(creator, name, handle, group, isManual, loader), mpExternalMicrocode(NULL), mColumnMajorMatrices(false)
    {
        if (createParamDictionary("D3D9GpuProgram"))
        {
            setupBaseParamDictionary();

            ParamDictionary* dict = getParamDictionary();
            dict->addParameter(ParameterDef("column_major_matrices",
                "Whether matrix packing in column-major order.",
                PT_BOOL),&msCmdColumnMajorMatrices);
			dict->addParameter(ParameterDef("external_micro_code",
				"the cached external micro code data.",
				PT_STRING),&msCmdExternalMicrocode);
        }
    }

	//-----------------------------------------------------------------------------
	D3D9GpuProgram::~D3D9GpuProgram()
	{

	}

	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::setExternalMicrocode(const void* pMicrocode, size_t size)
	{
		LPD3DXBUFFER pBuffer=0;
		HRESULT hr=D3DXCreateBuffer(size, &pBuffer);
		if(pBuffer)
		{
			memcpy(pBuffer->GetBufferPointer(), pMicrocode, size);
			this->setExternalMicrocode(pBuffer);
			SAFE_RELEASE(pBuffer);
		}
	}
	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::setExternalMicrocode(ID3DXBuffer* pMicrocode)
	{
		SAFE_RELEASE(mpExternalMicrocode);
		mpExternalMicrocode = pMicrocode;
		if(mpExternalMicrocode)
		{
			mpExternalMicrocode->AddRef();
		}
	}
    //-----------------------------------------------------------------------------
	LPD3DXBUFFER D3D9GpuProgram::getExternalMicrocode(void)
	{
		return mpExternalMicrocode;
	}

	//-----------------------------------------------------------------------------
    void D3D9GpuProgram::loadImpl(void)
    {
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		for (uint i = 0; i < D3D9RenderSystem::getResourceCreationDeviceCount(); ++i)
		{
			IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getResourceCreationDevice(i);

			loadImpl(d3d9Device);
		}
    }

	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::loadImpl(IDirect3DDevice9* d3d9Device)
	{
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		if (mpExternalMicrocode)
		{
			loadFromMicrocode(d3d9Device, mpExternalMicrocode);
		}
		else
		{
			// Normal load-from-source approach
			if (mLoadFromFile)
			{
				// find & load source code
				DataStreamPtr stream =
					ResourceGroupManager::getSingleton().openResource(
					mFilename, mGroup, true, this);
				mSource = stream->getAsString();
			}

			// Call polymorphic load
			loadFromSource(d3d9Device);
		}
	}
	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::unloadImpl(void)
	{
		SAFE_RELEASE(mpExternalMicrocode);
	}
	//-----------------------------------------------------------------------------
    void D3D9GpuProgram::loadFromSource(void)
    {
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		for (uint i = 0; i < D3D9RenderSystem::getResourceCreationDeviceCount(); ++i)
		{
			IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getResourceCreationDevice(i);

			loadFromSource(d3d9Device);
		}
    }

	//-----------------------------------------------------------------------------
	void D3D9GpuProgram::loadFromSource(IDirect3DDevice9* d3d9Device)
	{
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		// Populate compile flags
        DWORD compileFlags = 0;

		// Create the shader
		// Assemble source into microcode
		LPD3DXBUFFER microcode;
		LPD3DXBUFFER errors;
		HRESULT hr = D3DXAssembleShader(
			mSource.c_str(),
			static_cast<UINT>(mSource.length()),
			NULL,               // no #define support
			NULL,               // no #include support
			compileFlags,       // standard compile options
			&microcode,
			&errors);

		if (FAILED(hr))
		{
			String message = "Cannot assemble D3D9 shader " + mName + " Errors:\n" +
				static_cast<const char*>(errors->GetBufferPointer());
			errors->Release();
			OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, message,
				"D3D9GpuProgram::loadFromSource");
		}

		loadFromMicrocode(d3d9Device, microcode);

		SAFE_RELEASE(microcode);
		SAFE_RELEASE(errors);
	}
    //-----------------------------------------------------------------------
    GpuProgramParametersSharedPtr D3D9GpuProgram::createParameters(void)
    {
        // Call superclass
        GpuProgramParametersSharedPtr params = GpuProgram::createParameters();

        // Need to transpose matrices if compiled with column-major matrices
        params->setTransposeMatrices(mColumnMajorMatrices);

        return params;
    }
	//-----------------------------------------------------------------------------
    D3D9GpuVertexProgram::D3D9GpuVertexProgram(ResourceManager* creator,
        const String& name, ResourceHandle handle, const String& group,
        bool isManual, ManualResourceLoader* loader)
        : D3D9GpuProgram(creator, name, handle, group, isManual, loader)
    {
        mType = GPT_VERTEX_PROGRAM;
    }
	//-----------------------------------------------------------------------------
	D3D9GpuVertexProgram::~D3D9GpuVertexProgram()
	{
		// have to call this here reather than in Resource destructor
		// since calling virtual methods in base destructors causes crash
		unload();
	}
	//-----------------------------------------------------------------------------
    void D3D9GpuVertexProgram::loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode)
    {
		DeviceToVertexShaderIterator it = mMapDeviceToVertexShader.find(d3d9Device);

		if (it != mMapDeviceToVertexShader.end())
			SAFE_RELEASE(it->second);

		if (isSupported())
		{
			// Create the shader
			IDirect3DVertexShader9* pVertexShader;
			HRESULT hr;

			hr = d3d9Device->CreateVertexShader(
				static_cast<DWORD*>(microcode->GetBufferPointer()),
				&pVertexShader);

			if (FAILED(hr))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
					"Cannot create D3D9 vertex shader " + mName + " from microcode",
					"D3D9GpuVertexProgram::loadFromMicrocode");

			}

			mMapDeviceToVertexShader[d3d9Device] = pVertexShader;
		}
		else
		{
			LogManager::getSingleton().logMessage(
				"Unsupported D3D9 vertex shader '" + mName + "' was not loaded.");

			mMapDeviceToVertexShader[d3d9Device] = NULL;
		}
    }
	//-----------------------------------------------------------------------------
    void D3D9GpuVertexProgram::unloadImpl(void)
    {
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

        DeviceToVertexShaderIterator it = mMapDeviceToVertexShader.begin();

		while (it != mMapDeviceToVertexShader.end())
		{
			SAFE_RELEASE(it->second);
			++it;
		}
		mMapDeviceToVertexShader.clear();
		D3D9GpuProgram::unloadImpl();
    }

	//-----------------------------------------------------------------------------
	void D3D9GpuVertexProgram::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device)
	{

	}

	//-----------------------------------------------------------------------------
	void D3D9GpuVertexProgram::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device)
	{
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		DeviceToVertexShaderIterator it;

		// Find the shader of this device.
		it = mMapDeviceToVertexShader.find(d3d9Device);

		// Case shader found -> release it and erase from map.
		if (it != mMapDeviceToVertexShader.end())
		{
			SAFE_RELEASE(it->second);
			mMapDeviceToVertexShader.erase(it);
		}
	}

	//-----------------------------------------------------------------------------
	IDirect3DVertexShader9* D3D9GpuVertexProgram::getVertexShader( void )
	{
		IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device();
		DeviceToVertexShaderIterator it;

		// Find the shader of this device.
		it = mMapDeviceToVertexShader.find(d3d9Device);

		// Shader was not found -> load it.
		if (it == mMapDeviceToVertexShader.end())
		{
			loadImpl(d3d9Device);
			it = mMapDeviceToVertexShader.find(d3d9Device);
		}

		return it->second;
	}

	//-----------------------------------------------------------------------------
	//-----------------------------------------------------------------------------
    D3D9GpuFragmentProgram::D3D9GpuFragmentProgram(ResourceManager* creator,
        const String& name, ResourceHandle handle, const String& group,
        bool isManual, ManualResourceLoader* loader)
        : D3D9GpuProgram(creator, name, handle, group, isManual, loader)
    {
        mType = GPT_FRAGMENT_PROGRAM;
    }
	//-----------------------------------------------------------------------------
	D3D9GpuFragmentProgram::~D3D9GpuFragmentProgram()
	{
		// have to call this here reather than in Resource destructor
		// since calling virtual methods in base destructors causes crash
		unload();
	}
	//-----------------------------------------------------------------------------
    void D3D9GpuFragmentProgram::loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode)
    {
		DeviceToPixelShaderIterator it = mMapDeviceToPixelShader.find(d3d9Device);

		if (it != mMapDeviceToPixelShader.end())
			SAFE_RELEASE(it->second);

		if (isSupported())
		{
			// Create the shader
			IDirect3DPixelShader9* pPixelShader;
			HRESULT hr;

			hr = d3d9Device->CreatePixelShader(
				static_cast<DWORD*>(microcode->GetBufferPointer()),
				&pPixelShader);

			if (FAILED(hr))
			{
				OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
					"Cannot create D3D9 pixel shader " + mName + " from microcode.",
					"D3D9GpuFragmentProgram::loadFromMicrocode");

			}

			mMapDeviceToPixelShader[d3d9Device] = pPixelShader;
		}
		else
		{
			LogManager::getSingleton().logMessage(
				"Unsupported D3D9 pixel shader '" + mName + "' was not loaded.");

			mMapDeviceToPixelShader[d3d9Device] = NULL;
		}
    }
	//-----------------------------------------------------------------------------
    void D3D9GpuFragmentProgram::unloadImpl(void)
    {
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		DeviceToPixelShaderIterator it = mMapDeviceToPixelShader.begin();

		while (it != mMapDeviceToPixelShader.end())
		{
			SAFE_RELEASE(it->second);
			++it;
		}
		mMapDeviceToPixelShader.clear();
		D3D9GpuProgram::unloadImpl();
    }
	//-----------------------------------------------------------------------------
	void D3D9GpuFragmentProgram::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device)
	{

	}

	//-----------------------------------------------------------------------------
	void D3D9GpuFragmentProgram::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device)
	{
		D3D9_DEVICE_ACCESS_CRITICAL_SECTION

		DeviceToPixelShaderIterator it;

		// Find the shader of this device.
		it = mMapDeviceToPixelShader.find(d3d9Device);

		// Case shader found -> release it and erase from map.
		if (it != mMapDeviceToPixelShader.end())
		{
			SAFE_RELEASE(it->second);
			mMapDeviceToPixelShader.erase(it);
		}
	}

	//-----------------------------------------------------------------------------
	IDirect3DPixelShader9* D3D9GpuFragmentProgram::getPixelShader( void )
	{
		IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device();
		DeviceToPixelShaderIterator it;

		// Find the shader of this device.
		it = mMapDeviceToPixelShader.find(d3d9Device);

		// Shader was not found -> load it.
		if (it == mMapDeviceToPixelShader.end())
		{
			loadImpl(d3d9Device);
			it = mMapDeviceToPixelShader.find(d3d9Device);
		}

		return it->second;
	}
	//-----------------------------------------------------------------------------

}

<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkAAClip.h"

namespace skiagm {

static void paint_rgn(SkCanvas* canvas, const SkAAClip& clip,
                      const SkPaint& paint) {
    SkMask mask;
    SkBitmap bm;

    clip.copyToMask(&mask);

    SkAutoMaskFreeImage amfi(mask.fImage);

    bm.setConfig(SkBitmap::kA8_Config, mask.fBounds.width(),
                 mask.fBounds.height(), mask.fRowBytes);
    bm.setPixels(mask.fImage);

    // need to copy for deferred drawing test to work
    SkBitmap bm2;

    bm.deepCopyTo(&bm2, SkBitmap::kA8_Config);

    canvas->drawBitmap(bm2,
                       SK_Scalar1 * mask.fBounds.fLeft,
                       SK_Scalar1 * mask.fBounds.fTop,
                       &paint);
}

//////////////////////////////////////////////////////////////////////////////
/*
 * This GM tests anti aliased single operation booleans with SkAAClips,
 * SkRect and SkPaths.
 */
class SimpleClipGM : public GM {
public:
    enum SkGeomTypes {
        kRect_GeomType,
        kPath_GeomType,
        kAAClip_GeomType
    };

    SimpleClipGM(SkGeomTypes geomType)
    : fGeomType(geomType) {

        // offset the rects a bit so we get anti-aliasing in the rect case
        fBase.set(SkFloatToScalar(100.5f),
                  SkFloatToScalar(100.5f),
                  SkFloatToScalar(150.5f),
                  SkFloatToScalar(150.5f));
        fRect = fBase;
        fRect.inset(5, 5);
        fRect.offset(25, 25);

        fBasePath.addRoundRect(fBase, SkIntToScalar(5), SkIntToScalar(5));
        fRectPath.addRoundRect(fRect, SkIntToScalar(5), SkIntToScalar(5));
        INHERITED::setBGColor(0xFFDDDDDD);
    }

protected:
    void buildRgn(SkAAClip* clip, SkRegion::Op op) {
        clip->setPath(fBasePath, NULL, true);

        SkAAClip clip2;
        clip2.setPath(fRectPath, NULL, true);
        clip->op(clip2, op);
    }

    void drawOrig(SkCanvas* canvas) {
        SkPaint     paint;

        paint.setStyle(SkPaint::kStroke_Style);
        paint.setColor(SK_ColorBLACK);

        canvas->drawRect(fBase, paint);
        canvas->drawRect(fRect, paint);
    }

    void drawRgnOped(SkCanvas* canvas, SkRegion::Op op, SkColor color) {

        SkAAClip clip;

        this->buildRgn(&clip, op);
        this->drawOrig(canvas);

        SkPaint paint;
        paint.setColor(color);
        paint_rgn(canvas, clip, paint);
    }

    void drawPathsOped(SkCanvas* canvas, SkRegion::Op op, SkColor color) {

        this->drawOrig(canvas);

        canvas->save();

        // create the clip mask with the supplied boolean op
        if (kPath_GeomType == fGeomType) {
            // path-based case
            canvas->clipPath(fBasePath, SkRegion::kReplace_Op, true);
            canvas->clipPath(fRectPath, op, true);
        } else {
            // rect-based case
            canvas->clipRect(fBase, SkRegion::kReplace_Op, true);
            canvas->clipRect(fRect, op, true);
        }

        // draw a rect that will entirely cover the clip mask area
        SkPaint paint;
        paint.setColor(color);

        SkRect r = SkRect::MakeLTRB(SkIntToScalar(90),  SkIntToScalar(90),
                                    SkIntToScalar(180), SkIntToScalar(180));

        canvas->drawRect(r, paint);

        canvas->restore();
    }

    virtual SkString onShortName() {
        SkString str;
        str.printf("simpleaaclip_%s",
                    kRect_GeomType == fGeomType ? "rect" :
                    (kPath_GeomType == fGeomType ? "path" :
                    "aaclip"));
        return str;
    }

    virtual SkISize onISize() {
        return make_isize(640, 480);
    }

    virtual void onDraw(SkCanvas* canvas) {

        static const struct {
            SkColor         fColor;
            const char*     fName;
            SkRegion::Op    fOp;
        } gOps[] = {
            { SK_ColorBLACK,    "Difference", SkRegion::kDifference_Op    },
            { SK_ColorRED,      "Intersect",  SkRegion::kIntersect_Op     },
            { 0xFF008800,       "Union",      SkRegion::kUnion_Op         },
            { SK_ColorBLUE,     "XOR",        SkRegion::kXOR_Op           },
            { SK_ColorGREEN,    "Rev Diff",   SkRegion::kReverseDifference_Op },
            { SK_ColorYELLOW,   "Replace",    SkRegion::kReplace_Op       }
        };

        SkPaint textPaint;
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(SK_Scalar1*24);

        for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); op++) {
            canvas->drawText(gOps[op].fName, strlen(gOps[op].fName),
                             SkIntToScalar(75), SkIntToScalar(50),
                             textPaint);

            if (kAAClip_GeomType == fGeomType) {
                this->drawRgnOped(canvas, gOps[op].fOp, gOps[op].fColor);
            } else {
                this->drawPathsOped(canvas, gOps[op].fOp, gOps[op].fColor);
            }

            if (op && !(op % 3)) {
                canvas->translate(SkIntToScalar(-600), SkIntToScalar(250));
            } else {
                canvas->translate(SkIntToScalar(200), 0);
            }
        }
    }
private:

    SkGeomTypes fGeomType;

    SkRect fBase;
    SkRect fRect;

    SkPath fBasePath;       // fBase as a round rect
    SkPath fRectPath;       // fRect as a round rect

    typedef GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

// rects
static GM* MyFactory(void*) { return new SimpleClipGM(
                                            SimpleClipGM::kRect_GeomType); }
static GMRegistry reg(MyFactory);

// paths
static GM* MyFactory2(void*) { return new SimpleClipGM(
                                            SimpleClipGM::kPath_GeomType); }
static GMRegistry reg2(MyFactory2);

// aa clip
static GM* MyFactory3(void*) { return new SimpleClipGM(
                                            SimpleClipGM::kAAClip_GeomType); }
static GMRegistry reg3(MyFactory3);

}
<commit_msg>Fixed simpleaaclip gm - it wasn't showing xor case<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkAAClip.h"

namespace skiagm {

static void paint_rgn(SkCanvas* canvas, const SkAAClip& clip,
                      const SkPaint& paint) {
    SkMask mask;
    SkBitmap bm;

    clip.copyToMask(&mask);

    SkAutoMaskFreeImage amfi(mask.fImage);

    bm.setConfig(SkBitmap::kA8_Config, mask.fBounds.width(),
                 mask.fBounds.height(), mask.fRowBytes);
    bm.setPixels(mask.fImage);

    // need to copy for deferred drawing test to work
    SkBitmap bm2;

    bm.deepCopyTo(&bm2, SkBitmap::kA8_Config);

    canvas->drawBitmap(bm2,
                       SK_Scalar1 * mask.fBounds.fLeft,
                       SK_Scalar1 * mask.fBounds.fTop,
                       &paint);
}

//////////////////////////////////////////////////////////////////////////////
/*
 * This GM tests anti aliased single operation booleans with SkAAClips,
 * SkRect and SkPaths.
 */
class SimpleClipGM : public GM {
public:
    enum SkGeomTypes {
        kRect_GeomType,
        kPath_GeomType,
        kAAClip_GeomType
    };

    SimpleClipGM(SkGeomTypes geomType)
    : fGeomType(geomType) {

        // offset the rects a bit so we get anti-aliasing in the rect case
        fBase.set(SkFloatToScalar(100.5f),
                  SkFloatToScalar(100.5f),
                  SkFloatToScalar(150.5f),
                  SkFloatToScalar(150.5f));
        fRect = fBase;
        fRect.inset(5, 5);
        fRect.offset(25, 25);

        fBasePath.addRoundRect(fBase, SkIntToScalar(5), SkIntToScalar(5));
        fRectPath.addRoundRect(fRect, SkIntToScalar(5), SkIntToScalar(5));
        INHERITED::setBGColor(0xFFDDDDDD);
    }

protected:
    void buildRgn(SkAAClip* clip, SkRegion::Op op) {
        clip->setPath(fBasePath, NULL, true);

        SkAAClip clip2;
        clip2.setPath(fRectPath, NULL, true);
        clip->op(clip2, op);
    }

    void drawOrig(SkCanvas* canvas) {
        SkPaint     paint;

        paint.setStyle(SkPaint::kStroke_Style);
        paint.setColor(SK_ColorBLACK);

        canvas->drawRect(fBase, paint);
        canvas->drawRect(fRect, paint);
    }

    void drawRgnOped(SkCanvas* canvas, SkRegion::Op op, SkColor color) {

        SkAAClip clip;

        this->buildRgn(&clip, op);
        this->drawOrig(canvas);

        SkPaint paint;
        paint.setColor(color);
        paint_rgn(canvas, clip, paint);
    }

    void drawPathsOped(SkCanvas* canvas, SkRegion::Op op, SkColor color) {

        this->drawOrig(canvas);

        canvas->save();

        // create the clip mask with the supplied boolean op
        if (kPath_GeomType == fGeomType) {
            // path-based case
            canvas->clipPath(fBasePath, SkRegion::kReplace_Op, true);
            canvas->clipPath(fRectPath, op, true);
        } else {
            // rect-based case
            canvas->clipRect(fBase, SkRegion::kReplace_Op, true);
            canvas->clipRect(fRect, op, true);
        }

        // draw a rect that will entirely cover the clip mask area
        SkPaint paint;
        paint.setColor(color);

        SkRect r = SkRect::MakeLTRB(SkIntToScalar(90),  SkIntToScalar(90),
                                    SkIntToScalar(180), SkIntToScalar(180));

        canvas->drawRect(r, paint);

        canvas->restore();
    }

    virtual SkString onShortName() {
        SkString str;
        str.printf("simpleaaclip_%s",
                    kRect_GeomType == fGeomType ? "rect" :
                    (kPath_GeomType == fGeomType ? "path" :
                    "aaclip"));
        return str;
    }

    virtual SkISize onISize() {
        return make_isize(640, 480);
    }

    virtual void onDraw(SkCanvas* canvas) {

        static const struct {
            SkColor         fColor;
            const char*     fName;
            SkRegion::Op    fOp;
        } gOps[] = {
            { SK_ColorBLACK,    "Difference", SkRegion::kDifference_Op    },
            { SK_ColorRED,      "Intersect",  SkRegion::kIntersect_Op     },
            { 0xFF008800,       "Union",      SkRegion::kUnion_Op         },
            { SK_ColorGREEN,    "Rev Diff",   SkRegion::kReverseDifference_Op },
            { SK_ColorYELLOW,   "Replace",    SkRegion::kReplace_Op       },
            { SK_ColorBLUE,     "XOR",        SkRegion::kXOR_Op           },
        };

        SkPaint textPaint;
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(SK_Scalar1*24);
        int xOff = 0;

        for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); op++) {
            canvas->drawText(gOps[op].fName, strlen(gOps[op].fName),
                             SkIntToScalar(75), SkIntToScalar(50),
                             textPaint);

            if (kAAClip_GeomType == fGeomType) {
                this->drawRgnOped(canvas, gOps[op].fOp, gOps[op].fColor);
            } else {
                this->drawPathsOped(canvas, gOps[op].fOp, gOps[op].fColor);
            }

            if (xOff >= 400) {
                canvas->translate(SkIntToScalar(-400), SkIntToScalar(250));
                xOff = 0;
            } else {
                canvas->translate(SkIntToScalar(200), 0);
                xOff += 200;
            }
        }
    }
private:

    SkGeomTypes fGeomType;

    SkRect fBase;
    SkRect fRect;

    SkPath fBasePath;       // fBase as a round rect
    SkPath fRectPath;       // fRect as a round rect

    typedef GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

// rects
static GM* MyFactory(void*) { return new SimpleClipGM(
                                            SimpleClipGM::kRect_GeomType); }
static GMRegistry reg(MyFactory);

// paths
static GM* MyFactory2(void*) { return new SimpleClipGM(
                                            SimpleClipGM::kPath_GeomType); }
static GMRegistry reg2(MyFactory2);

// aa clip
static GM* MyFactory3(void*) { return new SimpleClipGM(
                                            SimpleClipGM::kAAClip_GeomType); }
static GMRegistry reg3(MyFactory3);

}
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "HTMLOListElementImp.h"

namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

void HTMLOListElementImp::eval()
{
    Nullable<std::u16string> attr = getAttribute(u"start");
    if (attr.hasValue()) {
        getStyle().setProperty(u"counter-reset", u"list-item " + attr.value(), u"non-css");
        getStyle().setProperty(u"counter-increment", u"list-item -1");
    }
}

bool HTMLOListElementImp::getReversed()
{
    // TODO: implement me!
    return 0;
}

void HTMLOListElementImp::setReversed(bool reversed)
{
    // TODO: implement me!
}

int HTMLOListElementImp::getStart()
{
    // TODO: implement me!
    return 0;
}

void HTMLOListElementImp::setStart(int start)
{
    // TODO: implement me!
}

bool HTMLOListElementImp::getCompact()
{
    // TODO: implement me!
    return 0;
}

void HTMLOListElementImp::setCompact(bool compact)
{
    // TODO: implement me!
}

std::u16string HTMLOListElementImp::getType()
{
    // TODO: implement me!
    return u"";
}

void HTMLOListElementImp::setType(std::u16string type)
{
    // TODO: implement me!
}

}
}
}
}
<commit_msg>(HTMLOListElementImp::eval) : Fix a bug<commit_after>/*
 * Copyright 2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "HTMLOListElementImp.h"

namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

void HTMLOListElementImp::eval()
{
    HTMLElementImp::eval();
    Nullable<std::u16string> attr = getAttribute(u"start");
    if (attr.hasValue()) {
        getStyle().setProperty(u"counter-reset", u"list-item " + attr.value(), u"non-css");
        getStyle().setProperty(u"counter-increment", u"list-item -1");
    }
}

bool HTMLOListElementImp::getReversed()
{
    // TODO: implement me!
    return 0;
}

void HTMLOListElementImp::setReversed(bool reversed)
{
    // TODO: implement me!
}

int HTMLOListElementImp::getStart()
{
    // TODO: implement me!
    return 0;
}

void HTMLOListElementImp::setStart(int start)
{
    // TODO: implement me!
}

bool HTMLOListElementImp::getCompact()
{
    // TODO: implement me!
    return 0;
}

void HTMLOListElementImp::setCompact(bool compact)
{
    // TODO: implement me!
}

std::u16string HTMLOListElementImp::getType()
{
    // TODO: implement me!
    return u"";
}

void HTMLOListElementImp::setType(std::u16string type)
{
    // TODO: implement me!
}

}
}
}
}
<|endoftext|>


<commit_before><commit_msg>Have gatherers take their own collision size and the collision size of their target resource source into account when checking their gather range.<commit_after><|endoftext|>


<commit_before>/**
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <memory>
#include <string>
#include <vector>
#include <set>
#include <fstream>
#include <functional>

#include "TestBase.h"
#include "processors/PutFile.h"
#include "utils/file/FileUtils.h"
#include "utils/TestUtils.h"
#include "PerformanceDataMonitor.h"
#include "rapidjson/filereadstream.h"

using org::apache::nifi::minifi::processors::PutFile;
using org::apache::nifi::minifi::processors::PerformanceDataMonitor;
using org::apache::nifi::minifi::processors::PerformanceDataCounter;

class PerformanceDataMonitorTester {
 public:
  PerformanceDataMonitorTester() {
    LogTestController::getInstance().setTrace<TestPlan>();
    dir_ = utils::createTempDir(&test_controller_);
    plan_ = test_controller_.createPlan();
    performance_monitor_ = plan_->addProcessor("PerformanceDataMonitor", "pdhsys");
    putfile_ = plan_->addProcessor("PutFile", "putfile", core::Relationship("success", "description"), true);
    plan_->setProperty(putfile_, PutFile::Directory.getName(), dir_);
  }

  bool runWithRetries(std::function<bool()>&& assertions, uint32_t max_tries = 10) {
    uint32_t tries = 0;
    for (uint32_t tries = 0; tries < max_tries; ++tries) {
      test_controller_.runSession(plan_);
      if (assertions()) {
        return true;
      }
      plan_->reset();
      LogTestController::getInstance().reset();
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    return false;
  }

  void setPerformanceMonitorProperty(const core::Property& property, const std::string& value) {
    plan_->setProperty(performance_monitor_, property.getName(), value);
  }

  TestController test_controller_;
  std::string dir_;
  std::shared_ptr<TestPlan> plan_;
  std::shared_ptr<core::Processor> performance_monitor_;
  std::shared_ptr<core::Processor> putfile_;
};

TEST_CASE("PerformanceDataMonitorEmptyPropertiesTest", "[performancedatamonitoremptypropertiestest]") {
  PerformanceDataMonitorTester tester;
  tester.test_controller_.runSession(tester.plan_);
  REQUIRE(tester.test_controller_.getLog().getInstance().contains("No valid counters for PerformanceDataMonitor", std::chrono::seconds(0)));

  auto created_flow_files = utils::file::FileUtils::list_dir_all(tester.dir_, tester.plan_->getLogger(), false);
  REQUIRE(created_flow_files.size() == 0);
}

TEST_CASE("PerformanceDataMonitorPartiallyInvalidGroupPropertyTest", "[performancedatamonitorpartiallyinvalidgrouppropertytest]") {
  PerformanceDataMonitorTester tester;
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::PredefinedGroups, "Disk,CPU,Asd");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::CustomPDHCounters, "\\Invalid\\Counter,\\System\\Processes");
  const auto assertions = [&tester]() {
    REQUIRE(tester.test_controller_.getLog().getInstance().contains("Asd is not a valid predefined group", std::chrono::seconds(0)));
    REQUIRE(tester.test_controller_.getLog().getInstance().contains("Error adding \\Invalid\\Counter to query", std::chrono::seconds(0)));

    bool ff_contains_all_data = false;

    const auto lambda = [&ff_contains_all_data](const std::string& path, const std::string& filename) -> bool {
      FILE* fp = fopen((path + utils::file::FileUtils::get_separator() + filename).c_str(), "r");
      REQUIRE(fp != nullptr);
      char readBuffer[500];
      rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
      rapidjson::Document document;
      document.ParseStream(is);
      fclose(fp);
      ff_contains_all_data =
        document.IsObject() &&
        document.HasMember("LogicalDisk") &&
        document["LogicalDisk"].HasMember("_Total") &&
        document["LogicalDisk"]["_Total"].HasMember("Free Megabytes") &&
        document["System"].HasMember("Processes");
      return !ff_contains_all_data;
    };

    utils::file::FileUtils::list_dir(tester.dir_, lambda, tester.plan_->getLogger(), false);
    return ff_contains_all_data;
  };
  REQUIRE(tester.runWithRetries(assertions));
}

TEST_CASE("PerformanceDataMonitorCustomPDHCountersTest", "[performancedatamonitorcustompdhcounterstest]") {
  PerformanceDataMonitorTester tester;
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::CustomPDHCounters, "\\System\\Processes,\\Process(*)\\% Processor Time");

  const auto assertions = [&tester]() {
    bool ff_contains_all_data = false;
    const auto lambda = [&ff_contains_all_data](const std::string& path, const std::string& filename) -> bool {
      FILE* fp = fopen((path + utils::file::FileUtils::get_separator() + filename).c_str(), "r");
      REQUIRE(fp != nullptr);
      char readBuffer[50000];
      rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
      rapidjson::Document document;
      document.ParseStream(is);
      fclose(fp);
      ff_contains_all_data =
        document.IsObject() &&
        document.HasMember("System") &&
        document["System"].HasMember("Processes") &&
        document.HasMember("Process") &&
        document["Process"].HasMember("PerformanceDataMonitorTests") &&
        document["Process"]["PerformanceDataMonitorTests"].HasMember("% Processor Time");
      return !ff_contains_all_data;
    };

    utils::file::FileUtils::list_dir(tester.dir_, lambda, tester.plan_->getLogger(), false);
    return ff_contains_all_data;
  };

  REQUIRE(tester.runWithRetries(assertions));
}

TEST_CASE("PerformanceDataMonitorCustomPDHCountersTestOpenTelemetry", "[performancedatamonitorcustompdhcounterstestopentelemetry]") {
  PerformanceDataMonitorTester tester;
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::PredefinedGroups, "Disk");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::CustomPDHCounters, "\\System\\Processes,\\Process(*)\\ID Process,\\Process(*)\\Private Bytes");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::OutputFormatProperty, "OpenTelemetry");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::OutputCompactness, "Compact");

  const auto assertions = [&tester]() {
    bool ff_contains_all_data = false;
    const auto lambda = [&ff_contains_all_data](const std::string& path, const std::string& filename) -> bool {
      FILE* fp = fopen((path + utils::file::FileUtils::get_separator() + filename).c_str(), "r");
      REQUIRE(fp != nullptr);
      char readBuffer[50000];
      rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
      rapidjson::Document document;
      document.ParseStream(is);
      fclose(fp);
      ff_contains_all_data =
        document.IsObject() &&
        document.HasMember("Name") &&
        document.HasMember("Timestamp") &&
        document.HasMember("Body") &&
        document["Body"].HasMember("System") &&
        document["Body"]["System"].HasMember("Processes") &&
        document["Body"].HasMember("Process") &&
        document["Body"]["Process"].HasMember("PerformanceDataMonitorTests") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("ID Process");
      return !ff_contains_all_data;
    };

    utils::file::FileUtils::list_dir(tester.dir_, lambda, tester.plan_->getLogger(), false);
    return ff_contains_all_data;
  };

  REQUIRE(tester.runWithRetries(assertions));
}

TEST_CASE("PerformanceDataMonitorAllPredefinedGroups", "[performancedatamonitorallpredefinedgroups]") {
  PerformanceDataMonitorTester tester;
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::PredefinedGroups, "CPU,Disk,Network,Memory,IO,System,Process");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::OutputFormatProperty, "OpenTelemetry");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::OutputCompactness, "Pretty");

  const auto assertions = [&tester]() {
    bool ff_contains_all_data = false;
    const auto lambda = [&ff_contains_all_data](const std::string& path, const std::string& filename) -> bool {
      FILE* fp = fopen((path + utils::file::FileUtils::get_separator() + filename).c_str(), "r");
      REQUIRE(fp != nullptr);
      char readBuffer[50000];
      rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
      rapidjson::Document document;
      document.ParseStream(is);
      fclose(fp);
      ff_contains_all_data =
        document.IsObject() &&
        document.HasMember("Name") &&
        document.HasMember("Timestamp") &&
        document.HasMember("Body") &&
        document["Body"].HasMember("PhysicalDisk") &&
        document["Body"]["PhysicalDisk"].HasMember("_Total") &&
        document["Body"]["PhysicalDisk"]["_Total"].HasMember("% Disk Read Time") &&
        document["Body"]["PhysicalDisk"]["_Total"].HasMember("% Disk Time") &&
        document["Body"]["PhysicalDisk"]["_Total"].HasMember("% Disk Write Time") &&
        document["Body"]["PhysicalDisk"]["_Total"].HasMember("% Idle Time") &&

        document["Body"].HasMember("LogicalDisk") &&
        document["Body"]["LogicalDisk"].HasMember("_Total") &&
        document["Body"]["LogicalDisk"]["_Total"].HasMember("Free Megabytes") &&
        document["Body"]["LogicalDisk"]["_Total"].HasMember("% Free Space") &&

        document["Body"].HasMember("Processor") &&
        document["Body"]["Processor"].HasMember("_Total") &&

        document["Body"].HasMember("Network Interface") &&

        document["Body"].HasMember("Memory") &&
        document["Body"]["Memory"].HasMember("% Committed Bytes In Use") &&
        document["Body"]["Memory"].HasMember("Available MBytes") &&
        document["Body"]["Memory"].HasMember("Page Faults/sec") &&
        document["Body"]["Memory"].HasMember("Pages/sec") &&

        document["Body"].HasMember("System") &&
        document["Body"]["System"].HasMember("% Registry Quota In Use") &&
        document["Body"]["System"].HasMember("Context Switches/sec") &&
        document["Body"]["System"].HasMember("File Control Bytes/sec") &&
        document["Body"]["System"].HasMember("File Control Operations/sec") &&

        document["Body"].HasMember("Process") &&
        document["Body"]["Process"].HasMember("PerformanceDataMonitorTests") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("% Processor Time") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("Elapsed Time") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("ID Process") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("Private Bytes");
      return !ff_contains_all_data;
    };

    utils::file::FileUtils::list_dir(tester.dir_, lambda, tester.plan_->getLogger(), false);
    return ff_contains_all_data;
  };

  REQUIRE(tester.runWithRetries(assertions));
}

TEST_CASE("PerformanceDataMonitorDecimalPlacesPropertyTest", "[performancedatamonitordecimalplacespropertytest]") {
  {
    PerformanceDataMonitorTester tester;
    tester.setPerformanceMonitorProperty(PerformanceDataMonitor::DecimalPlaces, "asd");
    REQUIRE_THROWS_WITH(tester.runProcessors(), "General Operation: Invalid conversion to int64_t for asd");
  }
  {
    PerformanceDataMonitorTester tester;
    tester.setPerformanceMonitorProperty(PerformanceDataMonitor::DecimalPlaces, "1234586123");
    REQUIRE_THROWS_WITH(tester.runProcessors(), "Process Schedule Operation: PerformanceDataMonitor Decimal Places is out of range");
  }
  {
    PerformanceDataMonitorTester tester;
    tester.setPerformanceMonitorProperty(PerformanceDataMonitor::DecimalPlaces, "");
    REQUIRE_NOTHROW(tester.runProcessors());
  }
}
<commit_msg>MINIFICPP-1583 windows build fix<commit_after>/**
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <memory>
#include <string>
#include <vector>
#include <set>
#include <fstream>
#include <functional>

#include "TestBase.h"
#include "processors/PutFile.h"
#include "utils/file/FileUtils.h"
#include "utils/TestUtils.h"
#include "PerformanceDataMonitor.h"
#include "rapidjson/filereadstream.h"

using org::apache::nifi::minifi::processors::PutFile;
using org::apache::nifi::minifi::processors::PerformanceDataMonitor;
using org::apache::nifi::minifi::processors::PerformanceDataCounter;

class PerformanceDataMonitorTester {
 public:
  PerformanceDataMonitorTester() {
    LogTestController::getInstance().setTrace<TestPlan>();
    dir_ = utils::createTempDir(&test_controller_);
    plan_ = test_controller_.createPlan();
    performance_monitor_ = plan_->addProcessor("PerformanceDataMonitor", "pdhsys");
    putfile_ = plan_->addProcessor("PutFile", "putfile", core::Relationship("success", "description"), true);
    plan_->setProperty(putfile_, PutFile::Directory.getName(), dir_);
  }

  bool runWithRetries(std::function<bool()>&& assertions, uint32_t max_tries = 10) {
    uint32_t tries = 0;
    for (uint32_t tries = 0; tries < max_tries; ++tries) {
      test_controller_.runSession(plan_);
      if (assertions()) {
        return true;
      }
      plan_->reset();
      LogTestController::getInstance().reset();
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    return false;
  }

  void setPerformanceMonitorProperty(const core::Property& property, const std::string& value) {
    plan_->setProperty(performance_monitor_, property.getName(), value);
  }

  TestController test_controller_;
  std::string dir_;
  std::shared_ptr<TestPlan> plan_;
  std::shared_ptr<core::Processor> performance_monitor_;
  std::shared_ptr<core::Processor> putfile_;
};

TEST_CASE("PerformanceDataMonitorEmptyPropertiesTest", "[performancedatamonitoremptypropertiestest]") {
  PerformanceDataMonitorTester tester;
  tester.test_controller_.runSession(tester.plan_);
  REQUIRE(tester.test_controller_.getLog().getInstance().contains("No valid counters for PerformanceDataMonitor", std::chrono::seconds(0)));

  auto created_flow_files = utils::file::FileUtils::list_dir_all(tester.dir_, tester.plan_->getLogger(), false);
  REQUIRE(created_flow_files.size() == 0);
}

TEST_CASE("PerformanceDataMonitorPartiallyInvalidGroupPropertyTest", "[performancedatamonitorpartiallyinvalidgrouppropertytest]") {
  PerformanceDataMonitorTester tester;
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::PredefinedGroups, "Disk,CPU,Asd");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::CustomPDHCounters, "\\Invalid\\Counter,\\System\\Processes");
  const auto assertions = [&tester]() {
    REQUIRE(tester.test_controller_.getLog().getInstance().contains("Asd is not a valid predefined group", std::chrono::seconds(0)));
    REQUIRE(tester.test_controller_.getLog().getInstance().contains("Error adding \\Invalid\\Counter to query", std::chrono::seconds(0)));

    bool ff_contains_all_data = false;

    const auto lambda = [&ff_contains_all_data](const std::string& path, const std::string& filename) -> bool {
      FILE* fp = fopen((path + utils::file::FileUtils::get_separator() + filename).c_str(), "r");
      REQUIRE(fp != nullptr);
      char readBuffer[500];
      rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
      rapidjson::Document document;
      document.ParseStream(is);
      fclose(fp);
      ff_contains_all_data =
        document.IsObject() &&
        document.HasMember("LogicalDisk") &&
        document["LogicalDisk"].HasMember("_Total") &&
        document["LogicalDisk"]["_Total"].HasMember("Free Megabytes") &&
        document["System"].HasMember("Processes");
      return !ff_contains_all_data;
    };

    utils::file::FileUtils::list_dir(tester.dir_, lambda, tester.plan_->getLogger(), false);
    return ff_contains_all_data;
  };
  REQUIRE(tester.runWithRetries(assertions));
}

TEST_CASE("PerformanceDataMonitorCustomPDHCountersTest", "[performancedatamonitorcustompdhcounterstest]") {
  PerformanceDataMonitorTester tester;
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::CustomPDHCounters, "\\System\\Processes,\\Process(*)\\% Processor Time");

  const auto assertions = [&tester]() {
    bool ff_contains_all_data = false;
    const auto lambda = [&ff_contains_all_data](const std::string& path, const std::string& filename) -> bool {
      FILE* fp = fopen((path + utils::file::FileUtils::get_separator() + filename).c_str(), "r");
      REQUIRE(fp != nullptr);
      char readBuffer[50000];
      rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
      rapidjson::Document document;
      document.ParseStream(is);
      fclose(fp);
      ff_contains_all_data =
        document.IsObject() &&
        document.HasMember("System") &&
        document["System"].HasMember("Processes") &&
        document.HasMember("Process") &&
        document["Process"].HasMember("PerformanceDataMonitorTests") &&
        document["Process"]["PerformanceDataMonitorTests"].HasMember("% Processor Time");
      return !ff_contains_all_data;
    };

    utils::file::FileUtils::list_dir(tester.dir_, lambda, tester.plan_->getLogger(), false);
    return ff_contains_all_data;
  };

  REQUIRE(tester.runWithRetries(assertions));
}

TEST_CASE("PerformanceDataMonitorCustomPDHCountersTestOpenTelemetry", "[performancedatamonitorcustompdhcounterstestopentelemetry]") {
  PerformanceDataMonitorTester tester;
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::PredefinedGroups, "Disk");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::CustomPDHCounters, "\\System\\Processes,\\Process(*)\\ID Process,\\Process(*)\\Private Bytes");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::OutputFormatProperty, "OpenTelemetry");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::OutputCompactness, "Compact");

  const auto assertions = [&tester]() {
    bool ff_contains_all_data = false;
    const auto lambda = [&ff_contains_all_data](const std::string& path, const std::string& filename) -> bool {
      FILE* fp = fopen((path + utils::file::FileUtils::get_separator() + filename).c_str(), "r");
      REQUIRE(fp != nullptr);
      char readBuffer[50000];
      rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
      rapidjson::Document document;
      document.ParseStream(is);
      fclose(fp);
      ff_contains_all_data =
        document.IsObject() &&
        document.HasMember("Name") &&
        document.HasMember("Timestamp") &&
        document.HasMember("Body") &&
        document["Body"].HasMember("System") &&
        document["Body"]["System"].HasMember("Processes") &&
        document["Body"].HasMember("Process") &&
        document["Body"]["Process"].HasMember("PerformanceDataMonitorTests") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("ID Process");
      return !ff_contains_all_data;
    };

    utils::file::FileUtils::list_dir(tester.dir_, lambda, tester.plan_->getLogger(), false);
    return ff_contains_all_data;
  };

  REQUIRE(tester.runWithRetries(assertions));
}

TEST_CASE("PerformanceDataMonitorAllPredefinedGroups", "[performancedatamonitorallpredefinedgroups]") {
  PerformanceDataMonitorTester tester;
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::PredefinedGroups, "CPU,Disk,Network,Memory,IO,System,Process");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::OutputFormatProperty, "OpenTelemetry");
  tester.setPerformanceMonitorProperty(PerformanceDataMonitor::OutputCompactness, "Pretty");

  const auto assertions = [&tester]() {
    bool ff_contains_all_data = false;
    const auto lambda = [&ff_contains_all_data](const std::string& path, const std::string& filename) -> bool {
      FILE* fp = fopen((path + utils::file::FileUtils::get_separator() + filename).c_str(), "r");
      REQUIRE(fp != nullptr);
      char readBuffer[50000];
      rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
      rapidjson::Document document;
      document.ParseStream(is);
      fclose(fp);
      ff_contains_all_data =
        document.IsObject() &&
        document.HasMember("Name") &&
        document.HasMember("Timestamp") &&
        document.HasMember("Body") &&
        document["Body"].HasMember("PhysicalDisk") &&
        document["Body"]["PhysicalDisk"].HasMember("_Total") &&
        document["Body"]["PhysicalDisk"]["_Total"].HasMember("% Disk Read Time") &&
        document["Body"]["PhysicalDisk"]["_Total"].HasMember("% Disk Time") &&
        document["Body"]["PhysicalDisk"]["_Total"].HasMember("% Disk Write Time") &&
        document["Body"]["PhysicalDisk"]["_Total"].HasMember("% Idle Time") &&

        document["Body"].HasMember("LogicalDisk") &&
        document["Body"]["LogicalDisk"].HasMember("_Total") &&
        document["Body"]["LogicalDisk"]["_Total"].HasMember("Free Megabytes") &&
        document["Body"]["LogicalDisk"]["_Total"].HasMember("% Free Space") &&

        document["Body"].HasMember("Processor") &&
        document["Body"]["Processor"].HasMember("_Total") &&

        document["Body"].HasMember("Network Interface") &&

        document["Body"].HasMember("Memory") &&
        document["Body"]["Memory"].HasMember("% Committed Bytes In Use") &&
        document["Body"]["Memory"].HasMember("Available MBytes") &&
        document["Body"]["Memory"].HasMember("Page Faults/sec") &&
        document["Body"]["Memory"].HasMember("Pages/sec") &&

        document["Body"].HasMember("System") &&
        document["Body"]["System"].HasMember("% Registry Quota In Use") &&
        document["Body"]["System"].HasMember("Context Switches/sec") &&
        document["Body"]["System"].HasMember("File Control Bytes/sec") &&
        document["Body"]["System"].HasMember("File Control Operations/sec") &&

        document["Body"].HasMember("Process") &&
        document["Body"]["Process"].HasMember("PerformanceDataMonitorTests") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("% Processor Time") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("Elapsed Time") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("ID Process") &&
        document["Body"]["Process"]["PerformanceDataMonitorTests"].HasMember("Private Bytes");
      return !ff_contains_all_data;
    };

    utils::file::FileUtils::list_dir(tester.dir_, lambda, tester.plan_->getLogger(), false);
    return ff_contains_all_data;
  };

  REQUIRE(tester.runWithRetries(assertions));
}

TEST_CASE("PerformanceDataMonitorDecimalPlacesPropertyTest", "[performancedatamonitordecimalplacespropertytest]") {
  {
    PerformanceDataMonitorTester tester;
    tester.setPerformanceMonitorProperty(PerformanceDataMonitor::DecimalPlaces, "asd");
    REQUIRE_THROWS_WITH(tester.runWithRetries([]{ return true; }, 1), "General Operation: Invalid conversion to int64_t for asd");
  }
  {
    PerformanceDataMonitorTester tester;
    tester.setPerformanceMonitorProperty(PerformanceDataMonitor::DecimalPlaces, "1234586123");
    REQUIRE_THROWS_WITH(tester.runWithRetries([]{ return true; }, 1), "Process Schedule Operation: PerformanceDataMonitor Decimal Places is out of range");
  }
  {
    PerformanceDataMonitorTester tester;
    tester.setPerformanceMonitorProperty(PerformanceDataMonitor::DecimalPlaces, "");
    REQUIRE_NOTHROW(tester.runWithRetries([]{ return true; }, 1));
  }
}
<|endoftext|>


<commit_before>
#include "initwindowpeer.hxx"

using namespace ::com::sun::star;

uno::Any SAL_CALL InitWindowPeer::getWindowHandle( const uno::Sequence< sal_Int8 >& ProcessId, sal_Int16 SystemType )
    throw ( uno::RuntimeException )
{
    uno::Any aRes;
    sal_Int32 nHwnd = (sal_Int32)m_hwnd;
    aRes <<= nHwnd;
    return aRes;
}

uno::Reference< awt::XToolkit > SAL_CALL InitWindowPeer::getToolkit()
    throw ( uno::RuntimeException )
{
    return uno::Reference< awt::XToolkit >();
}

void SAL_CALL InitWindowPeer::setPointer( const uno::Reference< awt::XPointer >& Pointer )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::setBackground( sal_Int32 Color )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::invalidate( sal_Int16 Flags )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::invalidateRect( const awt::Rectangle& Rect, sal_Int16 Flags )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::dispose()
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::addEventListener( const uno::Reference< lang::XEventListener >& xListener )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::removeEventListener( const uno::Reference< lang::XEventListener >& aListener )
    throw ( uno::RuntimeException )
{
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.1.548); FILE MERGED 2006/09/01 17:26:48 kaib 1.1.548.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: initwindowpeer.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 13:29:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"

#include "initwindowpeer.hxx"

using namespace ::com::sun::star;

uno::Any SAL_CALL InitWindowPeer::getWindowHandle( const uno::Sequence< sal_Int8 >& ProcessId, sal_Int16 SystemType )
    throw ( uno::RuntimeException )
{
    uno::Any aRes;
    sal_Int32 nHwnd = (sal_Int32)m_hwnd;
    aRes <<= nHwnd;
    return aRes;
}

uno::Reference< awt::XToolkit > SAL_CALL InitWindowPeer::getToolkit()
    throw ( uno::RuntimeException )
{
    return uno::Reference< awt::XToolkit >();
}

void SAL_CALL InitWindowPeer::setPointer( const uno::Reference< awt::XPointer >& Pointer )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::setBackground( sal_Int32 Color )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::invalidate( sal_Int16 Flags )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::invalidateRect( const awt::Rectangle& Rect, sal_Int16 Flags )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::dispose()
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::addEventListener( const uno::Reference< lang::XEventListener >& xListener )
    throw ( uno::RuntimeException )
{
}

void SAL_CALL InitWindowPeer::removeEventListener( const uno::Reference< lang::XEventListener >& aListener )
    throw ( uno::RuntimeException )
{
}

<|endoftext|>