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

Vespan

loneliness
Проверенный
2,136
1,769
не знаю как названить ну кароче улучшеный поиск в таблице по ключу
Lua:
tableKey = function(self, key)
    for k,v in pairs(self) do
        for l in k:gmatch("[^.]+") do
            if l == key then
                return v
            end
        end
    end
end
Lua:
local tbl = {
    ['bool8.bool32.int'] = "bool",
    ['fixedString32.encodedString2048.encodedString4096'] = "string32",
    ['compressedFloat'] = "float",
}
print(tableKey(tbl,"int")) -- bool
print(tableKey(tbl,"encodedString2048")) -- string32
print(tableKey(tbl,"booling")) -- nil

--все же лучше чем
local tbl = {
    ['bool8'] = "bool",
    ['bool32'] = "bool",
    ['int'] = "bool",
    ['fixedString32'] = "string32",
    ['encodedString2048'] = "string32",
    ['encodedString4096'] = "string32",
    ['compressedFloat'] = "float",
}
 
Последнее редактирование:

kirieshki.

Новичок
19
11
Переливающийся текст, работает с renderFontDrawText
Так как темы такой не нашёл, делаю свою.
Пример:

Код:
Lua:
function join_argb(a, r, g, b)
    local argb = b  -- b
    argb = bit.bor(argb, bit.lshift(g, 8))  -- g
    argb = bit.bor(argb, bit.lshift(r, 16)) -- r
    argb = bit.bor(argb, bit.lshift(a, 24)) -- a
    return argb
end

function string.insert(str1, str2, pos) -- функция вставки строки в строку по позиции
    return str1:sub(1,pos)..str2..str1:sub(pos+1)
end

function gradient_text(text, speed)
    local time = os.clock()
    local a = 255
    for i=string.len(RText) - 1, 0, -1 do
        local r = math.floor(math.sin((time * speed + i / 7)) * 127 + 128)
        local g = math.floor(math.sin((time * speed + i / 7)  + 2) * 127 + 128)
        local b = math.floor(math.sin((time * speed + i / 7)  + 3) * 127 + 128)
        local col = join_argb(a, r, g, b)
        local hex = ('%06X'):format(col)
        local hex = string.sub(hex, string.len(hex) - 5, string.len(hex))
        local hex = '{'..hex..'}'
        RText = string.insert(RText, hex, i)
    end
    return string.insert(text, RText, string.len(text))
end

Пример использования кода:
Lua:
-- лучше использовать в цикле while true в функции main()
local text = 'privet'
renderFontDrawText(font, 'privet'..gradient_text(text, 1), x, y, 0xFFFFFFFF)
 

Вложения

  • Arizona-RP-2025-01-27-00-05-48-_online-video-cutter.com_.gif
    Arizona-RP-2025-01-27-00-05-48-_online-video-cutter.com_.gif
    42.1 KB · Просмотры: 96

chromiusj

$IWishYouSweetDreams
Модератор
5,732
4,027
Переливающийся текст, работает с renderFontDrawText
Так как темы такой не нашёл, делаю свою.
Пример:

Код:
Lua:
function join_argb(a, r, g, b)
    local argb = b  -- b
    argb = bit.bor(argb, bit.lshift(g, 8))  -- g
    argb = bit.bor(argb, bit.lshift(r, 16)) -- r
    argb = bit.bor(argb, bit.lshift(a, 24)) -- a
    return argb
end

function string.insert(str1, str2, pos) -- функция вставки строки в строку по позиции
    return str1:sub(1,pos)..str2..str1:sub(pos+1)
end

function gradient_text(text, speed)
    local time = os.clock()
    local a = 255
    for i=string.len(RText) - 1, 0, -1 do
        local r = math.floor(math.sin((time * speed + i / 7)) * 127 + 128)
        local g = math.floor(math.sin((time * speed + i / 7)  + 2) * 127 + 128)
        local b = math.floor(math.sin((time * speed + i / 7)  + 3) * 127 + 128)
        local col = join_argb(a, r, g, b)
        local hex = ('%06X'):format(col)
        local hex = string.sub(hex, string.len(hex) - 5, string.len(hex))
        local hex = '{'..hex..'}'
        RText = string.insert(RText, hex, i)
    end
    return string.insert(text, RText, string.len(text))
