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

--GAME VARS
fDefaultFOV = 80
fAdditionalFOV = 0
fScreenAspectRatio = DisplayInfo:GetWidth() / DisplayInfo:GetHeight()
fScreenAspectRatio169 = 1.77778
fFactor = 0.00872665

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

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

	DefaultControls.AddHeader("Header_HUD_SZ_LEFT","HUD safe zone left",15,190,210,17)	
	DefaultControls.AddFixedFOVSlider("HUD_SZ_LEFT","HUDSZLSlider_Changed",55,220,125,35,0,40,0,1)
	HUD_SZ_LEFT:SetTickFrequency(5)
	HUD_SZ_LEFT:SetLabel1Text("0")
	HUD_SZ_LEFT:SetLabel2Text("40")
	DefaultControls.AddHeader("Header_HUDSZRIGHT","HUD safe zone right",245,190,210,17)	
	DefaultControls.AddFixedFOVSlider("HUD_SZ_RIGHT","HUDSZRSlider_Changed",285,220,125,35,0,40,0,1)
	HUD_SZ_RIGHT:SetTickFrequency(5)
	HUD_SZ_RIGHT:SetLabel1Text("0")
	HUD_SZ_RIGHT: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("CKDOFFix_Enable","Depth of field fix","CKDOFFix_Changed",255,141,180,14)
	DefaultControls.AddFixToggle("CKHUDFix_Enable","HUD safe zone fix","CKHUDFix_Changed",255,161,100,14)

end

