Проведи код-ревью и аудит кода. Произведи Рефакторинг и Профилирование кода. [code]
- User
Проведи код-ревью и аудит кода. Произведи Рефакторинг и Профилирование кода.
lua - Assistant
Проведи код-ревью и аудит кода. Произведи Рефакторинг и Профилирование кода.
require 'lib.moonloader'
local imgui = require('imgui')
local vkeys = require('vkeys')
local ffi = require('ffi')
local getbonePosition = ffi.cast("int (__thiscall*)(void*, float*, int, bool)", 0x5E4280)
local stun_anims = {'DAM_armL_frmBK', 'DAM_armL_frmFT', 'DAM_armL_frmLT', 'DAM_armR_frmBK', 'DAM_armR_frmFT', 'DAM_armR_frmRT', 'DAM_LegL_frmBK', 'DAM_LegL_frmFT', 'DAM_LegL_frmLT', 'DAM_LegR_frmBK', 'DAM_LegR_frmFT', 'DAM_LegR_frmRT', 'DAM_stomach_frmBK', 'DAM_stomach_frmFT', 'DAM_stomach_frmLT', 'DAM_stomach_frmRT'}
local mainWindowState = imgui.ImBool(false)
local smooth = imgui.ImFloat(0.0)
local radius = imgui.ImFloat(0.6)
local enable = imgui.ImBool(false)
local clistFilter = imgui.ImBool(false)
local visibleCheck = imgui.ImBool(false)
local checkStuned = imgui.ImBool(false)
local checkPause = imgui.ImBool(false)
function main()
repeat wait(0) until isSampAvailable()
lua_thread.create(smooth_aimbot)
while true do
wait(0)
if wasKeyPressed(vkeys.VK_INSERT) then
mainWindowState.v = not mainWindowState.v
end
imgui.Process = mainWindowState.v
end
end
function imgui.OnDrawFrame()
local posX, posY = getScreenResolution()
if mainWindowState.v then
imgui.SetNextWindowPos(imgui.ImVec2(posX / 2, posY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
imgui.SetNextWindowSize(imgui.ImVec2(350, 200), imgui.Cond.FirstUseEver)
imgui.Begin('Smooth aimbot', mainWindowState)
imgui.SliderFloat('Radius', radius, 0.0, 100.0, '%.1f')
imgui.SliderFloat('Smooth', smooth, 0.0, 50.0, '%.1f')
imgui.Checkbox('Enable', enable)
imgui.Checkbox('VisibleCheck', visibleCheck)
imgui.Checkbox('CheckStuned', checkStuned)
imgui.Checkbox('ClistFilter', clistFilter)
imgui.Checkbox('CheckPause', checkPause)
imgui.End()
end
end
function fix(angle)
if angle > math.pi then
angle = angle - (math.pi * 2)
elseif angle < -math.pi then
angle = angle + (math.pi * 2)
end
return angle
end
function GetNearestPed(fov)
local maxDistance = 35
local nearestPED = -1
for i = 0, sampGetMaxPlayerId(true) do
if sampIsPlayerConnected(i) then
local find, handle = sampGetCharHandleBySampPlayerId(i)
if find then
if isCharOnScreen(handle) then
if not isCharDead(handle) then
local _, currentID = sampGetPlayerIdByCharHandle(PLAYER_PED)
local enPos = {GetBodyPartCoordinates(GetNearestBone(handle), handle)}
local myPos = {getActiveCameraCoordinates()}
local vector = {myPos[1] - enPos[1], myPos[2] - enPos[2], myPos[3] - enPos[3]}
if isWidescreenOnInOptions() then coefficentZ = 0.0778 else coefficentZ = 0.103 end
local angle = {(math.atan2(vector[2], vector[1]) + 0.04253), (math.atan2((math.sqrt((math.pow(vector[1], 2) + math.pow(vector[2], 2)))), vector[3]) - math.pi / 2 - coefficentZ)}
local view = {fix(representIntAsFloat(readMemory(0xB6F258, 4, false))), fix(representIntAsFloat(readMemory(0xB6F248, 4, false)))}
local distance = math.sqrt((math.pow(angle[1] - view[1], 2) + math.pow(angle[2] - view[2], 2))) * 57.2957795131
if distance > fov then check = true else check = false end
if not check then
local myPos = {getCharCoordinates(PLAYER_PED)}
local distance = math.sqrt((math.pow((enPos[1] - myPos[1]), 2) + math.pow((enPos[2] - myPos[2]), 2) + math.pow((enPos[3] - myPos[3]), 2)))
if (distance < maxDistance) then
nearestPED = handle
maxDistance = distance
end
end
end
end
end
end
end
return nearestPED
end
function GetNearestBone(handle)
local maxDist = 20000
local nearestBone = -1
bone = {42, 52, 23, 33, 3, 22, 32, 8}
for n = 1, 8 do
local crosshairPos = {convertGameScreenCoordsToWindowScreenCoords(339.1, 179.1)}
local bonePos = {GetBodyPartCoordinates(bone[n], handle)}
local enPos = {convert3DCoordsToScreen(bonePos[1], bonePos[2], bonePos[3])}
local distance = math.sqrt((math.pow((enPos[1] - crosshairPos[1]), 2) + math.pow((enPos[2] - crosshairPos[2]), 2)))
if (distance < maxDist) then
nearestBone = bone[n]
maxDist = distance
end
end
return nearestBone
end
function GetBodyPartCoordinates(id, handle)
if doesCharExist(handle) then
local pedptr = getCharPointer(handle)
local vec = ffi.new("float[3]")
getbonePosition(ffi.cast("void*", pedptr), vec, id, true)
return vec[0], vec[1], vec[2]
end
end
function CheckStuned()
for k, v in pairs(stun_anims) do
if isCharPlayingAnim(PLAYER_PED, v) then
return false
end
end
return true
end
function smooth_aimbot()
if enable.v and isKeyDown(vkeys.VK_RBUTTON) then
local handle = GetNearestPed(radius.v)
if handle ~= -1 then
local _, myID = sampGetPlayerIdByCharHandle(PLAYER_PED)
local result, playerID = sampGetPlayerIdByCharHandle(handle)
if result then
if (checkStuned.v and not CheckStuned()) then return false end
if (clistFilter.v and sampGetPlayerColor(myID) == sampGetPlayerColor(playerID)) then return false end
if (checkPause.v and sampIsPlayerPaused(playerID)) then return false end
local myPos = {getActiveCameraCoordinates()}
local enPos = {GetBodyPartCoordinates(GetNearestBone(handle), handle)}
if not visibleCheck.v or (visibleCheck.v and isLineOfSightClear(myPos[1], myPos[2], myPos[3], enPos[1], enPos[2], enPos[3], true, true, false, true, true)) then
local vector = {myPos[1] - enPos[1], myPos[2] - enPos[2], myPos[3] - enPos[3]}
if isWidescreenOnInOptions() then coefficentZ = 0.0778 else coefficentZ = 0.103 end
local angle = {(math.atan2(vector[2], vector[1]) + 0.04253), (math.atan2((math.sqrt((math.pow(vector[1], 2) + math.pow(vector[2], 2)))), vector[3]) - math.pi / 2 - coefficentZ)}
local view = {fix(representIntAsFloat(readMemory(0xB6F258, 4, false))), fix(representIntAsFloat(readMemory(0xB6F248, 4, false)))}
local difference = {angle[1] - view[1], angle[2] - view[2]}
local smooth = {difference[1] / smooth.v, difference[2] / smooth.v}
setCameraPositionUnfixed((view[2] + smooth[2]), (view[1] + smooth[1]))
end
end
end
end
return false
end
Ваш Lua-скрипт представляет собой реализацию плавного аимбота для игры, вероятно, San Andreas Multiplayer (SAMP), с использованием библиотеки MoonLoader, ImGui для создания пользовательского интерфейса и vkeys для обработки клавиш. В целом, код функционален, но есть несколько областей, которые можно улучшить для повышения читаемости, производительности и безопасности.
Структурирование кода и модульность
Именование переменных и функций
fix можно переименовать в normalizeAngle, что лучше отражает предназначение функции.camelCase или snake_case, для улучшения читаемости.Оптимизация циклов и проверок
GetNearestPed и GetNearestBone можно добавить оптимизации для выхода из циклов раннее, если уже найден ближайший возможный вариант.Обработка ошибок и проверки
Использование констант и конфигураций
Оптимизация использования FFI
Улучшение интерфейса пользователя (GUI)
До:
local mainWindowState = imgui.ImBool(false)
local smooth = imgui.ImFloat(0.0)
local radius = imgui.ImFloat(0.6)
После:
local isMainWindowVisible = imgui.ImBool(false)
local smoothFactor = imgui.ImFloat(0.0)
local aimRadius = imgui.ImFloat(0.6)
fixДо:
function fix(angle)
if angle > math.pi then
angle = angle - (math.pi * 2)
elseif angle < -math.pi then
angle = angle + (math.pi * 2)
end
return angle
end
После:
-- Нормализует угол в диапазоне [-π, π]
local function normalizeAngle(angle)
while angle > math.pi do
angle = angle - (2 * math.pi)
end
while angle < -math.pi do
angle = angle + (2 * math.pi)
end
return angle
end
До:
function GetNearestPed(fov)
local maxDistance = 35
local nearestPED = -1
for i = 0, sampGetMaxPlayerId(true) do
if sampIsPlayerConnected(i) then
-- ...
end
end
return nearestPED
end
После:
local function getNearestPed(fov)
local maxDistance = 35
local nearestPed = nil
for i = 0, sampGetMaxPlayerId(true) do
if sampIsPlayerConnected(i) then
local find, handle = sampGetCharHandleBySampPlayerId(i)
if find and isCharOnScreen(handle) and not isCharDead(handle) then
local distance = calculateDistance(handle)
if distance < maxDistance and distance < fov then
nearestPed = handle
maxDistance = distance
end
end
end
end
return nearestPed or -1
end
Здесь предполагается, что существует функция calculateDistance для вычисления расстояния до педа.
smooth_aimbotДо:
function smooth_aimbot()
if enable.v and isKeyDown(vkeys.VK_RBUTTON) then
local handle = GetNearestPed(radius.v)
if handle ~= -1 then
-- ...
end
end
return false
end
После:
local function smoothAimbot()
if not enable.v or not isKeyDown(vkeys.VK_RBUTTON) then
return
end
local targetHandle = getNearestPed(aimRadius.v)
if targetHandle == -1 then
return
end
local myID = sampGetPlayerIdByCharHandle(PLAYER_PED)
local result, targetID = sampGetPlayerIdByCharHandle(targetHandle)
if not result then
return
end
if checkStunned and not isCharacterStunned() then
return
end
if clistFilter and isSameTeam(myID, targetID) then
return
end
if checkPause and sampIsPlayerPaused(targetID) then
return
end
if not visibleCheck.v or isLineOfSightClearTo(targetHandle) then
adjustCameraTowards(targetHandle)
end
end
Здесь предполагается, что функции isCharacterStunned, isSameTeam, isLineOfSightClearTo и adjustCameraTowards реализованы для повышения читаемости.
До:
local getbonePosition = ffi.cast("int (__thiscall*)(void*, float*, int, bool)", 0x5E4280)
После:
local BONE_POSITION_ADDRESS = 0x5E4280
local getBonePosition = ffi.cast("int (__thiscall*)(void*, float*, int, bool)", BONE_POSITION_ADDRESS)
Избегайте многократных вызовов функций для получения координат одного и того же объекта. Кэшируйте результаты, если они не изменяются внутри функции.
До:
local myPos = {getActiveCameraCoordinates()}
local enPos = {GetBodyPartCoordinates(GetNearestBone(handle), handle)}
После:
local myCoords = getActiveCameraCoordinates()
local nearestBone = getNearestBone(handle)
local enemyCoords = GetBodyPartCoordinates(nearestBone, handle)
Использование профилировщиков
LuaProfiler, для измерения времени выполнения функций и выявления узких мест.Минимизация вызовов в цикле
smooth_aimbot), должны быть максимально оптимизированы.Кэширование результатов
Асинхронная обработка
Доступ к памяти
readMemory и других низкоуровневых функций может привести к нестабильности игры или даже к бану в многопользовательских играх. Убедитесь, что вы понимаете риски и строго соблюдаете правила использования.Проверки существования объектов
PLAYER_PED существует и валиден перед вызовом функций с ним.Обработка ошибок
Рефакторинг и оптимизация кода – важные шаги для повышения его качества и производительности. Следуя вышеуказанным рекомендациям, вы сможете сделать свой скрипт более читаемым, эффективным и устойчивым. Не забывайте также регулярно тестировать изменения, чтобы убедиться в корректности работы после каждого улучшения.
Not yet included in a published release.