Полезные сниппеты и функции

kjor32

¯\_(ツ)_/¯
Всефорумный модератор
1,684
1,396
Усиливает блики воды.
Lua:
local memory = require 'memory'

memory.setfloat(memory.getuint32(0x73D6F9 + 2, true), значение, true)-- стандартное значение 0.3

image.png
image.png
 

CaJlaT

Овощ
Модератор
2,806
2,606
Не нашёл тут подобных функций, поэтому держите...
Описание: Проверяет находится ли переменная в массиве (с поиском по названию)
Код:
Lua:
function inTable(t, val, key)
    for k, v in pairs(t) do
        if key and k == key and v == val then return true end
        if type(v) == 'table' then
            if inTable(v, val, key) then return true end
        elseif not key and v == val then
            return true
        end
    end
    return false
end
Пример использования:
Lua:
local tbl = {
    {
        123,
        312,
        {
            id = 333
        }
    }
}
print(inTable(tbl, 123)) -- true
print(inTable(tbl, 333)) -- true
print(inTable(tbl, 333, 'id')) -- true
print(inTable(tbl, 123, 'id')) -- false


Описание: Получает таблицу, в которой находится переменная (с поиском по названию)
Код:
Lua:
function getTableByValue(t, val, key)
    for k, v in pairs(t) do
        if key and k == key and v == val then return t end
        if type(v) == 'table' then
            local test = getTableByValue(v, val, key)
            if test then return test end
        elseif not key and v == val then
            return t
        end
    end
    return false
end
Пример использования:
Lua:
local tbl = {
    {
        name = 'huy',
        333,
        {
            id = 333,
            name = 'aboba'
        }
    }
}
local t = getTableByValue(tbl, 333)
if t then print(encodeJson(t)) else print('Table not found!') end
-- выдаст {"1":333,"2":{"name":"aboba","id":333},"name":"huy"}

local t = getTableByValue(tbl, 123)
if t then print(encodeJson(t)) else print('Table not found!') end
-- выдаст Table not found!

local t = getTableByValue(tbl, 333, 'id')
if t then print(encodeJson(t)) else print('Table not found!') end
-- выдаст {"name":"aboba","id":333}
 

Gorskin

I shit on you
Проверенный
1,246
1,043
Описание: Проверяет взорвалось ли что-то в игре в зоне стрима.
Lua:
function main()
    while not isSampAvailable() do wait(0) end
       
    while true do
        wait(0)
        if isExpl() then
            print("Что-то где-то бабахнуло!")
        end
    end
end

function isExpl()
    return readMemory(0xC88950 + 0x28, 1, true) == 1
end
Пример того что можно с этим сделать:
 
Последнее редактирование:

paulohardy

вы еще постите говно? тогда я иду к вам
Всефорумный модератор
1,891
1,254
Описание: Проверяет взорвалось ли что-то в игре в зоне стрима.
Lua:
function main()
    while not isSampAvailable() do wait(0) end
       
    while true do
        wait(0)
        if isExpl() then
            print("Что-то где-то бабахнуло!")
        end
    end
end

function isExpl()
    if readMemory(0xC88950+0x28, 1, true) == 1 then
        return true
    else
        return false
    end
    return false
end
Lua:
function isExpl()
    return readMemory(0xC88950 + 0x28, 1, true) == 1
end
 

ARMOR

kjor32 is legend
Модератор
4,851
6,081
Описание: Убирает отключение чата при открытом Табе( Не ебу нахуя вообще Калькор это добавил, вроде таб не перекрывает чат ):

Код:
Lua:
local memory = require 'memory'

memory.fill(getModuleHandle("samp.dll") + 0x7524D, 0x90, 5, true) -- R3 версия

Пример использования:
Скрипт с поддержкой всех версий SAMP:
Lua:
local memory = require 'memory'
local ffi = require 'ffi'
local samp_base = nil
local addr = {
    [0x31DF13] = 0x7135D, -- R1
    [0x3195DD] = 0x713FD, -- R2
    [0xCC4D0] = 0x7524D, -- R3
    [0xCBCB0] = 0x7598D, -- R4
    [0xCBC90] = 0x7595C, -- R5
    [0xFDB60] = 0x753DD -- DL
}

