//
// Copyright(C) 2014-2015 Samuel Villarreal
//
// 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.
//
// DESCRIPTION:
//      Level Script For Level48.map
//

#include "scripts/common.txt"

kActor @g_pHummer1 = null;
kActor @g_pHummer2 = null;
kActor @g_pHunter = null;
kActor @g_pKey = null;
kActor @g_pWaterSoundActor = null;

kVec3 g_vHunterTauntLocation;

// Smoke39
enum eScripts {
	Script_Intro_SkipCheck = 12,
	Script_Intro_Cancelled,
	Script_Victory_SkipCheck,
	Script_Victory_Cancelled_Longhunter,
	Script_Victory_Cancelled_Dams
}

/*
==============================================================
CheckPosition
==============================================================
*/

bool CheckPosition(const float dist, const float angle, kVec3 &out position)
{
    kActor @actor = Player.Actor().CastToActor();
    float ang = actor.Yaw() + angle;

    position.x = actor.Origin().x + Math::Sin(ang) * dist;
    position.y = actor.Origin().y + Math::Cos(ang) * dist;
    position.z = actor.Origin().z;

    return actor.CheckPosition(position);
}

/*
==============================================================
SpawnHummer
==============================================================
*/

void SpawnHummer(kActor @actor)
{
    actor.Flags() &= ~(AF_HIDDEN|AF_DISABLED);
    actor.ClipFlags() |= CF_DROPOFF;
    actor.ClipFlags() &= ~(CF_NOENTERWATER|CF_NOEXITWATER);

    actor.AnimState().Set(anim_aiTeleportIn, 4.0f, ANF_ROOTMOTION);
    Game.PlaySound("sounds/shaders/generic_87_humvee_jump.ksnd");
}

/*
==============================================================
OpenDam
==============================================================
*/

void OpenDam(kActor @instigator)
{
    kActor @pForceField;
    kActor @pKey;

    for(int i = 0; i < 4; ++i)
    {
        kActor @waterGate = World.GetActorByTID(611 + i);
        kActor @waterFall = World.GetActorByTID(11 + i);

        waterFall.Flags() &= ~AF_HIDDEN;
        waterGate.AnimState().Set(anim_trapActivate, 96.0f, 0);
    }

	if(g_pWaterSoundActor is null)
	{
		@g_pWaterSoundActor = ActorFactory.Spawn("DummyActor", 0, 0, 0, 0);
	}

	// raise key and play waterfall sound
	if(!Game.IsRunningMapScript(11))
	{
		Game.CallDelayedMapScript(11, instigator, 0);
	}

    // raise platform/pedistal
    World.TriggerActorsByTID(instigator, 50);
    // raise water
    World.TriggerActorsByTID(instigator, 51);

    World.FloodFillAreaFlags(kVec3(-17.5f*GAME_SCALE, 0, 0), AAF_BLOCK, false);
    @pForceField = World.GetActorByTID(150);

    if(!(pForceField is null))
    {
        pForceField.Remove();
    }
}

/*
==============================================================
Script 0
==============================================================
*/

$script 0
{
    int state, state2, state3;

    Player.SilentCheckPoints() = true;

    GameVariables.GetInt("longHunterState", state);
    GameVariables.GetInt("hummer1State", state2);
    GameVariables.GetInt("hummer2State", state3);

	@g_pKey = World.GetActorByTID(1);
	if(g_pKey !is null)
	{
		g_pKey.AddCustomRef();
	}

    if(state == LHGS_NEW)
    {
        Game.CallDelayedMapScript(1, instigator, 0.0f);
    }

    @g_pHummer1 = World.GetActorByTID(1140);
    @g_pHummer2 = World.GetActorByTID(1141);

    @g_pHunter = World.GetActorByTID(400);

    if(state2 == HGS_ENTERED_ARENA)
    {
        Game.CallDelayedMapScript(2, instigator, 0);
    }
    else if(state3 == HGS_ENTERED_ARENA)
    {
        Game.CallDelayedMapScript(7, instigator, 0);
    }

    if(state == LHGS_INCOMBAT)
    {
        Game.CallDelayedMapScript(8, instigator, 0);
    }

    if(state != LHGS_DEAD)
    {
        for(int i = 0; i < 4; ++i)
        {
            kActor @waterFall = World.GetActorByTID(11 + i);
            waterFall.Flags() |= AF_HIDDEN;
        }
    }
    else
    {
        OpenDam(instigator);
        g_pHunter.ImpactType() = IT_FLESH_HUMAN;
    }
}

