#include "dll_defs.hpp"

namespace player {
	void init() {
		Game::Light light("Spot"); light.SetName("flashlight");
		light.SetState(true);
		light.SetRange(32);
		light.EnableShadow();
		light.SetSpecular(0);
		light.SetEnergy(8.0);
		light.SetColor(0xffffddff);
		light.SetShadowUpdateMode("Continuous");
		
		Game::CFrame player; player.SetName("player");
		player.MoveTo({-2, 1.5, -5});
		Game::DisableCursor();
		Game::HideCursor();
		Game::SetMousePosition({500, 500});
	}
	void tick() {
		static Game::CFrame player = Game::Root.GetChild<Game::CFrame>("player");
		static Game::Light flashlight = Game::Root.GetChild<Game::Light>("flashlight");
		static float Pitch = 0;
		static float Yaw = 0;
		static std::vector<float> moveVector = {0, 0, 0};
		static std::vector<float> velocityVector = {0, 0, 0};
		static bool grounded = false;
		
		Game::SetCameraPosition(player.Position());
		Game::SetCameraLookDirection(player.LookVector());
		Game::SetCameraUpDirection(player.UpVector());
		flashlight.SetPosition(player.Position());
		flashlight.SetDirection(player.LookVector());
		
		auto MouseDelta = Game::GetMouseDelta();
		Pitch += MouseDelta[1] / 100;
		Yaw -= MouseDelta[0] / 100;
		
		if (Game::IsKeyDown(KEY_W)) moveVector = Game::Vector3::Add(moveVector, Game::Vector3::Multiply(player.LookVector(), {1, 0, 1}));
		if (Game::IsKeyDown(KEY_S)) moveVector = Game::Vector3::Add(moveVector, Game::Vector3::Multiply(player.LookVector(), {-1, 0, -1}));
		if (Game::IsKeyDown(KEY_D)) moveVector = Game::Vector3::Add(moveVector, Game::Vector3::Multiply(player.RightVector(), {1, 0, 1}));
		if (Game::IsKeyDown(KEY_A)) moveVector = Game::Vector3::Add(moveVector, Game::Vector3::Multiply(player.RightVector(), {-1, 0, -1}));
		
		player.MoveBy(Game::Vector3::Scale(velocityVector, Game::DeltaTime()));
		
		player.RotateTo({Pitch, Yaw, 0});
		Game::SetMousePosition({500, 500});
		
		Game::RaycastSingle raycast(Game::Root.GetChild<Game::Model>("base"), player.Position(), {0, -1, 0});
		grounded = (raycast.distance <= 1.6f);
		if (raycast.distance < 1.6f) player.MoveBy({0, 1.6f - raycast.distance, 0});
		if (!grounded) velocityVector = Game::Vector3::Subtract(velocityVector, {0, Game::DeltaTime() * 9.8f, 0});
		else {
			velocityVector = Game::Vector3::Scale(Game::Vector3::Normalize(moveVector), 3);
			if (Game::IsKeyDown(KEY_SPACE)) velocityVector = Game::Vector3::Add(velocityVector, {0, 2, 0});
		}
		moveVector = {0, 0, 0};
	}
}