require(GlobalDependencys:GetDependency("StandardBase"):GetPackageName())

--GAME VARS
fDefaultFOV = 85
fAdditionalFOV = 0
fAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
fAspectRatio169 = 1.778
fFactor = 0.00872665
fHUDSafeZOneLeft = 0
fHUDSafeZoneRight = 0

--ControlVars
bFixEnabled = true
bFOV = true
bAspect = true
bHUDSafeZone = true
bCinematicsFPSLimit = true

--PROCESS VARS
Process_FriendlyName = Module:GetFriendlyName()
Process_WindowName = "*"
Process_ClassName = "UnrealWindow"
Process_EXEName = "AloneInTheDark-Win64-Shipping.exe"

--INJECTION BEHAVIOUR
InjectDelay = 500
WriteInterval = 100
SearchInterval = 100
SuspendThread = true

--Name                         Manual/Auto/Hybrid  		Steam/Origin/Any                IncludeFile:Configure;Enable;Periodic;Disable;
SupportedVersions = { 		
{"Automatically Detect",       "Hybrid",  			"Any",	                         "Configure_SignatureScan;Enable_Inject;Periodic;Disable_Inject;"},
}

function Init_Controls()

	DefaultControls.AddHeader("Header_FixesEnableDisable","Individual Fixes",245,70,210,17)
	
	DefaultControls.AddHeader("Header_FOV","FOV fine adjustment",15,70,210,17)	
	DefaultControls.AddFixedFOVSlider("FOVSlider","FOVSlider_Changed",55,100,125,35,0,60,0,1)
	FOVSlider:SetTickFrequency(5)
	FOVSlider:SetLabel1Text("-20")
	FOVSlider:SetLabel2Text("+40")
	
	DefaultControls.AddHeader("HeaderHUDSZ","HUD safe zone",15,160,210,17)	
	DefaultControls.AddFixedFOVSlider("HUD","HUDSZSlider_Changed",55,190,125,35,0,40,0,1)
	HUD:SetTickFrequency(5)
	HUD:SetLabel1Text("0")
	HUD:SetLabel2Text("40")
	
	DefaultControls.AddFixToggle("CKFOVFix_Enable","FOV fix","CKFOVFix_Changed",255,101,180,14)
	DefaultControls.AddFixToggle("CKARFix_Enable","Aspect ratio fix","CKARFix_Changed",255,121,180,14)
	DefaultControls.AddFixToggle("CKHUDFix_Enable","HUD safe zone fix","CKHUDFix_Changed",255,141,180,14)
	DefaultControls.AddFixToggle("CKCINEMATICSFPSFix_Enable","Cinematics FPS fix (uncapped)","CKCINEMATICSFPSLimitFix_Changed",255,161,190,14)
	
end

function Configure_SignatureScan() 
	
	local tAddress = HackTool:AddAddress("FOV")
	
	if HackTool:SignatureScan("C6 84 ?? ?? ?? ?? ?? ?? 48 ?? ?? 74 ?? E8 ?? ?? ?? ?? 0F ?? ?? 48 8B ?? ?? ?? ?? ?? ?? 48 ?? ?? E8 ?? ?? ?? ?? 0F 28 ?? ?? ?? ?? ?? ??",tAddress,PAGE_EXECUTE_READ,0x12,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--AloneInTheDark-Win64-Shipping.exe+361840D - 74 05                 	- je AloneInTheDark-Win64-Shipping.exe+3618414
		--AloneInTheDark-Win64-Shipping.exe+361840F - E8 5C 30 37 FE           	- call AloneInTheDark-Win64-Shipping.exe+198B470
		--AloneInTheDark-Win64-Shipping.exe+3618414 - 0F 28 C6               	- movaps xmm0,xmm6
		--AloneInTheDark-Win64-Shipping.exe+3618417 - 48 8B 8C 24 20 06 00 00  	- mov rcx,[rsp+00000620]
		--AloneInTheDark-Win64-Shipping.exe+361841F - 48 33 CC              	- xor rcx,rsp
	end
		
	local tAddress = HackTool:AddAddress("ASPECT")
	
	if HackTool:SignatureScan("8B 83 ?? ?? ?? ?? 89 ?? ?? 0F B6 ?? ?? ?? ?? ?? 33 ?? ?? 83 ?? ?? 31 ?? ?? 0F B6 ",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		local tAddress = HackTool:AddAddress("ASPECT", HackTool:GetAddress( string.format("ASPECTS%d",1) ))
		print( tAddress:GetInfo(TYPE_ADDRESS) )	
		--AloneInTheDark-Win64-Shipping.exe+3213EC2 - F3 0F 10 83 08 02 00 00   - movss xmm0,[rbx+00000208]
		--AloneInTheDark-Win64-Shipping.exe+3213ECA - F3 0F 11 47 18         	- movss [rdi+18],xmm0
		--AloneInTheDark-Win64-Shipping.exe+3213ECF - 8B 83 18 02 00 00        	- mov eax,[rbx+00000218]
		--AloneInTheDark-Win64-Shipping.exe+3213ED5 - 89 47 2C              	- mov [rdi+2C],eax
		--AloneInTheDark-Win64-Shipping.exe+3213ED8 - 0F B6 83 1C 02 00 00      - movzx eax,byte ptr [rbx+0000021C]
	end	
	
	local tAddress = HackTool:AddAddress("HUDSAFEZONE")
	
	if HackTool:SignatureScan("F3 ?? ?? ?? ?? 75 ?? E8 ?? ?? ?? ?? 40 ?? ?? ?? 0F 84",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--AloneInTheDark-Win64-Shipping.exe+2EB8F4A - FF D0                 - call rax
		--AloneInTheDark-Win64-Shipping.exe+2EB8F4C - 48 8B 5C 24 40        - mov rbx,[rsp+40]
		--AloneInTheDark-Win64-Shipping.exe+2EB8F51 - 0F 10 00              - movups xmm0,[rax]
		--AloneInTheDark-Win64-Shipping.exe+2EB8F54 - 48 8B C7              - mov rax,rdi
		--AloneInTheDark-Win64-Shipping.exe+2EB8F57 - 0F 11 07              - movups [rdi],xmm0
	end
	
	local tAddress = HackTool:AddAddress("CINEMATICFPSLIMIT")
	
	if HackTool:SignatureScan("F3 0F ?? ?? ?? EB ?? 0F ?? ?? 48 8B ?? ?? ?? 0F 28",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--AloneInTheDark-Win64-Shipping.exe+379E354 - 3B 05 3E 9C 70 02      - cmp eax,[AloneInTheDark-Win64-Shipping.exe+5EA7F98]
		--AloneInTheDark-Win64-Shipping.exe+379E35A - 0F 95 C3               - setne bl
		--AloneInTheDark-Win64-Shipping.exe+379E35D - F3 0F 10 04 9F         - movss xmm0,[rdi+rbx*4]
		--AloneInTheDark-Win64-Shipping.exe+379E362 - EB 03                  - jmp AloneInTheDark-Win64-Shipping.exe+379E367
		--AloneInTheDark-Win64-Shipping.exe+379E364 - 0F 28 C6               - movaps xmm0,xmm6
	end
		
	return true
end

function Enable_Inject()

	local Variables = HackTool:AllocateMemory("Variables",0)
	Variables:PushFloat("CompensatedFOV")
	Variables:PushFloat("FOVIn")
	Variables:PushFloat("FOVOut")
	Variables:PushFloat("AdditionalFOV")
	Variables:PushFloat("AspectRatio")
	Variables:PushFloat("ScreenRatio")
	Variables:PushFloat("factor")
	Variables:PushFloat("HUDSafeZoneLeft")
	Variables:PushFloat("HUDSafeZoneTop")
	Variables:PushFloat("HUDSafeZoneRight")
	Variables:PushFloat("HUDSafeZoneBottom")
	Variables:PushFloat("HUDSafeZoneDefRight")
	Variables:PushFloat("HUDSafeZoneDefBottom")
	Variables:PushFloat("HUD_Left")
	Variables:PushFloat("HUD_Width")
	Variables:PushFloat("tmp")

	Variables:Allocate()
	Variables["FOVIn"]:WriteFloat(fDefaultFOV)
	Variables["FOVOut"]:WriteFloat(fDefaultFOV)
	Variables["AdditionalFOV"]:WriteFloat(fAdditionalFOV)
	Variables["AspectRatio"]:WriteFloat(fAspectRatio169)
	Variables["ScreenRatio"]:WriteFloat(fAspectRatio)
	Variables["factor"]:WriteFloat(fFactor)
	Variables["HUDSafeZoneLeft"]:WriteFloat(0)
	Variables["HUDSafeZoneTop"]:WriteFloat(0)
	Variables["HUDSafeZoneRight"]:WriteFloat(1)
	Variables["HUDSafeZoneBottom"]:WriteFloat(1)
	Variables["HUDSafeZoneDefRight"]:WriteFloat(1)
	Variables["HUDSafeZoneDefBottom"]:WriteFloat(1)
	
	ResolutionChanged()	
	

	local asm = [[	

		(codecave:jmp)FOV,FOV_cc:
			movss [(allocation)Variables->FOVIn],$$2						$ctx=1
			fld dword ptr [(allocation)Variables->FOVIn]
			fmul dword ptr [(allocation)Variables->factor]
			fptan
			fstp st0
			fld dword ptr [(allocation)Variables->ScreenRatio]
			fdiv dword ptr [(allocation)Variables->AspectRatio]
			fmulp st1,st0
		    fld1
		    fpatan
			fdiv dword ptr [(allocation)Variables->factor]						; calculate compensated FOV
			fstp dword ptr [(allocation)Variables->CompensatedFOV]				; and retrieve it			
			movss $$2,[(allocation)Variables->CompensatedFOV]				$ctx=1
			addss $$2,[(allocation)Variables->AdditionalFOV]				$ctx=1
			movss [(allocation)Variables->FOVOut],$$2						$ctx=1
			%originalcode%
			jmp %returnaddress%
			%end%
									
		(codecave:jmp)ASPECT,ASPECT_cc:
			$$0 $$1,[(allocation)Variables->ScreenRatio]					$ctx=1
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)HUDSAFEZONE,HUDSAFEZONE_cc:
			fld dword ptr [(allocation)Variables->HUD_Width]
			fdiv dword ptr [$$2+8]											$ctx=1
			fstp dword ptr [$$2]											$ctx=1
			fld dword ptr [(allocation)Variables->HUD_Left]
			fstp dword ptr [$$2+0x2c]										$ctx=1
			%originalcode%
			jmp %returnaddress%		
			%end%
			
			tmp: (float)1.0
			
		(codecave:jmp)CINEMATICFPSLIMIT,CINEMATICFPSLIMIT_cc:
			$$0 $$1,[FPSLimit]												$ctx=1
			jmp %returnaddress%
			%end%
			
			FPSLimit: (float)0f
		
	]]

	if HackTool:CompileAssembly(asm,"Fixes") == nil then
		return ErrorOccurred("Assembly compilation failed...")
	else
		Toggle_CodeCave("FOV_cc",bFOV)
		Toggle_CodeCave("ASPECT_cc",bAspect)
		Toggle_CodeCave("HUDSAFEZONE_cc",bHUDSafeZone)
		Toggle_CodeCave("CINEMATICFPSLIMIT_cc",bCinematicsFPSLimit)
	end	
			
	Write_FOV()
	Write_AR()
	CalculateHUDScaling()
	Write_HUD_Safe_Zone()
	
end

function Periodic()

	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["FOVIn"] and Variables["AdditionalFOV"] then
		local fCompensatedFOV = Variables["CompensatedFOV"]:ReadFloat()
		local fFOVIn = Variables["FOVIn"]:ReadFloat()
		local fFOVOut = Variables["FOVOut"]:ReadFloat()
		PluginViewport:AppendStatusMessage( string.format("\r\n===== Fix informations =====\r\nFOV In: %.2f, Compensated FOV: %.2f, FOV Out: %.2f", fFOVIn, fCompensatedFOV, fFOVOut))
	end
	
end

function CalculateHUDScaling()

	local Width = DisplayInfo:GetWidth()
	
	if fHUDSafeZOneLeft ~= 0 then
		HUD_With_factor = 1 - ((fHUDSafeZOneLeft * 2) / 100)
		HUD_Left_factor = fHUDSafeZOneLeft / 100
		HUD_Width = Width * HUD_With_factor
		HUD_Left = Width * HUD_Left_factor
	else
		HUD_Width = DisplayInfo:GetfOffsetWidth(0,0)
		HUD_Left = DisplayInfo:GetiOffsetX(0)
	end
	
end

function FOVSlider_Changed(Sender)

	fAdditionalFOV = Sender:GetPosition() - 20
	lblFOVSlider.Caption:SetCaption( string.format("Value: +%.0f",fAdditionalFOV) )		
	Write_FOV()
	ForceUpdate()

end

function HUDSZSlider_Changed(Sender)

	fHUDSafeZOneLeft = Sender:GetPosition()
	lblHUD.Caption:SetCaption( string.format("+ %.0f %%",fHUDSafeZOneLeft) )
	CalculateHUDScaling()
	Write_HUD_Safe_Zone()
	ForceUpdate()
	
end

function Write_FOV()

	local Variables = HackTool:GetAllocation("Variables")
	if Variables and Variables["AdditionalFOV"] then
		if bFOV == true then
			Variables["AdditionalFOV"]:WriteFloat(fAdditionalFOV)
		else
			Variables["AdditionalFOV"]:WriteFloat(0)
		end
	end

end

function Write_AR()

	local Variables = HackTool:GetAllocation("Variables")
	if Variables and Variables["AspectRatio"] then
		if bAspect == true then
			Variables["AspectRatio"]:WriteFloat(fAspectRatio169)
		else
			Variables["AspectRatio"]:WriteFloat(fAspectRatio)
		end
	end

end

function Write_HUD_Safe_Zone()

	local Variables = HackTool:GetAllocation("Variables")
	if Variables and Variables["HUD_Left"] and Variables["HUD_Width"] then
		Variables["HUD_Left"]:WriteFloat(HUD_Left)
		Variables["HUD_Width"]:WriteFloat(HUD_Width)
	end
	
end

function Disable_Inject()
	
	CleanUp()
	
end

function CKFOVFix_Changed(Sender)

	bFOV = Toggle_CheckFix(Sender)
	Toggle_CodeCave("FOV_cc",bFOV)
	Write_FOV()
	ForceUpdate()
	
end

function CKARFix_Changed(Sender)

	bAspect = Toggle_CheckFix(Sender)
	Toggle_CodeCave("ASPECT_cc",bAspect)
	Write_AR()
	ForceUpdate()
	
end

function CKHUDFix_Changed(Sender)

	bHUDSafeZone = Toggle_CheckFix(Sender)
	Write_HUD_Safe_Zone()
	Toggle_CodeCave("HUDSAFEZONE_cc",bHUDSafeZone)
	ForceUpdate()

end

function CKCINEMATICSFPSLimitFix_Changed(Sender)

	bCinematicsFPSLimit = Toggle_CheckFix(Sender)
	Toggle_CodeCave("CINEMATICFPSLIMIT_cc",bCinematicsFPSLimit)
	ForceUpdate()

end

function ResolutionChanged() 

	SyncDisplayDetection()
	
end

function Init()

	Init_BaseControls()
	Init_Controls()

end

function DeInit()

	DisableFix()

end
