/////////////////////////////////////////////////////////////
// CINEMA SDK : TAG / EXPRESSION													 //
/////////////////////////////////////////////////////////////
// VERSION    : CINEMA 4D																	 //
/////////////////////////////////////////////////////////////
// (c) 1989-2002 MAXON Computer GmbH, all rights reserved	 //
/////////////////////////////////////////////////////////////

// "look at editor camera" expression example

#include "c4d.h"
#include "c4d_symbols.h"
#include "Tlookatcameraexp.h"

#include "lib_description.h"
#include "customgui_priority.h"


class LookAtCamera : public TagData
{
	public:
		virtual Bool Init(GeListNode *node);

		virtual LONG Execute(PluginTag *tag, BaseDocument *doc, BaseObject *op, BaseThread *bt, LONG priority, LONG flags);

		static NodeData *Alloc(void) { return gNew LookAtCamera; }
};

Bool LookAtCamera::Init(GeListNode *node)
{
	BaseTag				*tag  = (BaseTag*)node;
	BaseContainer *data = tag->GetDataInstance();

	data->SetBool(LOOKATCAMERAEXP_PITCH,TRUE);
	GeData d;
	if (node->GetParameter(DescLevel(EXPRESSION_PRIORITY),d,0))
	{
		PriorityData *pd = (PriorityData*)d.GetCustomDataType(CUSTOMGUI_PRIORITY_DATA);
		if (pd) pd->SetPriorityValue(PRIORITYVALUE_CAMERADEPENDANT,GeData(TRUE));
		node->SetParameter(DescLevel(EXPRESSION_PRIORITY),d,0);
	}

	return TRUE;
}

LONG LookAtCamera::Execute(PluginTag *tag, BaseDocument *doc, BaseObject *op, BaseThread *bt, LONG priority, LONG flags)
{
	BaseDraw   *bd = doc->GetRenderBaseDraw(); if (!bd) return TRUE;
	BaseObject *cp = bd->GetSceneCamera(doc); 
	if (!cp) cp=bd->GetEditorCamera();
	if (!cp) return TRUE;

	Vector local = cp->GetMg().off * (!op->GetUpMg()) - op->GetPos();
	Vector hpb   = VectorToHPB(local);

	if (!tag->GetData().GetBool(LOOKATCAMERAEXP_PITCH))
		hpb.y = op->GetRot().y;

	hpb.z = op->GetRot().z;

	op->SetRot(hpb);

	return EXECUTION_RESULT_OK;
}

// be sure to use a unique ID obtained from www.plugincafe.com
#define ID_LOOKATCAMERATAG	1001165

Bool RegisterLookAtCamera(void)
{
	// decide by name if the plugin shall be registered - just for user convenience
	String name=GeLoadString(IDS_LOOKATCAMERA); if (!name.Content()) return TRUE;
	return RegisterTagPlugin(ID_LOOKATCAMERATAG,name,TAG_EXPRESSION|TAG_VISIBLE,LookAtCamera::Alloc,"Tlookatcameraexp","lookatcamera.tif",0);
}