end

Пример использования кода:
Lua:
-- лучше использовать в цикле while true в функции main()
local text = 'privet'
renderFontDrawText(font, 'privet'..gradient_text(text, 1), x, y, 0xFFFFFFFF)
я сначала подумал, что цвет текста можно произвольный делать, но внимательно посмотрел
короче все придумали еще задавно посмотришь в сурсах
 

ARMOR

Say my name
Модератор
5,006
7,041
В муне 0.26 неправильно получается и устанавливается кватернион сущностей, в 0.27 это было исправлено, но почти никто не использует 0.27 так что вот:

Описание: Получает кватернион сущности по её указателю ( не по хендлу )
Lua:
local ffi = require("ffi")
ffi.cdef[[
    typedef struct CVector CVector;
    #pragma pack(push, 8)
    struct CVector
    {
        float x;
        float y;
        float z;
    };
    #pragma pack(pop)
    typedef struct CMatrix CMatrix;
    #pragma pack(push, 8)
    struct CMatrix
    {
        CVector right;
        unsigned int flags;
        CVector up;
        unsigned int pad1;
        CVector at;
        unsigned int pad2;
        CVector pos;
        unsigned int pad3;
        CMatrix *m_pAttachMatrix;
        int m_bAttachMatrixTemporary;
    };
    #pragma pack(pop)
    typedef struct CQuaternion CQuaternion;
    #pragma pack(push, 8)
    struct CQuaternion
    {
        CVector imag;
        float real;
    };
    #pragma pack(pop)
]]

local CPlaceable__GetMatrix = ffi.cast("CMatrix*(__thiscall*)(uintptr_t)", 0x411990)

function matrixToQuaternion(matrix)
    local trace = matrix.right.x + matrix.up.y + matrix.at.z
    local q = ffi.new("CQuaternion")
    
    if trace > 0 then
        local s = math.sqrt(trace + 1) * 2
        q.real = 0.25 * s
        q.imag.x = (matrix.at.y - matrix.up.z) / s
        q.imag.y = (matrix.right.z - matrix.at.x) / s
        q.imag.z = (matrix.up.x - matrix.right.y) / s
    else
        if matrix.right.x > matrix.up.y and matrix.right.x > matrix.at.z then
            local s = math.sqrt(1 + matrix.right.x - matrix.up.y - matrix.at.z) * 2
            q.real = (matrix.at.y - matrix.up.z) / s
            q.imag.x = 0.25 * s
            q.imag.y = (matrix.right.y + matrix.up.x) / s
            q.imag.z = (matrix.right.z + matrix.at.x) / s
        elseif matrix.up.y > matrix.at.z then
            local s = math.sqrt(1 + matrix.up.y - matrix.right.x - matrix.at.z) * 2
            q.real = (matrix.right.z - matrix.at.x) / s
            q.imag.x = (matrix.right.y + matrix.up.x) / s
            q.imag.y = 0.25 * s
            q.imag.z = (matrix.up.z + matrix.at.y) / s
        else
            local s = math.sqrt(1 + matrix.at.z - matrix.right.x - matrix.up.y) * 2
            q.real = (matrix.up.x - matrix.right.y) / s
            q.imag.x = (matrix.right.z + matrix.at.x) / s
            q.imag.y = (matrix.up.z + matrix.at.y) / s
            q.imag.z = 0.25 * s
        end
    end
    return q.imag.x, q.imag.y, q.imag.z, q.real
end