if samp_base == nil then
    samp_base = getModuleHandle("samp.dll")
    if samp_base ~= 0 then
        local nt_header = samp_base + ffi.cast("long*", samp_base + 60)[0]
        local entry_point_addr = ffi.cast("unsigned int*", nt_header + 40)[0]
        if addr[entry_point_addr] ~= nil then
            memory.fill(samp_base + addr[entry_point_addr], 0x90, 5, true)
        end
    end
end

Демонстрация:
1674753702594.png
 

ARMOR

kjor32 is legend
Модератор
4,851
6,081
Описание: Убирает отключение худа, чата и диалогов при зажатой F10

Lua:
local memory = require 'memory'

memory.fill(getModuleHandle("samp.dll") + 0x752C1, 0x90, 5, true) -- R3

--[[
0x713D1 - R1
0x71471 - R2
0x752C1 - R3
0x75A01 - R4
0x759D0 - R5
0x75451 - DL
]]
 

ARMOR

kjor32 is legend
Модератор
4,851
6,081
Описание: Устанавливает позицию ScrollBar'а чата:

Код:
Lua:
local memory = require 'memory'

function setChatScrollBarPos(pos)
    local pChat = memory.getuint32(getModuleHandle("samp.dll") + 0x26E8C8, true)
    local m_pScrollbar = memory.getuint32(pChat + 0x11E, true) -- Вообще это вроде как не m_pScrollBar, но похуй.
    memory.setint8(m_pScrollbar + 0x8E, pos, true)
end

Описание: Поднимает/Опускает ScrollBar чата на указаное количество строчек (

Код:
Lua:
local memory = require 'memory'

function scrollChatScrollBar(pos) -- Если хотите поднять - пишите отъемлимое число, например -5, а если наоборот опустить - пишите обычные числа, например 10
    local pChat = memory.getuint32(getModuleHandle("samp.dll") + 0x26E8C8, true)
    local m_pScrollbar = memory.getuint32(pChat + 0x11E, true)
    memory.setint8(m_pScrollbar + 0x8E, memory.getint8(m_pScrollbar + 0x8E, true) + pos, true)
end
--Не нужно говорить о том что можно было просто вызывать CChat::Scroll(), в ней если вы укажете любое число - она умножит его на 3 )

Описание: Получает позицию ScrollBar'а чата:

Код:
Lua:
local memory = require 'memory'

function getChatScrollBarPos()
    local pChat = memory.getuint32(getModuleHandle("samp.dll") + 0x26E8C8, true)
    local m_pScrollbar = memory.getuint32(pChat + 0x11E, true)
    return memory.getint8(m_pScrollbar + 0x8E, true)
end

Функции выше только для R3, но если хотите чтобы они работали на вашей версии просто измените адрес в переменной pChat на нужную:
Lua:
R1 - 0x21A0E4
R2 - 0x21A0EC
R3 - 0x26E8C8
R4 - 0x26E9F8
R5 - 0x26EB80
DL - 0x2ACA10
 
Последнее редактирование:

ARMOR

kjor32 is legend
Модератор
4,851
6,081
Описание: Отключает свечение от амулета( Свечение 50+ аксов на Аризоне ):

Lua:
local memory = require 'memory'

memory.fill(0x455F59, 0x90, 5, true)
 
  • Нравится
  • Грустно
  • Эм