function Configure_SignatureScan() 
	
	local tAddress = HackTool:AddAddress("FOV")
	
	if HackTool:SignatureScan("E8 ?? ?? ?? ?? 0F ?? ?? 48 8B ?? ?? ?? ?? ?? ?? 48 ?? ?? E8 ?? ?? ?? ?? 0F 28 ?? ?? ?? ?? ?? ?? 48 81 ?? ?? ?? ?? ?? C3",tAddress,PAGE_EXECUTE_READ,0x05,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TSCGame-Win64-Shipping.exe+16730C0 - 74 05                 	- je TSCGame-Win64-Shipping.exe+16730C7
		--TSCGame-Win64-Shipping.exe+16730C2 - E8 A9 9D 02 FF           - call TSCGame-Win64-Shipping.exe+69CE70
		--TSCGame-Win64-Shipping.exe+16730C7 - 0F 28 C6               	- movaps xmm0,xmm6
		--TSCGame-Win64-Shipping.exe+16730CA - 48 8B 8C 24 A0 05 00 00  - mov rcx,[rsp+000005A0]
		--TSCGame-Win64-Shipping.exe+16730D2 - 48 33 CC              	- xor rcx,rsp
	end

	local tAddress = HackTool:AddAddress("ASPECT")
	
	if HackTool:SignatureScan("CC CC CC 48 ?? ?? ?? ?? 57 48 ?? ?? ?? F2 ?? ?? ?? 48 ?? ?? F2 ?? ?? ?? 48 ?? ?? 8B ?? ?? 89 ?? ?? F2 ?? ?? ?? ?? F2 ?? ?? ?? ?? 8B ?? ?? 89 ?? ?? 8B ?? ?? 89 ?? ?? 8B ?? ?? 89 ?? ??",tAddress,PAGE_EXECUTE_READ,0x52,Process_EXEName) == 0 then
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--ASC-Win64-Shipping.exe+165AA40 - 8B 42 44              - mov eax,[rdx+44]
		--ASC-Win64-Shipping.exe+165AA43 - 89 41 44              - mov [rcx+44],eax
		--ASC-Win64-Shipping.exe+165AA46 - 8B 42 48              - mov eax,[rdx+48]
		--ASC-Win64-Shipping.exe+165AA49 - 89 41 48              - mov [rcx+48],eax
		--ASC-Win64-Shipping.exe+165AA4C - 8B 49 4C              - mov ecx,[rcx+4C]
	end

	local tAddress = HackTool:AddAddress("DOF")
	
	if HackTool:SignatureScan("8B ?? ?? 66 C7 ?? ?? ?? ?? ?? 85 ??",tAddress,PAGE_EXECUTE_READ,0x0,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TSCGame-Win64-Shipping.exe+D5B230 - 48 8B 05 09 CF 50 02  - mov rax,[TSCGame-Win64-Shipping.exe+3268140]
		--TSCGame-Win64-Shipping.exe+D5B237 - 32 DB                 - xor bl,bl
		--TSCGame-Win64-Shipping.exe+D5B239 - 8B 48 04              - mov ecx,[rax+04]
		--TSCGame-Win64-Shipping.exe+D5B23C - 66 C7 44 24 40 01 01  - mov word ptr [rsp+40],0101
		--TSCGame-Win64-Shipping.exe+D5B243 - 85 C9                 - test ecx,ecx
	end

	local tAddress = HackTool:AddAddress("HUDSAFEZONE")
	
	if HackTool:SignatureScan("48 ?? ?? 48 ?? ?? 66 48 ?? ?? ?? FF ?? 48 8B ?? ?? ?? 0F ?? ??",tAddress,PAGE_EXECUTE_READ,0x18,Process_EXEName) == 0 then	
		return ErrorOccurred(string.format(SigScanError,tAddress:GetName()))
	else	
		print( tAddress:GetInfo(TYPE_ADDRESS) )
		--TSCGame-Win64-Shipping.exe+D5B230 - 48 8B 05 09 CF 50 02  - mov rax,[TSCGame-Win64-Shipping.exe+3268140]
		--TSCGame-Win64-Shipping.exe+D5B237 - 32 DB                 - xor bl,bl
		--TSCGame-Win64-Shipping.exe+D5B239 - 8B 48 04              - mov ecx,[rax+04]
		--TSCGame-Win64-Shipping.exe+D5B23C - 66 C7 44 24 40 01 01  - mov word ptr [rsp+40],0101
		--TSCGame-Win64-Shipping.exe+D5B243 - 85 C9                 - test ecx,ecx
	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("DefaultAspectRatio")
	Variables:PushFloat("ScreenRatio")
	Variables:PushFloat("factor")
	Variables:PushFloat("HUDSafeZoneLeft")
	Variables:PushFloat("HUDSafeZoneTop")
	Variables:PushFloat("HUDSafeZoneRight")
	Variables:PushFloat("HUDSafeZoneBottom")
	Variables:Allocate()
	Variables["FOVIn"]:WriteFloat(fDefaultFOV)
	Variables["FOVOut"]:WriteFloat(fDefaultFOV)
	Variables["AdditionalFOV"]:WriteFloat(fAdditionalFOV)
	Variables["DefaultAspectRatio"]:WriteFloat(fScreenAspectRatio169)
	Variables["ScreenRatio"]:WriteFloat(fScreenAspectRatio)
	Variables["factor"]:WriteFloat(fFactor)
	Variables["HUDSafeZoneLeft"]:WriteFloat(0)
	Variables["HUDSafeZoneTop"]:WriteFloat(0)
	Variables["HUDSafeZoneRight"]:WriteFloat(1)
	Variables["HUDSafeZoneBottom"]:WriteFloat(1)
	
	ResolutionChanged()	

	local asm = [[	

		(codecave:jmp)FOV,FOV_cc:			
			%originalcode%
			movss [(allocation)Variables->FOVIn],$$1					$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->DefaultAspectRatio]
			fmulp st1,st0
			fld1
			fpatan
			fdiv dword ptr [(allocation)Variables->factor]
			fst dword ptr [(allocation)Variables->CompensatedFOV]
			fadd dword ptr [(allocation)Variables->AdditionalFOV]
			fstp dword ptr [(allocation)Variables->FOVOut]
			movss $$1,[(allocation)Variables->FOVOut]					$ctx=1
			jmp %returnaddress%
			%end%
									
		(codecave:jmp)ASPECT,ASPECT_cc:
		    $$0 $$2,[(allocation)Variables->ScreenRatio]				$ctx=1
			%originalcode%
			jmp %returnaddress%
			%end%
						
		(codecave:jmp)DOF,DOF_cc:
			%originalcode%
		    $$0 $$1,0													$ctx=1
			jmp %returnaddress%
			%end%
			
		(codecave:jmp)HUDSAFEZONE,HUDSAFEZONE_cc:
			%originalcode%
			$$0 $$2,[(allocation)Variables->HUDSafeZoneLeft]		$ctx=1 ; Will copy all safe zone offsets
			$$0 [$$1],$$2											$ctx=1
			jmp %returnaddress%			
			%end%
			
	]]

	if HackTool:CompileAssembly(asm,"Fixes") == nil then
		return ErrorOccurred("Assembly compilation failed...")
	else
		Toggle_CodeCave("FOV_cc",bFixEnabled)
		Toggle_CodeCave("ASPECT_cc",bAspect)
		Toggle_CodeCave("DOF_cc",bDOF)
		Toggle_CodeCave("HUDSAFEZONE_cc",bHUDSafeZone)
	end	
			
	Write_FOV()
	WriteAR()
	Write_HUD_Safe_Zone_Left()
	Write_HUD_Safe_Zone_Right()

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: %0.2f, Compensated FOV : %0.2f, FOV Out : %.02f", fFOVIn, fCompensatedFOV, fFOVOut))
	end
end

function FOVSlider_Changed(Sender)

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

end

function Write_FOV()

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

end

function WriteAR()

	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["AdditionalFOV"] then
		if bAspect == true then
			Variables["DefaultAspectRatio"]:WriteFloat(fScreenAspectRatio169)
		else
			Variables["DefaultAspectRatio"]:WriteFloat(fScreenAspectRatio)
		end
	end
	
end

function Write_HUD_Safe_Zone_Left()
	
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["HUDSafeZoneLeft"] then
		Variables["HUDSafeZoneLeft"]:WriteFloat(fHUDSafeZOneLeft / 100)
	end
	
end

function Write_HUD_Safe_Zone_Right()
	
	local Variables = HackTool:GetAllocation("Variables")
	
	if Variables and Variables["HUDSafeZoneRight"] then
		Variables["HUDSafeZoneRight"]:WriteFloat(1 - (fHUDSafeZoneRight / 100))
	end
	
end

function Disable_Inject()
	
	CleanUp()
	
end

function CKFOVFix_Changed(Sender)

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

function CKARFix_Changed(Sender)

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

function CKDOFFix_Changed(Sender)

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

end

function CKHUDFix_Changed(Sender)

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

end

function HUDSZLSlider_Changed(Sender)
	
	fHUDSafeZOneLeft = Sender:GetPosition()
	lblHUD_SZ_LEFT.Caption:SetCaption( string.format("+ %.0f %%",fHUDSafeZOneLeft) )
	Write_HUD_Safe_Zone_Left()
	ForceUpdate()
	
end

function HUDSZRSlider_Changed(Sender)

	fHUDSafeZoneRight = Sender:GetPosition()
	lblHUD_SZ_RIGHT.Caption:SetCaption( string.format("+ %.0f %%",fHUDSafeZoneRight) )
	Write_HUD_Safe_Zone_Right()
	ForceUpdate()
	
end

function ResolutionChanged() 

	SyncDisplayDetection()
	
end

function Init()

	Init_BaseControls()
	Init_Controls()

end

function DeInit()

	DisableFix()

end