function GetEntityQuaternion(pEntity)
    local x, y, z, w = 0, 0, 0, 0;
    local pMatrix = CPlaceable__GetMatrix(pEntity)
    if (pMatrix ~= 0 or pEntity ~= 0) then
        x, y, z, w = matrixToQuaternion(pMatrix);
    end
    return x, y, z, w;
end

Описание: Изменяет кватернион сущности по её указателю ( Не хендлу )
Lua:
local ffi = require("ffi")
ffi.cdef[[
    typedef struct CVector CVector;
    #pragma pack(push, 8)
    struct CVector
    {
        float x;
        float y;
        float z;
    };
    #pragma pack(pop)
    typedef struct CMatrix CMatrix;
    #pragma pack(push, 8)
    struct CMatrix
    {
        CVector right;
        unsigned int flags;
        CVector up;
        unsigned int pad1;
        CVector at;
        unsigned int pad2;
        CVector pos;
        unsigned int pad3;
        CMatrix *m_pAttachMatrix;
        int m_bAttachMatrixTemporary;
    };
    #pragma pack(pop)
    typedef struct CQuaternion CQuaternion;
    #pragma pack(push, 8)
    struct CQuaternion
    {
        CVector imag;
        float real;
    };
    #pragma pack(pop)
]]

local CPlaceable__GetMatrix = ffi.cast("CMatrix*(__thiscall*)(uintptr_t)", 0x411990)
local CMatrix__SetRotate = ffi.cast("void(__thiscall*)(CMatrix*, CQuaternion*)", 0x59BBF0)
local CEntity__UpdateRwFrame = ffi.cast("void(__thiscall*)(uintptr_t)", 0x532B00)
local CEntity__UpdateRW = ffi.cast("void(__thiscall*)(uintptr_t)", 0x446F90)

function setEntityQuaternion(pEntity, x, y, z, w)
    if (pEntity) then
        local quaternion = ffi.new("CQuaternion");
        quaternion.imag.x = x;
        quaternion.imag.y = y;
        quaternion.imag.z = z;
        quaternion.real = -w;
        local pMatrix = CPlaceable__GetMatrix(pEntity);
        CMatrix__SetRotate(pMatrix, quaternion);
        CEntity__UpdateRwFrame(pEntity)
        CEntity__UpdateRW(pEntity)
    end
end

Пример использования:
Lua:
function main()
    while true do
        wait(0)
        if isCharInAnyCar(playerPed) then
            local handle = storeCarCharIsInNoSave(playerPed)
            local pVehicle = getCarPointer(handle)
            local x, y, z, w = GetEntityQuaternion(pVehicle)
            setVehicleQuaternion(handle, x, y, z, w)
        end
    end
end
 

moreveal

Известный
Проверенный
929
625
description: Function to prevent a user from renaming the name of the Script.

code:
-- function to prevent renaming your script

function checkScriptName(correct_name)
    if thisScript().filename ~= correct_name then
        thisScript():unload()
    end

    if thisScript().filename ~= correct_name then
        sampAddChatMessage("Do not rename the script.", -1)
        os.rename(thisScript().path, thisScript().directory .. "\\" .. correct_name)
        thisScript():reload()
    end
end
unloading and then renaming? lol
 
  • Нравится
Реакции: Willy4ka и Cloud.

Vespan