Реакции: Devlo, its и ChromiusJ

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,771
11,215
Описание: рисует QR код через DrawList (требуется qrencode.lua: https://github.com/speedata/luaqrcode)
Пример использования:
Lua:
local newFrame = imgui.OnFrame(
    function() return isSampAvailable() end,
    function(self)
        self.HideCursor = true
        local DL = imgui.GetBackgroundDrawList()
        local QRSize = 40
        for _, ped in ipairs(getAllChars()) do
            if isCharOnScreen(ped) then
                local result, id = sampGetPlayerIdByCharHandle(ped)
                if result then
                    local x, y, z = getBodyPartCoordinates(8, ped)
                    local dist = getDistanceBetweenCoords3d(x, y, z + 0.5, getCharCoordinates(PLAYER_PED))
                    local pos = imgui.ImVec2(convert3DCoordsToScreen(x, y, z + 0.05 * dist))
                    imgui.DrawQrCode(DL, imgui.ImVec2(pos.x - QRSize / 2, pos.y - QRSize / 2), QRSize, sampGetPlayerNickname(id))
                end
            end
        end
    end
)
1676307691085.png

Код:
Lua:
local qrencode = require('qrencode')
function imgui.DrawQrCode(DL, pos, size, text)
    local status, result = qrencode.qrcode(text)
    assert(status, result)
    local x, y = pos.x, pos.y
    local pixelSize = size and size / #result or 20
    for columnIndex, pixels in ipairs(result) do
        for rowIndex, v in ipairs(pixels) do
            DL:AddRectFilled(imgui.ImVec2(x, y), imgui.ImVec2(x + pixelSize, y + pixelSize), v > 0 and 0xFF000000 or 0xFFffffff)
            y = y + pixelSize
        end
        x, y = x + pixelSize, pos.y
    end
end
 

Lance_Sterling

Известный
798
278
Описание: рисует плавный renderFontDrawText из одной точки в другую
Пример использования:
Lua:
sampRegisterChatCommand('wh', function()
    tableOfNew.wallhack.v = not tableOfNew.wallhack.v
    animatedRenderFontDrawText(280, 410, 150, 10, 10, 'Wallhack '..(tableOfNew.wallhack.v and '{00FF00}activated' or '{FF0000}deactivated'), '0xFFFFFF', 0.3, 'Tahoma', 20)
end)
Код:
animatedRenderFontDrawText(int x, int y, int finish, int alpha, int speed, string text, string color(HEX), float delay, string font, int font_size)

Lua:
function animatedRenderFontDrawText(x, y, finish, alpha, speed, text, color, delay, font, font_size)
    lua_thread.create(function()
        local ToScreen = convertGameScreenCoordsToWindowScreenCoords --конвертируем координаты для разных разрешений экрана
        local X, Y = ToScreen(x, y)--получаем координаты с которыми будем работать
        local number, tenths = tostring(delay):match('(%d+).(%d+)') --вычисляем десятые
        font_render = renderCreateFont(font, font_size, FCR_BORDER) --создаем шрифт
        repeat
            renderFontDrawText(font_render, text, X, Y, math.floor(alpha) * 0x1000000 + color) --рисуем текст с указанными параметрами
            wait(0) --добавляем задержку в 1 кадр что бы игра не крашила
            Y = Y - speed --отнимаем скорость у координаты Y что бы переместить текст выше
            alpha = alpha + speed + 5 --прибавляем альфа каналу скорость что бы была анимация появления
        until Y == select(2, ToScreen(x, y))-finish --выполнять код пока Y не достигнет указанных координат
        local t=os.clock() + delay --создаем таймер для отображения текста после окончания цикла repeat
        while t > os.clock() do
            renderFontDrawText(font_render, text, X, Y, math.floor(alpha) * 0x1000000 + color) --рисуем текст с указанными параметрами
            wait(0) --добавляем задержку в 1 кадр что бы игра не крашила
            if tonumber(tenths) ~= 0 and tonumber(number) == 0 then
                alpha = alpha - tenths:gsub('0*', '') --отнимаем у альфы задержку после точки для плавного скрытия рендера
            elseif tonumber(tenths) == 0 and tonumber(number) ~= 0 then
                alpha = alpha - delay --отнимаем у альфы задержку для плавного скрытия рендера
            else
                alpha = alpha - delay --отнимаем у альфы задержку для плавного скрытия рендера
            end
            if alpha <= 0 then break end
        end
    end)
end

ребята не судите строго впервые работаю с анимациями

Не баг, а фича
 
Последнее редактирование:

Andrinall

Известный
678
531
Тут человек переводил ShadeVertsLinearUV, ну и я решил присоединиться и перевести ShadeVertsLinearColorGradientKeepAlpha

Собственно..
1676733237860.png


с dl:AddText это выглядит вот так вот
1676734737706.png

Lua:
local imgui = require 'mimgui'

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
    sw, sh = getScreenResolution()
end)
local wnd = imgui.OnFrame(function() return true end, function()
    local dl = imgui.GetBackgroundDrawList()

    local vtxstart = dl.VtxBuffer.Size

    dl:AddRectFilled(
        imgui.ImVec2( sw / 2 - 50, sh / 2 - 50 ),
        imgui.ImVec2( sw / 2 + 50, sh / 2 + 50 ),
        0xFFFFFFFF, 8, 15
    )

    dl:PathArcTo(
        imgui.ImVec2( sw / 2 + 25, sh / 2 + 25 ),
        50, 0, math.pi * 2, 64
    )
    dl:PathFillConvex(0xFFFFFFFF)

    local vtxend = dl.VtxBuffer.Size
    dl:ShadeVertsLinearColorGradientKeepAlpha(
        vtxstart, vtxend,
        imgui.ImVec2( sw / 2 - 50, sh / 2 - 50 ),
        imgui.ImVec2( sw / 2 + 50, sh / 2 + 50 ),
        0xFFFF5525, 0xFF2555FF
    )
end)
wnd.HideCursor = true