/*
==============================================================
Script 1 - begin intro cutscene when player gets near key
==============================================================
*/

$script 1
{
    kActor @actor = Player.Actor().CastToActor();
    kVec3 position;

    if(actor.OnGround())
    {
        float x = actor.Origin().x;
        float y = actor.Origin().y;
        float dist = (30*GAME_SCALE);

        if(x * x + y * y < (dist*dist))
        {
            if( CheckPosition(15*GAME_SCALE, Math::Deg2Rad(180.0f), position) ||
                CheckPosition(15*GAME_SCALE, Math::Deg2Rad( 90.0f), position) ||
                CheckPosition(15*GAME_SCALE, Math::Deg2Rad(-90.0f), position))
            {
                g_vHunterTauntLocation = position;

                Game.CallDelayedMapScript(3, instigator, 0.0f);

                Camera.origin = actor.Origin();
                Camera.origin.z += (4*GAME_SCALE);

                Camera.SetEyeView(Camera.origin);

                Camera.yaw = (g_vHunterTauntLocation - actor.Origin()).ToYaw();
                Camera.pitch = 0;
                Camera.roll = 0;

                Camera.StartCinematic();
                Camera.fov = 74.0f;

                // Smoke39 - allow player to skip cutscene
                Game.CallDelayedMapScript( Script_Intro_SkipCheck, instigator, 0 );

                return;
            }
        }
    }

    delay(0.1f);
    $restart;
}

/*
==============================================================
Script 2 - spawn second humvee when first is destroyed
==============================================================
*/

$script 2
{
    if(g_pHummer1.Health() <= 0)
    {
        SpawnHummer(g_pHummer2);
        PlayLoop.TagActorForBossBar(g_pHummer2);
        Game.CallDelayedMapScript(7, instigator, 0);
        return;
    }

    delay(0.1f);
    $restart;
}

/*
==============================================================
Script 3 - intro cutscene - longhunter taunt
==============================================================
*/

$script 3
{
    if(Camera.CinematicState() == 2)
    {
        g_pHunter.SetPosition(kVec3(g_vHunterTauntLocation.x, g_vHunterTauntLocation.y, 0));
        g_pHunter.Origin().z = g_pHunter.FloorHeight();
        g_pHunter.Yaw() = (Player.Actor().Origin() - g_pHunter.Origin()).ToYaw();

        g_pHunter.AnimState().Set(anim_longHunterTaunt, 4.0f, ANF_ROOTMOTION);

        Game.CallDelayedMapScript(4, instigator, 3.6f);

        delay(1.35f);
        g_pHunter.PlaySound("sounds/shaders/longhunter_taunt_1.ksnd");
        return;
    }

    $restart;
}

/*
==============================================================
Script 4 - intro cutscene - spawn first humvee
==============================================================
*/

$script 4
{
    Camera.SetLookAtActor(g_pHummer1);

    SpawnHummer(g_pHummer1);
    Game.CallDelayedMapScript(2, instigator, 0.0f);

    Camera.origin = g_vHunterTauntLocation;
    Camera.origin.z += (6*GAME_SCALE);

    Camera.SetEyeView(Camera.origin);

    Game.CallDelayedMapScript(6, instigator, 2.5f);
}

/*
==============================================================
Script 5
==============================================================
*/

$script 5
{
}

/*
==============================================================
Script 6 - end intro cutscene
==============================================================
*/

$script 6
{
    Camera.StopCinematic();
    PlayLoop.TagActorForBossBar(g_pHummer1);
}

/*
==============================================================
Script 7 - activate longhunter when second humvee is destroyed
==============================================================
*/

$script 7
{
    if(g_pHummer2.Health() <= 0)
    {
        PlayLoop.TagActorForBossBar(g_pHunter);
        g_pHunter.ImpactType() = IT_FLESH_HUMAN;
        Game.CallDelayedMapScript(8, instigator, 0);
        return;
    }

    delay(0.1f);
    $restart;
}

/*
==============================================================
Script 8 - longhunter death, victory dance
==============================================================
*/

$script 8
{
    if(g_pHunter.Health() <= 0)
    {
        kActor @pItem;

        Game.CallDelayedMapScript(9, instigator, 0);
        Game.CallDelayedMapScript(10, instigator, 7.0f);
		Game.CallDelayedMapScript(11, instigator, 0);
        // Smoke39 - allow cutscene to be skipped
		// delay by 1 extra tick to make sure $script 9 starts cinematic first
        Game.CallDelayedMapScript( Script_Victory_SkipCheck, instigator, 2 * GAME_DELTA_TIME );

        delay(0.35f);
        g_pHunter.AnimState().Set(anim_aiDeathStand, 4.0f, ANF_ROOTMOTION);
        g_pHunter.ModelVariation() = 1;
		g_pHunter.Flags() &= ~AF_SOLID;

        @pItem = ActorFactory.Spawn("Wpn_PulseRifle",
            g_pHunter.Origin().x, g_pHunter.Origin().y, g_pHunter.Origin().z,
            0, g_pHunter.SectorIndex());

		pItem.Flags() |= AF_CASTSHADOW;
        pItem.Scale() = kVec3(0.35f, 0.35f, 0.35f);

        delay(11.25f);
        Player.Victory();
        return;
    }

    $restart;
}

/*
==============================================================
Script 9 - begin victory cutscene
==============================================================
*/

$script 9
{
    Camera.StartCinematic(CMF_LOCK_PLAYER|CMF_UNLOCK_PLAYER_ON_FINISH|CMF_SHOW_HIDDEN_OBJECTS);
    PlayLoop.RemoveBossActor();

    Camera.SetLookAtActor(g_pHunter);
    Camera.fov = 74.0f;

    Camera.SetFinalView(0);
    Camera.SetRotationTrack(0,
                            Math::Deg2Rad(0.0f),    // start angle
                            Math::Deg2Rad(160.0f),  // dest angle
                            7*GAME_SCALE,           // start distance
                            8*GAME_SCALE,           // dest distance
                            8*GAME_SCALE,           // start height
                            2*GAME_SCALE,           // dest height
                            5*GAME_SCALE,           // start look at height
                            3*GAME_SCALE);          // dest look at height

    Camera.AutoPlayRotationTrack(0, 3.33f, CMLT_COSINE);
}

/*
==============================================================
Script 10 - watch key rising
==============================================================
*/

$script 10
{
    Game.HaltMapScript(9);

    Camera.ClearLookAtActor();
    Camera.ClearViewTracks();
    Camera.SetFinalView(0);

    Camera.SetEyeView(kVec3(50*GAME_SCALE, 50*GAME_SCALE, 10*GAME_SCALE));
    Camera.SetFocusView(kVec3(0, 0, 0));

    OpenDam(instigator);

    delay(4.6f);
}


/*
==============================================================
Script 11 - raise key and play waterfall sound
==============================================================
*/

$script 11
{
	if(g_pKey !is null)
	{
		g_pKey.Origin().z = g_pKey.FloorHeight() + 13.998407f;
	}

	if(g_pWaterSoundActor !is null)
	{
		g_pWaterSoundActor.SetPosition(Camera.Active() ? Camera.origin : Player.Actor().Origin());
		g_pWaterSoundActor.PlaySound("sounds/shaders/waterfall_rush_lh.ksnd");
	}

	$restart;
}

/*
==============================================================
Smoke39
==============================================================
*/