loneliness
Проверенный
2,136
1,769
Пути навигации ИИ в одиночной игре (взять все из /data/paths/*.dat)
sa-mp-000.png
sa-mp-000.png
не ебу, на воде координаты, на суше и на воздухе так и по z = 0, возможно для миссий

применение - тепнуть игрока на тратуар, машину на дорогу(да есть в муне для этого функция ну не важно), или ботов так можно сделать которые по тратуару будут ходить к заданой точке!?!?!?!
вообщем, не важно, мозг присуствует(луашко) придумаете сами

(вроде была тема/ответ с нодами но не нашел, да и вроде там только ноды по транспорту были)
(вроде были еще ноды для полета транспорта, как найду то обновлю ответ)(луашко)
 

Вложения

  • peds.json
    1.9 MB · Просмотры: 2
  • cars.json
    1.5 MB · Просмотры: 3
  • navi.json
    1.4 MB · Просмотры: 2

vuule

Новичок
7
0
Открывает/Закрывает консоль sampfuncs

Lua:
local ffi = require("ffi")
local sampfuncs = getModuleHandle("SampFuncs.asi")
-- R1
function setSFConsoleState(bValue)
    local pSfConsole = ffi.cast("void**", sampfuncs + 0x11572C)[0]
    ffi.cast("void(__thiscall*)(void*, bool)", sampfuncs + 0x12EBB)(pSfConsole, bValue)
end
-- R3
function setSFConsoleState(bValue)
    local pSfConsole = ffi.cast("void**", sampfuncs + 0x1136C0)[0]
    ffi.cast("void(__thiscall*)(void*, bool)", sampfuncs + 0x131E7)(pSfConsole, bValue)
end

Пример использования:
Lua:
setSFConsoleState(true)
Is this all because I tried to see if it would work, otherwise I use R3 but it won't work at all
 

UBP

Известный
366
236
---Форматирует JSON строку с отступами
Lua:
---Форматирует JSON строку с отступами
---@param str string JSON строка
---@param indent number|nil Размер отступа (по умолчанию 2)
---@return string formatted Отформатированная строка
local function format_json(str, indent)
    indent = indent or 2
    local formatted = str:gsub("%{", "{\n"):gsub("%}", "\n}")
                        :gsub("%[", "[\n"):gsub("%]", "\n]")
                        :gsub(",%s*", ",\n")
   
    local level = 0
    local result = {}
    for line in formatted:gmatch("[^\n]+") do
        level = level - (line:match("^%s*[%]%}]") and 1 or 0)
        table.insert(result, string.rep(" ", level * indent) .. line:match("^%s*(.-)%s*$"))
        level = level + (line:match("[%{%[]%s*$") and 1 or 0)
    end
    return table.concat(result, "\n")
end
-- Функция для создания отсортированной таблицы
Lua:
-- Порядок полей для разных типов
local field_orders = {
    default = {
        __type = 1,
        value = 2,
        size = 3,
        x = 4,
        y = 5,
        z = 6,
        w = 7
    },
    vec2 = {
        __type = 1,
        x = 2,
        y = 3
    },
    vec4 = {
        __type = 1,
        x = 2,
        y = 3,
        z = 4,
        w = 5
    }
}
-- Функция сортировки ключей вспомогательного массива
--@param keys table Таблица ключей
---@param value_type string Тип значения
local function sort_keys(keys, value_type, data)
    if not data then return keys end
    local order = field_orders[value_type] or field_orders.default
    table.sort(keys, function(a, b)
        local a_val = data[a]
        local b_val = data[b]
        local a_has_type = type(a_val) == 'table' and a_val.__type
        local b_has_type = type(b_val) == 'table' and b_val.__type
        if (a_has_type and b_has_type) or (not a_has_type and not b_has_type) then
            local is_num_a = type(a) == 'number'
            local is_num_b = type(b) == 'number'
           
            if is_num_a ~= is_num_b then
                return is_num_a
            end
            if is_num_a and is_num_b then
                return a < b
            end
            return tostring(a) < tostring(b)
        end
        return a_has_type
    end)
    return keys
end

-- Функция для создания отсортированной таблицы
--@param data table Данные для сортировки
--@return table Отсортированная таблица
local function create_sorted_table(data, value_type)
    if type(data) ~= 'table' then return data end
    local keys = {}
    for k in pairs(data) do
        table.insert(keys, k)
    end
    keys = sort_keys(keys, value_type or (data.__type and data.__type or 'default'), data)
    local result = {}
    for _, k in ipairs(keys) do
        local v = data[k]
        result[k] = create_sorted_table(v, type(v) == 'table' and v.__type)
    end
    return result
end


Вырезано из https://www.blast.hk/threads/228834/