Сам метод:
function ImLengthSqr(vec2) return (vec2.x * vec2.x) + (vec2.y * vec2.y) end
function ImDot(a, b) return a.x * b.x + a.y * b.y end
function ImClamp(v, mn, mx) return ((v < mn) and mn or ((v > mx) and mx or v)) end

-- int, int, ImVec2, ImVec2, ImU32, ImU32
function imgui.ImDrawList.__index:ShadeVertsLinearColorGradientKeepAlpha(vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col0, col1)
    local gradient_extent = imgui.ImVec2(gradient_p1.x - gradient_p0.x, gradient_p1.y - gradient_p0.y )
    local gradient_inv_length2 = 1.0 / ImLengthSqr(gradient_extent)

    col0 = {
        r = bit.band(bit.rshift(col0, 16), 0xFF),
        g = bit.band(bit.rshift(col0, 8), 0xFF),
        b = bit.band(bit.rshift(col0, 0), 0xFF)
    }

    local col_delta = {
        r = bit.band(bit.rshift(col1, 16), 0xFF) - col0.r,
        g = bit.band(bit.rshift(col1, 8), 0xFF) - col0.g,
        b = bit.band(bit.rshift(col1, 0), 0xFF) - col0.b
    }

    for vert = vert_start_idx, vert_end_idx do
        local d = ImDot(
            imgui.ImVec2(
                self.VtxBuffer.Data[vert].pos.x - gradient_p0.x,
                self.VtxBuffer.Data[vert].pos.y - gradient_p0.y
            ),
            gradient_extent
        )
        local t = ImClamp(d * gradient_inv_length2, 0.0, 1.0)
      
        self.VtxBuffer.Data[vert].col = bit.bor(
            bit.lshift(col0.r + col_delta.r * t, 16),
            bit.lshift(col0.g + col_delta.g * t, 8),
            bit.lshift(col0.b + col_delta.b * t, 0),
            bit.band(self.VtxBuffer.Data[vert].col, 0xFF000000)
        )
    end
end
 
Последнее редактирование:

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,771
11,215
Описание: загружает тему mimgui из JSON
Структура:
JSON:
{
    "col": {
        "WindowBg": [0, 0, 0, 1],
        "Text": [1, 1, 1, 1]
    },
    "style": {
        WindowRounding: 15,
        WindowPadding: [5, 5]
    }
}
Код:

