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

--GAME VARS
fDefaultFOV = 0
fDefaultAspectRatio = 1.77778
--fDefaultAspectRatio = 1.777777791
fAdditionalFOV = 0
fAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
fFactor = 0.00872665
fHUDSafeZOneLeft = 0
fHUDSafeZoneRight = 100

--ControlVars
bFixEnabled = true
bFOV = true
bPillarBoxing = true
bDOF = true
bFringe = true
--bHUDSafeZone = true

--PROCESS VARS
Process_FriendlyName = Module:GetFriendlyName()
Process_WindowName = "*"
Process_ClassName = "UnrealWindow"
Process_EXEName = "TME-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,80,0,1)
	
	FOVSlider:SetTickFrequency(5)
	FOVSlider:SetLabel1Text("-20")
	FOVSlider:SetLabel2Text("+60")

	DefaultControls.AddFixToggle("CKFOVFix_Enable","FOV fix","CKFOVFix_Changed",255,101,180,14)
	DefaultControls.AddFixToggle("CKARFix_Enable","Letterbox fix","CKARFix_Changed",255,121,180,14)
	DefaultControls.AddFixToggle("CKDOFFix_Enable","Depth of field fix","CKDOFFix_Changed",255,141,180,14)
	DefaultControls.AddFixToggle("CKFRINGEFix_Enable","Chromatic aberration fix","CKFRINGEFix_Changed",255,161,180,14)

end

function Configure_SignatureScan() 
	
	local tAddress = HackTool:AddAddress("FOV")
	
	if HackTool:SignatureScan("74 ?? 48 8B ?? ?? ?? ?? ?? ?? 48 ?? ?? 74 ?? E8 ?? ?? ?? ?? 48 8B ?? ?? ?? ?? ?? ?? 48 ?? ?? 74 ?? E8 ?? ?? ?? ?? 0F ?? ?? 48 8B ?? ?? ?? ?? ?? ?? 48 ?? ?? E8 ?? ?? ?? ?? 0F 28",tAddress,PAGE_EXECUTE_READ,0x26,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TME-Win64-Shipping.exe+1980322 - 48 33 CC                 - xor rcx,rsp
		--TME-Win64-Shipping.exe+1980325 - E8 66 23 C7 00           - call TME-Win64-Shipping.exe+25F2690
		--TME-Win64-Shipping.exe+198032A - 0F 28 B4 24 80 06 00 00  - movaps xmm6,[rsp+00000680]
		--TME-Win64-Shipping.exe+1980332 - 48 81 C4 98 06 00 00     - add rsp,00000698
		--TME-Win64-Shipping.exe+1980339 - C3                       - ret 
	end
	
	local tResultCount = HackTool:SignatureScanMulti("CC CC 48 ?? ?? ?? ?? 57 48 ?? ?? ?? F2 ?? ?? ?? 48 ?? ?? F2 ?? ?? ?? 48 ?? ?? 8B ?? ?? 89 ?? ?? F2 ?? ?? ?? ?? F2 ?? ?? ?? ?? 8B ?? ?? 89 ?? ?? 8B ?? ?? 89 ?? ?? 8B ?? ?? 89 ?? ??","ASPECTs",PAGE_EXECUTE_READ,0x51,Process_EXEName)
	
	if tResultCount ~= 2 then	
		return ErrorOccurred("Could not find ASPECTs injection point, " .. Process_FriendlyName .. 
							 " may have updated to a version that is no longer supported.\r\n\r\n" .. 
							 "Try selecting a different version and re-enable the fix."	)
	else	
		local tAddress = HackTool:AddAddress("ASPECT", HackTool:GetAddress( string.format("ASPECTs%d",1) ))
		print( tAddress:GetInfo(TYPE_ADDRESS) )		
		--TME-Win64-Shipping.exe+196D819 - 89 41 28              - mov [rcx+28],eax
		--TME-Win64-Shipping.exe+196D81C - 8B 42 2C              - mov eax,[rdx+2C]
		--TME-Win64-Shipping.exe+196D81F - 89 41 2C              - mov [rcx+2C],eax
		--TME-Win64-Shipping.exe+196D822 - 8B 41 30              - mov eax,[rcx+30]
		--TME-Win64-Shipping.exe+196D825 - 33 42 30              - xor eax,[rdx+30]
	end
	
	local tAddress = HackTool:AddAddress("DOF")
	
	if HackTool:SignatureScan("8B ?? ?? 66 C7 ?? ?? ?? ?? ?? 85 ?? 0F 8E",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )		
		--TME-Win64-Shipping.exe+10225CB - 48 8B 05 0E 50 D1 02  - mov rax,[TME-Win64-Shipping.exe+3D375E0]
		--TME-Win64-Shipping.exe+10225D2 - 32 DB                 - xor bl,bl
		--TME-Win64-Shipping.exe+10225D4 - 8B 48 04              - mov ecx,[rax+04]
		--TME-Win64-Shipping.exe+10225D7 - 66 C7 44 24 50 01 01  - mov word ptr [rsp+50],0101
		--TME-Win64-Shipping.exe+10225DE - 85 C9                 - test ecx,ecx
	end
	
	local tAddress = HackTool:AddAddress("FRINGE")
	
	if HackTool:SignatureScan("7F ?? 89 B3 ?? ?? ?? ?? 8B ?? ?? 39 05",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TME-Win64-Shipping.exe+19C5CBA - 48 8B 05 0F A8 41 02  - mov rax,[TME-Win64-Shipping.exe+3DE04D0]
		--TME-Win64-Shipping.exe+19C5CC1 - 39 30                 - cmp [rax],esi
		--TME-Win64-Shipping.exe+19C5CC3 - 7F 06                 - jg TME-Win64-Shipping.exe+19C5CCB
		--TME-Win64-Shipping.exe+19C5CC5 - 89 B3 FC 0F 00 00     - mov [rbx+00000FFC],esi
		--TME-Win64-Shipping.exe+19C5CCB - 8B 04 2F              - mov eax,[rdi+rbp]
	end

	return true

end


function Enable_Inject()

	if bAspect == true then
		fAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
	end

	local Variables = HackTool:AllocateMemory("Variables",0)
	Variables:PushFloat("FOVIn")
	Variables:PushFloat("FOVOut")
	Variables:PushFloat("CompensatedFOV")
	Variables:PushFloat("AdditionalFOV")
	Variables:PushFloat("DefaultAspectRatio")
	Variables:PushFloat("ScreenAspect")
	Variables:PushFloat("AspectRatio")
	Variables:PushFloat("factor")
	
	Variables:Allocate()
	Variables["FOVIn"]:WriteFloat(fDefaultFOV)
	Variables["AdditionalFOV"]:WriteFloat(fAdditionalFOV)
	Variables["DefaultAspectRatio"]:WriteFloat(fDefaultAspectRatio)
	Variables["AspectRatio"]:WriteFloat(fAspectRatio)
	Variables["ScreenAspect"]:WriteFloat(DisplayInfo:GetWidth() / DisplayInfo:GetHeight())
	Variables["factor"]:WriteFloat(fFactor)
	

	
	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->AspectRatio]
			fdiv dword ptr [(allocation)Variables->DefaultAspectRatio]
			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 $$2,[(allocation)Variables->ScreenAspect]				$ctx=1
			%originalcode%
			jmp %returnaddress%
			%end%
			
		(codecave)DOF,DOF_cc:
			xor $$1,$$1													$ctx=1
			nop
			%end%
			
		(codecave)FRINGE,FRINGE_cc:
			nop
			nop
			%end%
			
	]]

	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("DOF_cc",bDOF)
		Toggle_CodeCave("FRINGE_cc",bFringe)
	end	
			
	Write_FOV()
	
end

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

function FOVSlider_Changed(Sender)

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

end

function Write_FOV()

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

end

function Disable_Inject()
	
	CleanUp()
	
end

function CKFOVFix_Changed(Sender)

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

function CKARFix_Changed(Sender)

	bAspect = Toggle_CheckFix(Sender)
	Toggle_CodeCave("ASPECT_cc",bAspect)
	fAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
	
	if bAspect == false then
		fAspectRatio = fDefaultAspectRatio
	end
	
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["AspectRatio"] then
		Variables["AspectRatio"]:WriteFloat(fAspectRatio)
	end
	
	ForceUpdate()

end

function CKDOFFix_Changed(Sender)

	bDOF = Toggle_CheckFix(Sender)
	Toggle_CodeCave("DOF_cc",bDOF)
	ForceUpdate()
	
end

function CKFRINGEFix_Changed(Sender)

	bFringe = Toggle_CheckFix(Sender)
	Toggle_CodeCave("FRINGE_cc",bFringe)
	ForceUpdate()
	
end

function ResolutionChanged() 

	SyncDisplayDetection()
	
end

function Init()

	Init_BaseControls()
	Init_Controls()

end

function DeInit()

	DisableFix()

end