// Script_Intro_SkipCheck
$script 12
{
	if ( Camera.CinematicState() == CAMS_IDLE )
		return;

	if ( Camera.UserInterrupted() )
	{
		if ( g_pHunter.AnimState().IsPlaying(anim_longHunterTaunt) )
			Game.CallDelayedMapScript( Script_Intro_Cancelled, instigator, 0 );

		if ( g_pHummer1.Flags() & AF_HIDDEN != 0 )
		{
			SpawnHummer( g_pHummer1 );
			Game.CallDelayedMapScript( 2, instigator, 0 );
		}

		Camera.StopCinematic();
		PlayLoop.TagActorForBossBar( g_pHummer1 );

		Game.HaltMapScript( 3 ); // prevent taunt sound
		Game.HaltMapScript( 4 ); // cancel queued humvee spawning
		Game.HaltMapScript( 6 ); // cancel queued cutscene end

		return;
	}

	$restart;
}

// Script_Intro_Cancelled - fast-track taunt anim when no one's looking
$script 13
{
	if ( Camera.CinematicState() == CAMS_FADEBACK_TO_CLIENT )
	{
		// stopping anim and/or setting last frame simply freezes longhunter
		// changing speed to 0 makes him disappear
		// 1 may make his first move too fast?
		// setting ANF_CYCLECOMPLETED does nothing
		// make sure anim hasn't already finished
		if ( g_pHunter.AnimState().IsPlaying(anim_longHunterTaunt) )
			g_pHunter.AnimState().ChangeSpeed( 0.1f );
	}
	else
		$restart;
}

// Script_Victory_SkipCheck
$script 14
{
	if ( Camera.CinematicState() == CAMS_IDLE )
		return;

	if ( Camera.UserInterrupted() )
	{
		Camera.StopCinematic();

		Game.HaltMapScript(  8 ); // cancel watching death anim and victory dance
		Game.HaltMapScript( 10 ); // cancel queued cut to key rising

		// longhunter hasn't started dying yet
		if ( g_pHunter.ModelVariation() != 1 )
		{
			g_pHunter.AnimState().Set( anim_aiDeathStand, 4.0f, ANF_ROOTMOTION );
			g_pHunter.ModelVariation() = 1;

			kActor @pItem = ActorFactory.Spawn( "Wpn_PulseRifle",
				g_pHunter.Origin().x, g_pHunter.Origin().y, g_pHunter.Origin().z,
				0, g_pHunter.SectorIndex() );
			pItem.Scale() = kVec3( 0.35f, 0.35f, 0.35f );
		}

		// longhunter is still dying -- wait for camera to fade out to fastrack anim
		if ( g_pHunter.AnimState().IsPlaying(anim_aiDeathStand) )
			Game.CallDelayedMapScript( Script_Victory_Cancelled_Longhunter, instigator, 0 );

		// make sure dams fully open off-camera
		Game.CallDelayedMapScript( Script_Victory_Cancelled_Dams, instigator, 0 );

		return;
	}

	$restart;
}

// Script_Victory_Cancelled_Longhunter - fast-track longhunter death anim when no one's looking
$script 15
{
	if ( Camera.CinematicState() == CAMS_FADEBACK_TO_CLIENT )
	{
		if ( g_pHunter.AnimState().IsPlaying(anim_aiDeathStand) )
			g_pHunter.AnimState().ChangeSpeed( 0.1f );
	}
	else
		$restart;
}

// Script_Victory_Cancelled_Dams - open dams if necessary, and fast-track lower anims when no one's looking
$script 16
{
	if ( Camera.CinematicState() == CAMS_FADEBACK_TO_CLIENT )
	{
		// force field still exists - means cutscene was canceled before dams started opening
		if ( World.GetActorByTID(150) !is null )
			OpenDam( instigator );
		// fast-track dams opening
		for ( int i = 0;  i < 4;  i++ )
		{
			kActor @waterGate = World.GetActorByTID( 611 + i );
			if ( waterGate.AnimState().IsPlaying(anim_trapActivate) )
				waterGate.AnimState().ChangeSpeed( 0.1f );
		}
	}
	else
		$restart;
}
