--HOOKS
-- https://www.blast.hk/threads/39138
local hook = {hooks = {}}
addEventHandler('onScriptTerminate', function(scr)
if scr == script.this then
for i, hook in ipairs(hook.hooks) do
if hook.status then
hook.stop()
end
end
end
end)
ffi.cdef [[
int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect);
]]
function hook.new(cast, callback, hook_addr, size)
jit.off(callback, true) --off jit compilation | thx FYP
local size = size or 5
local new_hook = {}
local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback))))
local void_addr = ffi.cast('void*', hook_addr)
local old_prot = ffi.new('unsigned long[1]')
local org_bytes = ffi.new('uint8_t[?]', size)
ffi.copy(org_bytes, void_addr, size)
local hook_bytes = ffi.new('uint8_t[?]', size, 0x90)
hook_bytes[0] = 0xE9
ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5
new_hook.call = ffi.cast(cast, hook_addr)
new_hook.status = false
local function set_status(bool)
new_hook.status = bool
ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot)
ffi.copy(void_addr, bool and hook_bytes or org_bytes, size)
ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot)
end
new_hook.stop = function() set_status(false) end
new_hook.start = function() set_status(true) end
new_hook.start()
table.insert(hook.hooks, new_hook)
return setmetatable(new_hook, {
__call = function(self, ...)
self.stop()
local res = self.call(...)
self.start()
return res
end
})
end
--HOOKS
-- Constants
local SAMP_BASE = getModuleHandle('samp.dll')
local DRAW_HEALTH_BAR_FUNC_ADDRESS = SAMP_BASE + 0x689C0
local END_HEALTH_BAR_FUNC_ADDRESS = SAMP_BASE + 0x68670
local SAMP_OFFSET = {0x68610, 0x70F96, 0x68F70, 0x68FA0, 0x21A0FC, 0x66E00, 0x66BD0, 0x12C980, 0x12C940, 0x21A0EC, 0x65F10, 0x9A7D0, 0x70E10, 0x6FD00}
-- Function Signatures
local drawHealthBarFunc = ffi.cast("void(__thiscall*)(void*, CVector*, float, float, float)", DRAW_HEALTH_BAR_FUNC_ADDRESS)
local getBonePositionFunc = ffi.cast("int (__thiscall*)(void*, float*, int, bool)", 0x5E4280)
-- Global Variables
local textId = 2014
local position = ffi.new("CVector")
local size = ffi.new("SIZE")
-- Helper Function to Measure Text Size
-- раньше крашила игру в рандомные моменты... требует тестов короч, вот так вот бля :(
-- _DWORD __thiscall CFonts::GetLittleTextScreenSize(CFonts this, _DWORD pSize, const char szText, int nFormat)
local function sampGetMeasuredTextSize(text)
local getTextSizeFuncAddr = SAMP_BASE + SAMP_OFFSET[7]
local getTextSizeFunc = ffi.cast("void (__thiscall)(void, SIZE, const char, int)", getTextSizeFuncAddr)
local fontsInstancePtr = ffi.cast("void**", SAMP_BASE + SAMP_OFFSET[5])[0]
Assistant
User
Assistant
code
size.cx, size.cy = 0, 0
local flags = bit.bor(0x00000000, 0x00000100) -- DT_LEFT and DT_NOCLIP
getTextSizeFunc(fontsInstancePtr, size, text, flags)
return size
end
-- Correction Function for Vertical Alignment
local function verticalAlignmentCorrection(x)
return 0.84 + 0.0216625 * (x - 10)
end
-- Get Body Part Coordinates
local function getBodyPartCoordinates(boneId, pedHandle)
local pedPointer = getCharPointer(pedHandle)
local coordinates = ffi.new("float[3]")
getBonePositionFunc(ffi.cast("void*", pedPointer), coordinates, boneId, true)
return coordinates[0], coordinates[1], coordinates[2]
end
-- Hook for customizing EndHealthBar
local function EndHealthBarHook(playerTags)
if sampIs3dTextDefined(textId) then
sampDestroy3dText(textId)
end
code
if sampIs3dTextDefined(textId + 1) then
sampDestroy3dText(textId + 1)
end
local charX, charY, charZ = getCharCoordinates(playerPed)
local limbX, limbY, limbZ = getBodyPartCoordinates(8, playerPed)
local cameraX, cameraY, cameraZ = getActiveCameraCoordinates()
local cameraDistance = getDistanceBetweenCoords3d(charX, charY, charZ, cameraX, cameraY, cameraZ)
local result, id = sampGetPlayerIdByCharHandle(playerPed)
if not result then
print("sampGetPlayerIdByCharHandle error in EndHealthBarHook"); return EndHealthBar(playerTags)
end
local nickname = sampGetPlayerNickname(id)
local color = sampGetPlayerColor(id)
local text = string.format("%s (%d)", nickname, id) --"{ffffff}pururin (30)"
local measuredSize = sampGetMeasuredTextSize(text)
local offset = verticalAlignmentCorrection(measuredSize.cy)
position.x,
position.y,
position.z = limbX, limbY, limbZ
local health = sampGetPlayerHealth(id)
local armor = sampGetPlayerArmor(id)
drawHealthBarFunc(playerTags, position, health, armor, cameraDistance)
limbZ = limbZ + 0.21 + ((cameraDistance * 0.047499999) * offset)
local limbZ2 = limbZ + ((cameraDistance * 0.047499999) * offset) / 2
sampCreate3dTextEx(textId, text, color, limbX, limbY, limbZ, 600, false, -1, -1)
sampCreate3dTextEx(textId + 1, "{d0aeeb} * смотрите, я ролевик", 0xFFFFFFFF, limbX, limbY, limbZ2, 600, false, -1, -1)
return EndHealthBar(playerTags)
end
-- Main Function to Initialize the Hook
function main()
while not isPlayerPlaying(playerPed) do
wait(100)
end
добавь МАКСИМУМ дебажных принтов. не меняй сам код
To add maximum debugging prints to the code without altering its functionality, you can insert print statements at key points in the code. This will help trace the flow of execution and display the values of important variables at each step.
Here's how you can do it:
lua
local ffi = require 'ffi'
-- FFI Definitions
ffi.cdef[[
typedef struct {
float x;
float y;
float z;
} CVector;
typedef struct {
long cx;
long cy;
} SIZE;
]]
--HOOKS
print("Setting up hooks...")
local hook = {hooks = {}}
addEventHandler('onScriptTerminate', function(scr)
print("Script termination event triggered")
if scr == script.this then
for i, hook in ipairs(hook.hooks) do
print("Disabling hook", i)
if hook.status then
hook.stop()
end
end
end
end)
ffi.cdef [[
int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect);
]]
print("Hook setup defined.")
function hook.new(cast, callback, hook_addr, size)
print("Creating new hook...")
jit.off(callback, true) --off jit compilation | thx FYP
local size = size or 5
local new_hook = {}
local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback))))
local void_addr = ffi.cast('void*', hook_addr)
local old_prot = ffi.new('unsigned long[1]')
local org_bytes = ffi.new('uint8_t[?]', size)
ffi.copy(org_bytes, void_addr, size)
local hook_bytes = ffi.new('uint8_t[?]', size, 0x90)
hook_bytes[0] = 0xE9
ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5
new_hook.call = ffi.cast(cast, hook_addr)
new_hook.status = false
local function set_status(bool)
print("Changing hook status to", bool)
new_hook.status = bool
ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot)
ffi.copy(void_addr, bool and hook_bytes or org_bytes, size)
ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot)
end
new_hook.stop = function() set_status(false) end
new_hook.start = function() set_status(true) end
new_hook.start()
table.insert(hook.hooks, new_hook)
print("New hook created and started.")
return setmetatable(new_hook, {
__call = function(self, ...)
print("Calling hooked function...")
self.stop()
local res = self.call(...)
self.start()
print("Hooked function call complete.")
return res
end
})
end
print("Hooks initialized.")
-- Constants
print("Setting up constants...")
local SAMP_BASE = getModuleHandle('samp.dll')
local DRAW_HEALTH_BAR_FUNC_ADDRESS = SAMP_BASE + 0x689C0
local END_HEALTH_BAR_FUNC_ADDRESS = SAMP_BASE + 0x68670
local SAMP_OFFSET = {0x68610, 0x70F96, 0x68F70, 0x68FA0, 0x21A0FC, 0x66E00, 0x66BD0, 0x12C980, 0x12C940, 0x21A0EC, 0x65F10, 0x9A7D0, 0x70E10, 0x6FD00}
-- Function Signatures
print("Function signatures...")
local drawHealthBarFunc = ffi.cast("void(__thiscall*)(void*, CVector*, float, float, float)", DRAW_HEALTH_BAR_FUNC_ADDRESS)
local getBonePositionFunc = ffi.cast("int (__thiscall*)(void*, float*, int, bool)", 0x5E4280)
-- Global Variables
print("Initializing global variables...")
local textId = 2014
local position = ffi.new("CVector")
local size = ffi.new("SIZE")
-- Helper Function to Measure Text Size
local function sampGetMeasuredTextSize(text)
print("Measuring text size for:", text)
local getTextSizeFuncAddr = SAMP_BASE + SAMP_OFFSET[7]
local getTextSizeFunc = ffi.cast("void (__thiscall*)(void*, SIZE*, const char*, int)", getTextSizeFuncAddr)
local fontsInstancePtr = ffi.cast("void**", SAMP_BASE + SAMP_OFFSET[5])[0]
size.cx, size.cy = 0, 0
local flags = bit.bor(0x00000000, 0x00000100) -- DT_LEFT and DT_NOCLIP
getTextSizeFunc(fontsInstancePtr, size, text, flags)
print("Measured size:", size.cx, size.cy)
return size
end
-- Correction Function for Vertical Alignment
local function verticalAlignmentCorrection(x)
local correction = 0.84 + 0.0216625 * (x - 10)
print("Vertical alignment correction:", correction)
return correction
end
-- Get Body Part Coordinates
local function getBodyPartCoordinates(boneId, pedHandle)
print("Getting body part coordinates...")
local pedPointer = getCharPointer(pedHandle)
local coordinates = ffi.new("float[3]")
getBonePositionFunc(ffi.cast("void*", pedPointer), coordinates, boneId, true)
print("Coordinates:", coordinates[0], coordinates[1], coordinates[2])
return coordinates[0], coordinates[1], coordinates[2]
end
-- Hook for customizing EndHealthBar
local function EndHealthBarHook(playerTags)
print("Running EndHealthBarHook...")
if sampIs3dTextDefined(textId) then
sampDestroy3dText(textId)
print("Destroyed 3D text with ID", textId)
end
if sampIs3dTextDefined(textId + 1) then
sampDestroy3dText(textId + 1)
print("Destroyed 3D text with ID", textId + 1)
end
local charX, charY, charZ = getCharCoordinates(playerPed)
local limbX, limbY, limbZ = getBodyPartCoordinates(8, playerPed)
local cameraX, cameraY, cameraZ = getActiveCameraCoordinates()
local cameraDistance = getDistanceBetweenCoords3d(charX, charY, charZ, cameraX, cameraY, cameraZ)
print("Camera distance:", cameraDistance)
local result, id = sampGetPlayerIdByCharHandle(playerPed)
if not result then
print("sampGetPlayerIdByCharHandle error in EndHealthBarHook")
return EndHealthBar(playerTags)
end
local nickname = sampGetPlayerNickname(id)
local color = sampGetPlayerColor(id)
print("Player ID:", id, "Nickname:", nickname, "Color:", color)
local text = string.format("%s (%d)", nickname, id)
local measuredSize = sampGetMeasuredTextSize(text)
local offset = verticalAlignmentCorrection(measuredSize.cy)
position.x, position.y, position.z = limbX, limbY, limbZ
local health = sampGetPlayerHealth(id)
local armor = sampGetPlayerArmor(id)
print("Health:", health, "Armor:", armor)
drawHealthBarFunc(playerTags, position, health, armor, cameraDistance)
limbZ = limbZ + 0.21 + ((cameraDistance * 0.047499999) * offset)
local limbZ2 = limbZ + ((cameraDistance * 0.047499999) * offset) / 2
sampCreate3dTextEx(textId, text, color, limbX, limbY, limbZ, 600, false, -1, -1)
sampCreate3dTextEx(textId + 1, "{d0aeeb} * смотрите, я ролевик", 0xFFFFFFFF, limbX, limbY, limbZ2, 600, false, -1, -1)
print("EndHealthBarHook finished.")
return EndHealthBar(playerTags)
end
-- Main Function to Initialize the Hook
function main()
print("Waiting for player to start playing...")
while not isPlayerPlaying(playerPed) do
wait(100)
end
print("Player is playing. Initializing EndHealthBar hook...")
EndHealthBar = hook.new(
'void* (__thiscall *)(void *this)',
EndHealthBarHook,
END_HEALTH_BAR_FUNC_ADDRESS
)
print("EndHealthBar hook initialized.")
end
print("Script loaded.")
This version of the script prints detailed information at various execution points, which will help track the flow and values of variables during execution. This kind of logging is crucial for debugging complex code, especially when dealing with FFI and game modification scripts.
function get_samp_version()
if (samp_base == nil or samp_base == 0) then samp_base = getModuleHandle("samp.dll") end;
if (samp_base ~= 0) then
local entry_point_addr = ffi.cast("unsigned int*", samp_base + ffi.cast("long*", samp_base + 60)[0] + 40)[0];
local versions = {
[0x31DF13] = 'r1',
[0xCC4D0] = 'r3'
};
return versions[entry_point_addr] or nil;
end
end
function GetTextScreenSize(str)
local size = ffi.new("unsigned int[1]", 0)
CFonts__GetTextScreenSize(ffi.cast("void**", samp + addr.RefFontRenderer)[0], size, str, 1)
return size[0]
end
function getUrl(text)
local this = {
status = false,
link = '',
size = 0,
domain = '',
protocol = '',
path = '',
before = { text = '', size = 0 },
after = { text = '', size = 0 }
}
if text:find('https?://.-%..-') or text:find('.-%..-') then
for , v in ipairs(domainZones) do
if text:find('.-%.' .. v .. '[%s%p]') or text:find('.-%.' .. v .. '/') or text:find('.-%.' .. v .. '′)thenif(text')) or (text:find(text:find('^.-%.' .. v) and '^' or '[^A-Za-zА-Яа-я0-9]') .. '.-%.' .. v .. (text:find('.-%.' .. v .. '[/.-])') then
this.protocol, this.domain, this.path = text:match('(https?)://(.-)%.' .. v .. '([/%a+%-%.%%~%%?%x+=]$', '')
this.link = (#this.protocol > 0 and this.protocol .. '://' or '') .. ('%s.%s'):format(this.domain, v) .. (this.path and this.path or '') local subdomain
if this.domain:find('%.') then
this.subdomain, this.domain = this.domain:reverse():gsub('[A-Za-zА-Яа-я%.%-]-%.', '', 1):reverse(), this.domain:reverse():match('([A-Za-zА-Яа-я%.%-]-)%.'):reverse()
end
local before, after = text:match(('(.-)%s(.*)'):format(this.link:find('%-') and this.link:gsub('%-', '%%-') or this.link))
this.before = {
text = before or '',
size = before and GetTextScreenSize(before) or 0
}
print('BEF:', this.before.text, this.before.size, text)
code
this.size = this.link and GetTextScreenSize(this.link) or 0
this.status = true
break
end
end
end
end
return this
end
function CChat__RenderEntry(this, text, x1, y1, x2, y2, color)
if y2 - y1 < 25 then
for k, v in ipairs(lines) do if v.from.y == y1 then table.remove(lines, k) end end
local str = ffi.string(text)
if #str > 0 and not str:find('^%[%d%d:%d%d:%d%d%]$') then
local urlData = getUrl(str)
if urlData.status then
table.insert(lines, {
from = imgui.ImVec2(x1, y1),
to = imgui.ImVec2(x2, y2),
URL = urlData
})
print('added')
end
end
end
CChat_RenderEntry(this, text, x1, y1, x2, y2, color)
end
function f2(...)
print(f2, ...)
f1(...)
end
function main()
while not isSampAvailable() do wait(0) end
f1 = hook.call.new("void(__thiscall*)(void*, unsigned int*, const char*, int)", f2, getModuleHandle('samp.dll') + addr.GetTextScreenSize)
-- sampAddChatMessage('[Сообщение] Вениамин (300 метров от вас): куплю пива, напишу луа скрипт и возьму в рот, пиши: t.me/venibon', -1)
CChat_RenderEntry = hook.jmp.new('void(__thiscall *)(void , const char, int, int, int, int, uint32_t)', CChat__RenderEntry, getModuleHandle('samp.dll') + addr.RenderEntry) -- CChat::RenderEntry
wait(-1)
end
local frame = imgui.OnFrame(
function() return isSampAvailable() end,
function(self)
self.HideCursor = true
local DL = imgui.GetBackgroundDrawList()
local cur = imgui.ImVec2(getCursorPos())
for index, data in ipairs(lines) do
local chatXOffset = data.from.x
local urlHovered = (cur.x > chatXOffset + data.URL.before.size and cur.x < chatXOffset + data.URL.before.size + data.URL.size) and (cur.y > data.from.y and cur.y < data.to.y)
DL:AddLine(imgui.ImVec2(chatXOffset + data.URL.before.size, data.to.y), imgui.ImVec2(chatXOffset + data.URL.before.size + data.URL.size, data.to.y), urlHovered and 0xFFffa85c or 0xFFff9130, 2)
if urlHovered and imgui.IsMouseClicked(0) then
URL = #data.URL.protocol == 0 and 'https://'..data.URL.link or data.URL.link
imgui.OpenPopup(u8'Переход по ссылке##'..tostring(index))
end
code
imgui.PushStyleVarVec2(imgui.StyleVar.WindowPadding, imgui.ImVec2(5, 5))
if imgui.BeginPopupModal(u8'Переход по ссылке##'..tostring(index), nil, imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.NoTitleBar) then
local winSize = imgui.GetWindowSize()
imgui.Text(u8'Вы действительно хотите перейти по ссылке')
imgui.CenterText(URL or 'undefined', imgui.ImVec4(0.2, 0.3, 1, 1))
local buttonSize = imgui.ImVec2(winSize.x - 10, 20)
if imgui.Button(u8'Перейти', buttonSize) then
os.execute('start '..URL)
imgui.CloseCurrentPopup()
end
if imgui.Button(u8'Отмена', buttonSize) then
imgui.CloseCurrentPopup()
end
imgui.EndPopup()
end
imgui.PopStyleVar()
end
end
)
function imgui.CenterText(text, color)
imgui.SetCursorPosX(imgui.GetWindowSize().x / 2 - imgui.CalcTextSize(text).x / 2)
imgui.TextColored(color or imgui.ImVec4(1, 1, 1, 1), text)
end
The provided Lua script is quite complex and involves the use of several libraries, including FFI (Foreign Function Interface), hooks, imgui (Immediate Mode Graphical User Interface), and encoding. The script is for a game modification, likely for the popular game Grand Theft Auto: San Andreas with the SA-MP (San Andreas Multiplayer) mod. This script seems to handle the extraction and interaction with URLs found in chat messages within the game. Let's break down the key components:
Key Components of the Script:
FFI and Hooks:
The script uses ffi to interface with C functions and structures directly. This allows Lua to interact with game memory, such as calling functions from the game's DLLs (samp.dll).
hook library is used to set hooks on certain functions, allowing you to intercept and modify function calls within the game.
SA-MP Version Check:
The script checks the SA-MP version to set the appropriate address offsets for certain functions.
Function Wrapping:
CFonts__GetTextScreenSize and CFonts__RefFontRenderer are wrapped to calculate text sizes within the game. This is crucial for determining the position and size of URLs in chat messages.
Domain Zone Handling:
A list of domain zones is provided to identify potential links in chat messages. This part of the script attempts to extract URLs from the message text based on these recognized domain zones.
Chat Rendering and URL Detection:
CChat__RenderEntry is a function hook that intercepts chat rendering calls. It analyzes each message to detect URLs and stores their details.
Mouse Interaction:
Uses imgui to render graphics and handle mouse interactions. This is essential for detecting hover and click events on URLs in the chat interface.
URL Handling:
If a URL is detected and the user clicks on it, a modal popup is initiated to confirm the transition. On confirmation, it uses os.execute to open a web browser with the clicked link.
Main Function:
Sets up initial hooks and waits for the game and SA-MP to become available. Once ready, it sets hooks on the GetTextScreenSize and RenderEntry functions.
How It Works:
URL Detection: The script scans text messages for potential URLs based on known domain zones and formats.
Hook Management: It hooks into render functions to detect when and where URL-related text appears within the game.
Interactive UI: Using imgui, it provides user interaction for clicking and confirming URL navigation.
Debugging Prints: To debug or trace the execution, you can insert print statements at key points, such as when URLs are detected or when a URL is opened.
Debugging Tips:
To debug this script effectively, you should consider adding print statements at strategic locations:
After checking or matching URL patterns in getUrl.
Before and after calling important functions (especially those using ffi.cast and hook).
When user interactions occur in the imgui OnFrame function.
This approach allows you to follow the logic step by step and see the values of variables, which could help identify issues or verify the script's correct operation.
Not yet included in a published release.
:
find((text:
find(′https?:
//.−
.') and '[^A-Za-zА-Яа-я0-9]' or '′)))theniftext:find(′https?://.−%?%x+=]