// K-3D
// Copyright (c) 1995-2004, Timothy M. Shead
//
// Contact: tshead@k-3d.com
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

/** \file
		\brief Implements the geometry helpers
		\author Romain Behar (romainbehar@yahoo.com)
*/

#include <k3dsdk/classes.h>
#include <k3dsdk/idag.h>
#include <k3dsdk/imesh_sink.h>
#include <k3dsdk/imesh_source.h>
#include <k3dsdk/iobject.h>
#include <k3dsdk/plugins.h>
#include <k3dsdk/property.h>
#include <k3dsdk/result.h>

#include "helpers.h"

namespace libk3dgeometry
{

namespace detail
{

// Creates a new mesh, put it in a FrozenMesh() and connect it a MeshInstance
k3d::mesh* create_mesh(k3d::idocument& Document, const std::string Name, k3d::iobject*& ReturnFrozenMesh, k3d::iobject*& ReturnMeshInstance)
{
	k3d::mesh* const mesh = new k3d::mesh();
	return_val_if_fail(mesh, 0);

	// Create document object ...
	k3d::iobject* const frozen_mesh = k3d::create_document_plugin(k3d::classes::FrozenMesh(), Document);
	return_val_if_fail(frozen_mesh, 0);
	ReturnFrozenMesh = frozen_mesh;

	k3d::imesh_sink* const frozen_mesh_sink = dynamic_cast<k3d::imesh_sink*>(frozen_mesh);
	return_val_if_fail(frozen_mesh_sink, 0);
	k3d::imesh_source* const frozen_mesh_source = dynamic_cast<k3d::imesh_source*>(frozen_mesh);
	return_val_if_fail(frozen_mesh_source, 0);
	k3d::set_property_value(frozen_mesh_sink->mesh_sink_input(), mesh);

	frozen_mesh->set_name(Name);

	// Create mesh object instance ...
	k3d::iobject* instance = k3d::create_document_plugin(k3d::classes::MeshInstance(), Document);
	return_val_if_fail(instance, 0);
	ReturnMeshInstance = instance;

	instance->set_name(Name + " instance");

	// Set dependencies ...
	k3d::imesh_sink* const instance_sink = dynamic_cast<k3d::imesh_sink*>(instance);
	return_val_if_fail(instance_sink, false);

	k3d::idag::dependencies_t dependencies;
	dependencies[&instance_sink->mesh_sink_input()] = &frozen_mesh_source->mesh_source_output();
	Document.dag().set_dependencies(dependencies);

	return mesh;
}

} // namespace detail

} // namespace libk3dgeometry