Lua:
function imgui.LoadJsonTheme(JSON)
    if (not JSON) then return false, 'json is nil' end;
    local theme = decodeJson(JSON);
    if (not theme) then return false, 'invalid json' end;
 
    if (theme.col) then
        for param, value in pairs(theme.col) do
            local status, _ = pcall(function() return imgui.Col[param] ~= nil end);
            if (not status) then return false, 'Unknown color style var "'..param..'"' end;
            if (type(value) ~= 'table') then return false, 'Color must be "table"' end;
            if (#value ~= 4) then return false, 'Color must have 4 parameters (r, g, b, a)' end;
            imgui.GetStyle().Colors[imgui.Col[param]] = imgui.ImVec4(table.unpack(value));
        end
    end
    if (theme.style) then
        for param, value in pairs(theme.style) do
            if (not imgui.StyleVar[param]) then return false, 'Unknown style var "'..param..'"' end;
            if (type(value) ~= 'table' and type(value) ~= 'number') then return false, 'Style must be "table" or "number" ('..param..')' end;
            if (type(value) == 'table' and (#value ~= 4 and #value ~= 2)) then return false, 'Incorrect value length (ImVec2 = 2 (x, y), ImVec4 = 4 (x, y, z, w)) (var:'..param..')' end;
            imgui.GetStyle()[param] = type(value) == 'number' and value or (#value == 2 and imgui.ImVec2(table.unpack(value)) or imgui.ImVec4(table.unpack(value)));
        end
    end

    return true, 'ok';
end
Пример использования:
click
Lua:
local defaultTheme = [[
{
    "col":{
        "WindowBg": [1, 0, 0, 0.5],
        "Text": [1, 1, 1, 1]
    },
    "style":{
        "WindowRounding": 20,
        "WindowPadding": [10, 15]
    }
}
]]

local ffi = require('ffi')
local imgui = require('mimgui')
local themeCode = imgui.new.char[4096](defaultTheme);

-- PASTE imgui.LoadJsonTheme HERE

local newFrame = imgui.OnFrame(
    function() return true end,
    function(self)
        imgui.SetNextWindowSize(imgui.ImVec2(300, 185), imgui.Cond.FirstUseEver)
        if imgui.Begin('Main Window', nil) then
            local size = imgui.GetWindowSize();
            imgui.Text('Theme JSON:');
            imgui.InputTextMultiline('##themeCode', themeCode, ffi.sizeof(themeCode), imgui.ImVec2(size.x - 15, size.y - 85));
            if imgui.Button('Apply theme', imgui.ImVec2(size.x - 15, 25)) then
                local ok, code = imgui.LoadJsonTheme(ffi.string(themeCode));
                sampAddChatMessage(ok and 'Тема изменена!' or 'Ошибка, не удалось изменить тему, причина: '..code, -1)
            end
            imgui.End()
        end
    end
)
1676739426204.png
1676739431315.png
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,771
11,215
Описание: получает список файлов в папке
Код:
Lua:
---@param path string directory
---@param ftype string|string[] file extension
---@return string[] files names
function getFilesInPath(path, ftype)
    assert(path, '"path" is required');
    assert(type(ftype) == 'table' or type(ftype) == 'string', '"ftype" must be a string or array of strings');
    local result = {};
    for _, thisType in ipairs(type(ftype) == 'table' and ftype or { ftype }) do
        local searchHandle, file = findFirstFile(path.."\\"..thisType);
        table.insert(result, file)
        while file do file = findNextFile(searchHandle) table.insert(result, file) end
    end
    return result;
end
Пример использования:
поиск файлов с расширением .lua, .luac и .log
Lua:
local files = getFilesInPath(getWorkingDirectory(), {'*.lua', '*.luac', '*.log'})
imgui.Text('Total files: '..tostring(#files))
imgui.Separator()
for _, filename in ipairs(files) do
    imgui.Text(filename)
end
1676740209363.png
 
Последнее редактирование: