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

why ega

РП игрок
Модератор
2,539
2,229
Перевод из Эйлера в кватернион это обычная математика. Скорее всего ГТА-шные функции ни чем не отличаются от функций, которые можно найти в интернете. В таком случае можно тупо ChatGPT спросить (держу в курсе), а не использовать странную функцию, которая спизжена откуда-то, а автор не знает как она работает. В итоге, в ходе разработки могут возникнуть непредвиденные последствия.
йоу, а моя функция - не математика? ось W a.k.a скалярная часть кватерниона равна косинусу 1/2 радианта. Z = -синус все той же 1/2 радианта. Эта функция родилась случайно, когда я юзал обрывок кода Криптона и заметил, что его можно существенно так укоротить.
 
  • Эм
Реакции: riverya4life и Musaigen

Vespan

loneliness
Проверенный
2,101
1,632
легчайшее эмуляция RPC(как у imring'a но чутка меньше по коду☠️☠️)
Lua:
function emul_rpc(name,p)
    local sampev = require'samp.events'
    local handler = require 'samp.events.handlers'
    local function getn(t); local i = 0;    for k,v in pairs(t) do i = i + 1 end return i;  end
    local function reverseTable(tbl)
        local rev = {}
        for i=#tbl, 1, -1 do
            rev[#rev+1] = tbl[i]
        end
        return rev
    end
    for _,INTERFACE in pairs({'OUTCOMING_RPCS','OUTCOMING_PACKETS','INCOMING_RPCS','INCOMING_PACKETS'}) do
        for k,v in pairs(sampev.INTERFACE[INTERFACE]) do
            if (name == v[1] or name == k) then
                local values, bs = getn(v)-1, raknetNewBitStream()
                if type(v[2]) == 'function' then
                    v[3](bs,p)
                else
                    local T = ((p[1] ~= nil and type(p[1]) == 'table') or (#p == 0 and getn(p) ~= 0))
                    if not T then
                        p = reverseTable(p)
                    elseif T and (p[1] ~= nil and type(p[1]) == 'table') then
                        local res = {}
                        for k,v in pairs(p) do
                            for kk,vv in pairs(p[k]) do
                                res[kk] = vv
                            end
                        end
                        p = res
                    end
                    for _,vv in pairs(v) do
                        if type(vv) == 'table' then
                            for k,v in pairs(vv) do
                                for kk,vv in pairs(sampev.INTERFACE.BitStreamIO) do
                                    if kk == v then
                                        sampev.INTERFACE.BitStreamIO[kk].write(bs, p[(T and k or values)])
                                        values = values - 1
                                    end
                                end
                            end
                        end
                    end
                end
                raknetEmulRpcReceiveBitStream(k, bs)
                raknetDeleteBitStream(bs)
            end
        end
    end
end
Lua:
function emul_rpc(name,p)
    local sampev = require'samp.events'
    local handler = require 'samp.events.handlers'
    local function getn(t); local i = 0;    for k,v in pairs(t) do i = i + 1 end return i;  end
    local function reverseTable(tbl)
        local rev = {}
        for i=#tbl, 1, -1 do
            rev[#rev+1] = tbl[i]
        end
        return rev
    end
    for INTERFACE,_ in pairs(sampev.INTERFACE) do
        if INTERFACE ~= 'BitStreamIO' then
            for k,v in pairs(sampev.INTERFACE[INTERFACE]) do
                if (name == v[1] or name == k) then
                    local values, bs = getn(v)-1, raknetNewBitStream()
                    if type(v[2]) == 'function' then
                        v[3](bs,p)
                    else
                        p = reverseTable(p)
                        for kk,vv in pairs(v) do
                            if type(vv) == 'table' then
                                for k,v in pairs(vv) do
                                    for kk,vv in pairs(sampev.INTERFACE.BitStreamIO) do
                                        if kk == v then
                                            sampev.INTERFACE.BitStreamIO[kk].write(bs, p[values])
                                            values = values - 1
                                        end
                                    end
                                end
                            end
                        end
                    end
                    raknetEmulRpcReceiveBitStream(k, bs)
                    raknetDeleteBitStream(bs)
                end
            end
        end
    end
end

Lua:
    -- создаем объект

    MYPOS = {getCharCoordinates(PLAYER_PED)}
    -- можно и emul_rpc(44,{
    emul_rpc('onCreateObject',{
        1, {
            modelId = 19362,
            position = {x=MYPOS[1],y=MYPOS[2],z=MYPOS[3]},
            rotation = {x=0,y=0,z=0},
            drawDistance = 50,
            noCameraCol = true,
            attachToVehicleId = 65535,--none
            attachToObjectId = 65535,--none
            attachToPlayerId = 65535,--none
            texturesCount = 0,
            materialText = {},
            materials = {},
        },
    })

    --

    --отправка сообщение в чат

    emul_rpc('onServerMessage',{ {text = 'TEXT'}, {color = -1} })
    emul_rpc('onServerMessage',{text = 'TEXT',color = -1 })
    emul_rpc('onServerMessage',{-1,'TEXT'})
    -- сделал три вида аргументов для легчайшей эмулиции, оно все работает=нормально
 
Последнее редактирование:

imring

Ride the Lightning
Всефорумный модератор
2,355
2,516
легчайшее эмуляция RPC(как у imring'a но чутка меньше по коду☠️☠️)
Lua:
function emul_rpc(name,p)
    local sampev = require'samp.events'
    local handler = require 'samp.events.handlers'
    local function getn(t); local i = 0;    for k,v in pairs(t) do i = i + 1 end return i;  end
    local function reverseTable(tbl)
        local rev = {}
        for i=#tbl, 1, -1 do
            rev[#rev+1] = tbl[i]
        end
        return rev
    end
    for INTERFACE,_ in pairs(sampev.INTERFACE) do
        if INTERFACE ~= 'BitStreamIO' then
            for k,v in pairs(sampev.INTERFACE[INTERFACE]) do
                if (name == v[1] or name == k) then
                    local values, bs = getn(v)-1, raknetNewBitStream()
                    if type(v[2]) == 'function' then
                        v[3](bs,p)
                    else
                        p = reverseTable(p)
                        for kk,vv in pairs(v) do
                            if type(vv) == 'table' then
                                for k,v in pairs(vv) do
                                    for kk,vv in pairs(sampev.INTERFACE.BitStreamIO) do
                                        if kk == v then
                                            sampev.INTERFACE.BitStreamIO[kk].write(bs, p[values])
                                            values = values - 1
                                        end
                                    end
                                end
                            end
                        end
                    end
                    raknetEmulRpcReceiveBitStream(k, bs)
                    raknetDeleteBitStream(bs)
                end
            end
        end
    end
end
Lua:
    -- создаем объект
    MYPOS = {getCharCoordinates(PLAYER_PED)}
    -- можно и emul_rpc(44,{
    emul_rpc('onCreateObject',{
        1, {
            modelId = 19362,
            position = {x=MYPOS[1],y=MYPOS[2],z=MYPOS[3]},
            rotation = {x=0,y=0,z=0},
            drawDistance = 50,
            noCameraCol = true,
            attachToVehicleId = 65535,
            attachToObjectId = 65535,
            attachToPlayerId = 65535,
            texturesCount = 0,
            materialText = {},
            materials = {},
        },
    })
    --
    --отправка сообщение в чат
    emul_rpc('onServerMessage',{-1,'когда уже мне купят сухарики! !!!!'})
вся информация находилась в библиотеке, а я зачем-то все рпс переписал... (не помню, вручную или нет)
переделал функцию
 

Vespan

loneliness
Проверенный
2,101
1,632
Lua:
TABLE = {
    -- ['НАЗВАНИЕ RPC ИЗ samp.events.lua'] = {{['НАЗВАНИЕ bitstream rpc ИЗ samp.events.lua']}}
    ['onServerMessage'] = {
        {
            ['text'] = {search='find',who='test',func = function(text) print("SERVER TEXT ",text) end},
            ['color'] = nil,
        },
        {
            ['text'] = {search='==',who='(( Vespan_Dark: text ))'},
            ['color'] = nil,
        },
    },
    ['onShowDialog'] = {
        {
            ['text'] = {search = 'find', who = '%[0%]'},
        }
    },
    ['onSendChat'] = {-- addEventHandler('onSendRpc',function(id,bs)
        {
            ['message'] = {search = 'find', who = 'test'},
        }
    }
}
addEventHandler('onReceiveRpc'--[[or onSendRpc]],function(id,bs)
    local n = {}
    for name,_ in pairs(TABLE) do
        for INTERFACE,_ in pairs(sampev.INTERFACE) do
            if INTERFACE ~= 'BitStreamIO' then
                for k,v in pairs(sampev.INTERFACE[INTERFACE]) do
                    if id == k and v[1] == name then
                        for _,V in pairs(v) do
                            if type(V) == 'table' then
                                for k,v in pairs(V) do
                                    n[k] = sampev.INTERFACE.BitStreamIO.bs_read[v](bs)
                                end
                            end
                        end
                        --
                        for N,_ in ipairs(t[name]) do
                            for kk,vv in pairs(t[name][N]) do
                                if vv ~= nil and type(vv) == 'table' then
                                    if n[kk] ~= nil and (vv.search == 'find' and n[kk]:find(vv.who) or n[kk] == vv.who) then
                                        vv.func = vv.func or function(_) end
                                        vv.func(n[kk])
                                    end
                                end
                            end
                        end

                    end
                end
            end
        end
    end
end)
замена вот, ну вот этого
Lua:
function sampev.onShowDialog(id, style, title, b1, b2, text)
    for k,v in pairs(j) do
        if v.text:find(text) then
            sendTelegramNotification('flint syhariki')
        end
    end
end
function samoev.onShowMessage(color,text)
    for k,v in pairs(j) do
        if v.text:find(text) then
            sendTelegramNotification('flint syhariki')
        end
    end
end
-- и так далее
как пример - можно сделать через (М)имгуи добавление "триггеров" на текст/цвет/стиля/..
 
  • Bug
  • Нравится
  • Вау
Реакции: Moorell, Angr и why ega

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,766
11,208
Описание: простенький селектор. Можно использовать вместо радиобаттонов или комбо. По умолчанию размер 1 пункта выбирается автоматически, но есть возможность указать всем элементам один размер (fixedSize)
Код:
Lua:
function imgui.ItemSelector(name, items, selected, fixedSize, dontDrawBorders)
    assert(items and #items > 1, 'items must be array of strings');
    assert(selected[0], 'Wrong argument #3. Selected must be "imgui.new.int"');
    local DL = imgui.GetWindowDrawList();
    local style = {
        rounding = imgui.GetStyle().FrameRounding,
        padding = imgui.GetStyle().FramePadding,
        col = {
            default = imgui.GetStyle().Colors[imgui.Col.Button],
            hovered = imgui.GetStyle().Colors[imgui.Col.ButtonHovered],
            active = imgui.GetStyle().Colors[imgui.Col.ButtonActive],
            text = imgui.GetStyle().Colors[imgui.Col.Text]
        }
    };
    local pos = imgui.GetCursorScreenPos();
    local start = pos;
    local maxSize = 0;
    for index, item in ipairs(items) do
        local textSize = imgui.CalcTextSize(item);
        local sizeX = (fixedSize or textSize.x) + style.padding.x * 2;
        imgui.SetCursorScreenPos(pos);
        if imgui.InvisibleButton('##imguiSelector_'..item..'_'..tostring(index), imgui.ImVec2(sizeX, textSize.y + style.padding.y * 2)) then
            local old = selected[0];
            selected[0] = index;
            return selected[0], old;
        end
        DL:AddRectFilled(
            pos,
            imgui.ImVec2(pos.x + sizeX, pos.y + textSize.y + style.padding.y * 2),
            imgui.GetColorU32Vec4((selected[0] == index or imgui.IsItemActive()) and style.col.active or (imgui.IsItemHovered() and style.col.hovered or style.col.default)),
            style.rounding,
            (index == 1 and 5 or (index == #items and 10 or 0))
        );
        if index > 1 and not dontDrawBorders then DL:AddLine(imgui.ImVec2(pos.x, pos.y + style.padding.y), imgui.ImVec2(pos.x, pos.y + textSize.y + style.padding.y), imgui.GetColorU32Vec4(imgui.GetStyle().Colors[imgui.Col.Border]), 1) end
        DL:AddText(imgui.ImVec2(pos.x + sizeX / 2 - textSize.x / 2, pos.y + style.padding.y), imgui.GetColorU32Vec4(style.col.text), item);
        pos = imgui.ImVec2(pos.x + sizeX, pos.y);
    end
    DL:AddRect(start, imgui.ImVec2(pos.x, pos.y + imgui.CalcTextSize('A').y + style.padding.y * 2), imgui.GetColorU32Vec4(imgui.GetStyle().Colors[imgui.Col.Border]), imgui.GetStyle().FrameRounding, nil, imgui.GetStyle().FrameBorderSize);
    DL:AddText(imgui.ImVec2(pos.x + style.padding.x, pos.y + (imgui.CalcTextSize(name).y + style.padding.y * 2) / 2 - imgui.CalcTextSize(name).y / 2), imgui.GetColorU32Vec4(style.col.text), name);
end
Пример использования:
Lua:
local imgui = require('mimgui');
local encoding = require('encoding');
encoding.default = 'CP1251';
u8 = encoding.UTF8;

imgui.OnInitialize(function()
    imgui.GetStyle().FrameRounding = 5;
end)

local enabled = imgui.new.int(1);
local input = imgui.new.char[128](u8'Продам гараж, куплю айфон');
local selected, chats = imgui.new.int(1), {
    '/vr',
    '/fam',
    '/j'
};

local frame = imgui.OnFrame(
    function() return true end,
    function(this)
        if imgui.Begin('BLATNOY FLUDER') then
            imgui.Text(u8'Мега блатной автопиар');
            imgui.InputText(u8'Текст', input, 128);
            imgui.ItemSelector(u8'Куда отправлять?', chats, selected);
            imgui.ItemSelector(u8'Статус', { u8'Вкл', u8'Выкл' }, enabled, 60);
            imgui.End();
        end
    end
)
1679670245296.png

Цвета и закругление берутся из стиля окна (imgui.Col.Button, imgui.Col.ButtonHovered, imgui.Col.ButtonActive, imgui.Col.Text)
 
Последнее редактирование:

Vespan

loneliness
Проверенный
2,101
1,632
удобная функция imgui(!!! !! !! !! !) для выбора даты
Lua:
--[[
bool result, int edit time = imgui.Calendar(const char,button name&os.date format,int unix time,table name days,imgui.ImVec2 size button)
]]
function imgui.Calendar(label,buttonName,time,days,sizebutton)
    days = days or {['mo'] = 'Mo',['tu'] = 'Tu',['we'] = 'We',['th'] = 'Th',['fr'] = 'Fr',['sa'] = 'Sa',['su'] = 'Su',}
    local daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31}
    if imgui_calendar == nil then imgui_calendar = {} end
    if imgui_calendar[label] == nil then imgui_calendar[label] = {
        previousDate = time
    } end
    local t,editTime = imgui_calendar[label],time
    if imgui.Button(os.date(buttonName,time),sizebutton or imgui.ImVec2(0,0)) then
        imgui.OpenPopup(label)
    end
    if imgui.BeginPopup(label) then

        imgui.SetCursorPosX(imgui.GetWindowWidth() /2 - imgui.CalcTextSize(os.date('%B %Y',time)).x /2)
        imgui.Text(os.date('%B %Y',time))
        local Y = imgui.GetCursorPosY()-imgui.CalcTextSize(os.date('%B %Y',time)).y

        if t.previousDate ~= time then
            imgui.SetCursorPosX(imgui.GetWindowWidth() /2 - imgui.CalcTextSize('previous date '..os.date('%d.%m.%Y',t.previousDate)).x /2)
            imgui.Text('previous date '..os.date('%d.%m.%Y',t.previousDate))
        end

        imgui.Spacing()
        imgui.Columns(7,'_',true)
        for k,v in pairs(days) do
            imgui.SetCursorPosX((imgui.GetColumnOffset() + (imgui.GetColumnWidth() / 2)) - imgui.CalcTextSize(tostring(v)).x / 2)
            imgui.Text(v)
            imgui.NextColumn()
        end
        for i = 1,daysInMonths[tonumber(os.date('%m',time))] do
            if i == 1 then
                local K = 0
                for k,v in pairs(days) do
                    K = K + 1
                    if (os.date('%a',(time-(86400*((tonumber(os.date('%d',time)))-1) ))):lower()):sub(1,2) == k then
                        for i = 1,K-1 do
                            imgui.NextColumn()
                        end
                    end
                end
            end
            imgui.SetCursorPosX((imgui.GetColumnOffset() + (imgui.GetColumnWidth() / 2)) - imgui.CalcTextSize(tostring(i)).x+5 / 2)
            imgui.PushStyleColor(23,imgui.GetStyle().Colors[(os.date('%d',time):gsub('^0','') == tostring(i) and 25 or 23)] )
            if imgui.Button(tostring(i)) then
                time = os.time({year = os.date("%Y",time), month = os.date('%m',time), day = i,hour = os.date('%H',time), min = os.date('%M',time), sec = os.date('%S',time), isdst = false})
            end
            imgui.PopStyleColor()
            imgui.NextColumn()
        end

        imgui.Columns(1)
        imgui.Text(string.rep('\t',15))
        -- <|>
        imgui.SetCursorPos(imgui.ImVec2(imgui.GetWindowWidth()-imgui.CalcTextSize('>').x-16,Y-2.5))
        if imgui.SmallButton('>') then
            time = os.time({year = os.date("%Y",time), month = os.date('%m',time)+1, day = 1,hour = os.date('%H',time), min = os.date('%M',time), sec = os.date('%S',time), isdst = false})
        end

        imgui.SetCursorPos(imgui.ImVec2(6,Y-2.5))
        if imgui.SmallButton('<') then
            time = os.time({year = os.date("%Y",time), month = os.date('%m',time)-1, day = 1,hour = os.date('%H',time), min = os.date('%M',time), sec = os.date('%S',time), isdst = false})
        end

        imgui.EndPopup()
    end
    if not imgui.IsPopupOpen(label) then imgui_calendar[label] = nil end
    return editTime ~= time, time
end
using:
Lua:
TIME = 1679667209
function main()
--      
        local b,t = imgui.Calendar('test',u8'ДАТА/DATE %d.%m.%Y',TIME)
        if b then sampAddChatMessage("EDIT TIME!") TIME = t end
        imgui.Text('%s,%s',b,t)
1679672328027.png
1679672341336.png
1679672366635.png
 

CaJlaT

Овощ
Модератор
2,806
2,604
удобная функция imgui(!!! !! !! !! !) для выбора даты
Lua:
--[[
bool result, int edit time = imgui.Calendar(const char,button name&os.date format,int unix time,table name days,imgui.ImVec2 size button)
]]
function imgui.Calendar(label,buttonName,time,days,sizebutton)
    days = days or {['mo'] = 'Mo',['tu'] = 'Tu',['we'] = 'We',['th'] = 'Th',['fr'] = 'Fr',['sa'] = 'Sa',['su'] = 'Su',}
    local daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31}
    if imgui_calendar == nil then imgui_calendar = {} end
    if imgui_calendar[label] == nil then imgui_calendar[label] = {
        previousDate = time
    } end
    local t,editTime = imgui_calendar[label],time
    if imgui.Button(os.date(buttonName,time),sizebutton or imgui.ImVec2(0,0)) then
        imgui.OpenPopup(label)
    end
    if imgui.BeginPopup(label) then

        imgui.SetCursorPosX(imgui.GetWindowWidth() /2 - imgui.CalcTextSize(os.date('%B %Y',time)).x /2)
        imgui.Text(os.date('%B %Y',time))
        local Y = imgui.GetCursorPosY()-imgui.CalcTextSize(os.date('%B %Y',time)).y

        if t.previousDate ~= time then
            imgui.SetCursorPosX(imgui.GetWindowWidth() /2 - imgui.CalcTextSize('previous date '..os.date('%d.%m.%Y',t.previousDate)).x /2)
            imgui.Text('previous date '..os.date('%d.%m.%Y',t.previousDate))
        end

        imgui.Spacing()
        imgui.Columns(7,'_',true)
        for k,v in pairs(days) do
            imgui.SetCursorPosX((imgui.GetColumnOffset() + (imgui.GetColumnWidth() / 2)) - imgui.CalcTextSize(tostring(v)).x / 2)
            imgui.Text(v)
            imgui.NextColumn()
        end
        for i = 1,daysInMonths[tonumber(os.date('%m',time))] do
            if i == 1 then
                local K = 0
                for k,v in pairs(days) do
                    K = K + 1
                    if (os.date('%a',(time-(86400*((tonumber(os.date('%d',time)))-1) ))):lower()):sub(1,2) == k then
                        for i = 1,K-1 do
                            imgui.NextColumn()
                        end
                    end
                end
            end
            imgui.SetCursorPosX((imgui.GetColumnOffset() + (imgui.GetColumnWidth() / 2)) - imgui.CalcTextSize(tostring(i)).x+5 / 2)
            imgui.PushStyleColor(23,imgui.GetStyle().Colors[(os.date('%d',time):gsub('^0','') == tostring(i) and 25 or 23)] )
            if imgui.Button(tostring(i)) then
                time = os.time({year = os.date("%Y",time), month = os.date('%m',time), day = i,hour = os.date('%H',time), min = os.date('%M',time), sec = os.date('%S',time), isdst = false})
            end
            imgui.PopStyleColor()
            imgui.NextColumn()
        end

        imgui.Columns(1)
        imgui.Text(string.rep('\t',15))
        -- <|>
        imgui.SetCursorPos(imgui.ImVec2(imgui.GetWindowWidth()-imgui.CalcTextSize('>').x-16,Y-2.5))
        if imgui.SmallButton('>') then
            time = os.time({year = os.date("%Y",time), month = os.date('%m',time)+1, day = 1,hour = os.date('%H',time), min = os.date('%M',time), sec = os.date('%S',time), isdst = false})
        end

        imgui.SetCursorPos(imgui.ImVec2(6,Y-2.5))
        if imgui.SmallButton('<') then
            time = os.time({year = os.date("%Y",time), month = os.date('%m',time)-1, day = 1,hour = os.date('%H',time), min = os.date('%M',time), sec = os.date('%S',time), isdst = false})
        end

        imgui.EndPopup()
    end
    if not imgui.IsPopupOpen(label) then imgui_calendar[label] = nil end
    return editTime ~= time, time
end
using:
Lua:
TIME = 1679667209
function main()
--    
        local b,t = imgui.Calendar('test',u8'ДАТА/DATE %d.%m.%Y',TIME)
        if b then sampAddChatMessage("EDIT TIME!") TIME = t end
        imgui.Text('%s,%s',b,t)
Посмотреть вложение 194895Посмотреть вложение 194896Посмотреть вложение 194897
Мой вариант на mimgui, написанный ещё 8 марта (мб и наговнил, не старался оптимизировать и превращать в сниппет).
Не копируйте данный код, он у вас работать не будт, это не сниппет, просто пример
1679738509623.png

Lua:
--OnFrame
imgui.SelectDate(nav.log.date[1], imgui.ImVec2((nav.log.date.type == 1 and imgui.GetWindowWidth()-15 or imgui.GetWindowWidth()/2-9), 24))


--Где-то
function dateFormat(format, dateTime) return os.date(format, os.time(dateTime)) end
function getCalendar(date)
    local day, month, year
    if type(date) == 'string' then day, month, year = date:match('(%d+)%.(%d+)%.(%d+)')
    elseif type(date) == 'table' then day, month, year = date.day, date.month, date.year
    else return false end

    local days = {
        today = dateFormat('*t',{day = day, month = month, year = year}),
        last = dateFormat('*t',{day = 0, month = month+1, year = year})
    }

    local monthName = {'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'}
    local daysOfWeek = {7, 1, 2, 3, 4, 5, 6}
    local calendar = {
        {},
        month = string.format('%s', monthName[days.today.month]),
        year = days.today.year,
        day =  days.today.day,
        monthn =  days.today.month
    }
   
    for i = 1, days.last.day do
        local day = dateFormat('*t', {day = i, month = month, year = year})
        if daysOfWeek[day.wday] == 1 then table.insert(calendar, {}) end
        calendar[#calendar][daysOfWeek[day.wday]] = day.day
    end
    for i = 1, 7 do if not calendar[1][i] then calendar[1][i] = '--' end end
    for i = 1, 7 do if not calendar[#calendar][i] then calendar[#calendar][i] = '--' end end
    return calendar
end

function getDateTable(date)
    local day, month, year = date:match('(%d+)%.(%d+)%.(%d+)')
    return os.date('*t', os.time({day = day, month = month, year = year}))
end

function imgui.SelectDate(var, size)
    imgui.PushFont(fonts[16])
    if imgui.Button(ti.ICON_CALENDAR_EVENT..' '..str(var), size) then
        vars.popup = getDateTable(str(var))
        imgui.OpenPopup(u8'Выбор даты##'..str(var))
    end
    imgui.PopFont()
    local X, Y = getScreenResolution()
    if imgui.BeginPopup(u8'Выбор даты##'..str(var)) then
        local calendar = getCalendar(dateFormat('%d.%m.%Y', vars.popup))
        if imgui.Button(ti.ICON_CARET_LEFT..'##2') then
            vars.popup.year = vars.popup.year - 1
            calendar = getCalendar(dateFormat('%d.%m.%Y', vars.popup))
        end
        imgui.SameLine()
        imgui.ButtonDisabled(imgui.GetStyle().Colors[imgui.Col.Button], u8(calendar.year), imgui.ImVec2(110, 0))
        imgui.SameLine()
        if imgui.Button(ti.ICON_CARET_RIGHT..'##2') then
            vars.popup.year = vars.popup.year + 1
            calendar = getCalendar(dateFormat('%d.%m.%Y', vars.popup))
        end
        if imgui.Button(ti.ICON_CARET_LEFT) then
            vars.popup.month = vars.popup.month - 1
            vars.popup.day = 1
            calendar = getCalendar(dateFormat('%d.%m.%Y', vars.popup))
        end
        imgui.SameLine()
        imgui.ButtonDisabled(imgui.GetStyle().Colors[imgui.Col.Button], u8(calendar.month), imgui.ImVec2(110, 0))
        imgui.SameLine()
        if imgui.Button(ti.ICON_CARET_RIGHT) then
            vars.popup.month = vars.popup.month + 1
            vars.popup.day = 1
            calendar = getCalendar(dateFormat('%d.%m.%Y', vars.popup))
        end
        imgui.Text(u8('Пн   Вт  Ср   Чт   Пт  Сб   Вс'))
        for i, v in ipairs(calendar) do
            for ii, day in ipairs(v) do
                if type(day) == 'string' then
                    if imgui.ButtonDisabled(nil, day..'##'..i..ii, imgui.ImVec2(20, 20)) then
                        vars.popup.month = vars.popup.month + (i == 1 and -1 or 1)
                        vars.popup.day = 1
                        calendar = getCalendar(dateFormat('%d.%m.%Y', vars.popup))
                    end
                else
                    local date = dateFormat('%d.%m.%Y', {day = day, month = vars.popup.month, year = vars.popup.year})
                    if imgui.ButtonSelected(date == dateFormat('%d.%m.%Y', vars.popup), tostring(day), imgui.ImVec2(20, 20)) then
                        vars.popup.day = day
                        imgui.StrCopy(var, dateFormat('%d.%m.%Y', vars.popup)..'##'..i..ii)
                        refreshLogs()
                    end
                end
                if ii < #v then imgui.SameLine() end
            end
        end
        imgui.EndPopup()
    end
end

В принципе, можно допилить и вместо -- выводить даты прошлого и следющего месяца, но даже сейчас при нажатии на -- он меняет месяц
 
  • Нравится
Реакции: Moorell

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,766
11,208
Описание: обычный инпут с названием и подсказкой для ввода. Внешний вид инпута зависит от стиля окна (FrameRounding, FramePadding, Col.FrameBg, Col.FrameBgHovered)
Код:
Lua:
function imgui.CustomInput(name, hint, buffer, bufferSize, flags, width)
    local width = width or imgui.GetWindowSize().x / 2;
    local DL = imgui.GetWindowDrawList();
    local pos = imgui.GetCursorScreenPos();
    local nameSize = imgui.CalcTextSize(name);
    local padding = imgui.GetStyle().FramePadding;
    DL:AddRectFilled(
        pos,
        imgui.ImVec2(pos.x + padding.x * 2 + nameSize.x, pos.y + nameSize.y + padding.y * 2),
        imgui.GetColorU32Vec4(imgui.GetStyle().Colors[imgui.Col.FrameBgHovered]),
        imgui.GetStyle().FrameRounding, 1 + 4
    );
    DL:AddRectFilled(
        imgui.ImVec2(pos.x + padding.x * 2 + nameSize.x, pos.y),
        imgui.ImVec2(pos.x + padding.x * 2 + nameSize.x + width, pos.y + nameSize.y + padding.y * 2),
        imgui.GetColorU32Vec4(imgui.GetStyle().Colors[imgui.Col.FrameBg]),
        imgui.GetStyle().FrameRounding,
        10
    );
    DL:AddText(imgui.ImVec2(pos.x + padding.x, pos.y + padding.y), imgui.GetColorU32Vec4(imgui.GetStyle().Colors[imgui.Col.Text]), name);
    imgui.SetCursorScreenPos(imgui.ImVec2(pos.x + padding.x * 2 + nameSize.x, pos.y))
    imgui.PushItemWidth(width);
    imgui.PushStyleColor(imgui.Col.FrameBg, imgui.ImVec4(0, 0, 0, 0));
    local input = imgui.InputTextWithHint('##customInput_'..tostring(name), hint or '', buffer, bufferSize, flags);
    imgui.PopStyleColor();
    imgui.PopItemWidth();

    return input;
end
Пример использования:
Lua:
imgui.CustomInput(u8'Текст рекламы', u8'введи сюда что-нибудь', input, 128);
FramePadding = 10, 10
1679743350696.png

FramePadding = 5, 5
1679743375182.png

FramePadding = 0, 0
1679743390184.png
 

why ega

РП игрок
Модератор
2,539
2,229
Описание: Создает файл из строки с байтами. Чтобы превратить файл в строку с байтами, Вам необходимо скачать .exe из этой статьи и правильно запустить.
Код:
MoonLoader:
function createFile(path, base)          
    local dirPath = path:gsub(path:match("[^\\]*$"), "")
    if not doesDirectoryExist(dirPath) then      
        createDirectory(dirPath)
    end
    local file = io.open(path, "wb")
    file:write(base)
    file:close()  
end
LuaJIT/MoonLoader:
local lfs = require("lfs")

function createFile(path, base)          
    local dirPath = path:gsub(path:match("[^\\]*$"), "")
    if not os.rename(dirPath, dirPath) then      
        lfs.mkdir(dirPath)
    end
    local file = io.open(path, "wb")
    file:write(base)
    file:close()
end
Пример использования:
Lua:
local audio = "" -- байты, не могу вставить их, т.к. пизда редатору тогда

package.cpath = ("%s;D:/DEV/lua/luajit-compiler/luajit/lua/?.dll"):format(package.cpath) -- эта строка нужна для удобства размещения библиотеки в LuaJIT, не обращайте внимания и не используйте, если вы используете функцию под MoonLoader
local lfs = require("lfs")

function createFile(path, base)          
    local dirPath = path:gsub(path:match("[^\\]*$"), "")            
    if not os.rename(dirPath, dirPath) then      
        lfs.mkdir(dirPath)
    end
    local file = io.open(path, "wb")
    file:write(base)
    file:close()  
end

createFile("D:\\DEV\\lua\\scripts\\assets\\lua.mp3", audio) -- передаем в функцию путь и строку с байтами
 

Gorskin

I shit on you
Проверенный
1,246
1,040
Описание: Меняет скорость перемещения в карте. Вверх-вниз. Влево-вправо.
Lua:
local speedInputs = 20.0 -- скорость перемещения по карте
writeMemory(0xEDDFAF, 4, representFloatAsInt(speedInputs), true)
local MapOptionInputs = {
    [1] = 0x577679+2, [2] = 0x5779A8+2,
    [3] = 0x577E70+2, [4] = 0x578320+2,
    [5] = 0x5784B5+2, [6] = 0x578650+2
}
for i = 1, #MapOptionInputs do
    writeMemory(MapOptionInputs[i], 4, 0xEDDFAF, true)
end
 
Последнее редактирование:

lorgon

Известный
657
267
Описание: Получает координаты точек лежащих на поверхности шара (равномерно распределённые)
Lua:
function getPointOnSphere(x0, y0, z0, r, n, i) -- x0, y0, z0 - центр, r - радиус шара, n - максимальное кол-во точек, i - номер точки
    local inc = math.pi * (3 - math.sqrt(5))
    local off = 2 / n
    local y = i * off - 1 + (off / 2)
    local R = math.sqrt(1 - y * y)
    local phi = i * inc
    local x = x0 + r * math.cos(phi) * R
    local y = y0 + r * y
    local z = z0 + r * math.sin(phi) * R
    return x, y, z
end

Пример использования:
Lua:
local n = 100
local radius = 25.0
for i = 1, n do
    local x, y, z = getPointOnSphere(center_x, center_y, center_z, radius, n, i)
    drawPoint(x, y, z) -- гипотетическая функция
end

1680785309934.png
 

ARMOR

kjor32 is legend
Модератор
4,846
6,071
Описание: Рисует полоску прогресса( Такую же как полоска ХП, Брони ).

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

local drawBarChart = ffi.cast("void (__cdecl *)(float x, float y, unsigned short width, unsigned char height, float progress, signed char progressAdd, unsigned char drawPercentage, unsigned char drawBlackBorder, unsigned long color, unsigned long addColor)", 0x728640)

Пример использования: Полоска выносливости
Lua:
-- Пример говно.
local ffi = require 'ffi'
local memory = require 'memory'
local sizeX, sizeY = getScreenResolution()

local drawBarChart = ffi.cast("void (__cdecl *)(float x, float y, unsigned short width, unsigned char height, float progress, signed char progressAdd, unsigned char drawPercentage, unsigned char drawBlackBorder, unsigned long color, unsigned long addColor)", 0x728640)

function onD3DPresent() -- Нужно вызывать в onD3DPresent(). В обычном беск. цикле работать не будет.
    drawBarChart(sizeX - 280, 70.0, 184, 20, getSprintLocalPlayer(), 0, false, true, 0xFF8438C2, 0)
end

function getSprintLocalPlayer() -- Функция imring
    local float = memory.getfloat(0xB7CDB4)
    return float/31.47000244
end

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

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,766
11,208
Описание: возвращает параметры запуска игры
Код:
Lua:
local ffi = require('ffi')
ffi.cdef('const char* GetCommandLineA(void);')
Пример использования:
проверка на игру с лаунчера арз:
Lua:
print(ffi.string(ffi.C.GetCommandLineA()):find('%-arizona') and 'ты с лаунчера' or 'лошпед')
еще один пример
Lua:
local ffi = require('ffi')
ffi.cdef('const char* GetCommandLineA(void);')
print('Params:', ffi.string(ffi.C.GetCommandLineA()))
1681034016821.png
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,766
11,208
Описание: увидел кринж гайды по отправке запросов в OpenAI api, авторы которых просто скопировал код из моего ANSAI (привет @Sanurial и @JasonEllison )
Код:
Lua:
local requests = require('requests')
local effil = require('effil')
local encoding = require('encoding')
encoding.default = 'CP1251'
u8 = encoding.UTF8

---@class CompletionParameters
---@field model 'gpt-3.5-turbo' | 'text-davinci-003' | 'text-curie-001' | 'text-babbage-001' | 'text-ada-001' | nil
---@field prompt string | nil
---@field temperature number | nil
---@field max_tokens number | nil
---@field top_p number | nil
---@field frequency_penalty number | nil
---@field presence_penalty number | nil
---@field stop table<number, string> | nil

---@class OpenAPI
---@field MODEL { GPT3_5TURBO: 'gpt-3.5-turbo', DAVINCI_003: 'text-davinci-003', CURIE_001: 'text-curie-001', BABBAGE_001: 'text-babbage-001', ADA_001: 'text-ada-001' }
---@field createCompletion fun(self: table, prompt: string | nil, parameters: CompletionParameters | nil)
---@field createCompletionAsync fun(self: table, prompt: string | nil, parameters: CompletionParameters | nil, callbackOk: fun(response: string) | nil, callbackError: fun(error: string) | nil)

---@param token string OpenAI API KEY
---@return OpenAPI
function OpenAI(token)
    assert(token, 'token not provided')
    return setmetatable({
        baseURL = 'https://api.openai.com/v1/completions',
        token = token,
        MODEL = {
            GPT3_5TURBO = 'gpt-3.5-turbo',
            DAVINCI_003 = 'text-davinci-003',
            CURIE_001 = 'text-curie-001',
            BABBAGE_001 = 'text-babbage-001',
            ADA_001 = 'text-ada-001'
        }
    }, {
        __index = function(self, key)
            return ({
                createCompletion = function(prompt, parameters)
                    assert(prompt)
                    return requests.post(self.baseURL, {
                        headers = self.__buildHeaders(),
                        data = self.__buildData(prompt, parameters)
                    })
                end,
                createCompletionAsync = function(___, prompt, parameters, callbackOk, callbackError)
                    local method, url = 'POST', self.baseURL
                    local args = {
                        headers = self.__buildHeaders(),
                        data = u8(encodeJson(self.__buildData(prompt, parameters)))
                    }
                    local resolve, reject = callbackOk, callbackError

                    local request_thread = effil.thread(function (method, url, args)
                        local requests = require('requests')
                        local result, response = pcall(requests.request, method, url, args)
                        if result then
                            response.json, response.xml = nil, nil
                            return true, response
                        else
                            return false, response
                        end
                    end)(method, url, args)
                    if not resolve then resolve = function() end end
                    if not reject then reject = function() end end
                    lua_thread.create(function()
                        local runner = request_thread
                        while true do
                            local status, err = runner:status()
                            if not err then
                                if status == 'completed' then
                                    local result, response = runner:get()
                                    if result then resolve(response) else reject(response) end
                                    return
                                elseif status == 'canceled' then return reject(status) end
                            else return reject(err) end
                            wait(0)
                        end
                    end)
                end,
                __buildHeaders = function(encodeToJson)
                    local headers = {
                        ['Authorization'] = 'Bearer '..self.token,
                        ['Content-Type'] = 'application/json'
                    }
                    return encodeToJson and encodeJson(headers) or headers
                end,
                __buildData = function(prompt, parameters, encodeToJson)
                    local data = {
                        model = parameters.model or self.MODEL.GPT3_5TURBO,
                        prompt = prompt,
                        temperature = parameters.temperature or 0.9,
                        max_tokens = parameters.max_tokens or 150,
                        top_p = parameters.top_p or 1,
                        frequency_penalty = parameters.frequency_penalty or 0,
                        presence_penalty = parameters.presence_penalty or 0.6,
                        stop = parameters.stop or {'You:'}
                    }
                    return encodeToJson and encodeJson(data) or data
                end
            })[key]
        end
    })
end
Пример использования:
Lua:
--// тут функция OpenAPI и прочая хуйня

local api = OpenAI('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') -- токен не рабочий

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('openai', function(prompt)
        local response = api:createCompletion(prompt, { model = api.MODEL.GPT3_5TURBO })
        print('Code:', response.status_code)
        print('Text:', response.text)
    end)
    sampRegisterChatCommand('openaiAsync', function(prompt)
        local callback = {
            ok = function(response)
                print('Code:', response.status_code)
                print('Text:', response.text)
            end,
            error = function(message)
                print('Error sending async request:', message)
            end
        }
        api:createCompletionAsync(prompt, { model = api.MODEL.GPT3_5TURBO }, callback.ok, callback.error)
    end)
    wait(-1)
end
 
Последнее редактирование:

Sanurial

Участник
78
12
Описание: увидел кринж гайды по отправке запросов в OpenAI api, авторы которых просто скопировал код из моего ANSAI (привет @Sanurial и @JasonEllison )
Код:
Lua:
local requests = require('requests')
local effil = require('effil')
local encoding = require('encoding')
encoding.default = 'CP1251'
u8 = encoding.UTF8

---@class CompletionParameters
---@field model 'gpt-3.5-turbo' | 'text-davinci-003' | 'text-curie-001' | 'text-babbage-001' | 'text-ada-001' | nil
---@field prompt string | nil
---@field temperature number | nil
---@field max_tokens number | nil
---@field top_p number | nil
---@field frequency_penalty number | nil
---@field presence_penalty number | nil
---@field stop table<number, string> | nil

---@class OpenAPI
---@field MODEL { GPT3_5TURBO: 'gpt-3.5-turbo', DAVINCI_003: 'text-davinci-003', CURIE_001: 'text-curie-001', BABBAGE_001: 'text-babbage-001', ADA_001: 'text-ada-001' }
---@field createCompletion fun(self: table, prompt: string | nil, parameters: CompletionParameters | nil)
---@field createCompletionAsync fun(self: table, prompt: string | nil, parameters: CompletionParameters | nil, callbackOk: fun(response: string) | nil, callbackError: fun(error: string) | nil)

---@param token string OpenAI API KEY
---@return OpenAPI
function OpenAI(token)
    assert(token, 'token not provided')
    return setmetatable({
        baseURL = 'https://api.openai.com/v1/completions',
        token = token,
        MODEL = {
            GPT3_5TURBO = 'gpt-3.5-turbo',
            DAVINCI_003 = 'text-davinci-003',
            CURIE_001 = 'text-curie-001',
            BABBAGE_001 = 'text-babbage-001',
            ADA_001 = 'text-ada-001'
        }
    }, {
        __index = function(self, key)
            return ({
                createCompletion = function(prompt, parameters)
                    assert(prompt)
                    return requests.post(self.baseURL, {
                        headers = self.__buildHeaders(),
                        data = self.__buildData(prompt, parameters)
                    })
                end,
                createCompletionAsync = function(___, prompt, parameters, callbackOk, callbackError)
                    local method, url = 'POST', self.baseURL
                    local args = {
                        headers = self.__buildHeaders(),
                        data = u8(encodeJson(self.__buildData(prompt, parameters)))
                    }
                    local resolve, reject = callbackOk, callbackError

                    local request_thread = effil.thread(function (method, url, args)
                        local requests = require('requests')
                        local result, response = pcall(requests.request, method, url, args)
                        if result then
                            response.json, response.xml = nil, nil
                            return true, response
                        else
                            return false, response
                        end
                    end)(method, url, args)
                    if not resolve then resolve = function() end end
                    if not reject then reject = function() end end
                    lua_thread.create(function()
                        local runner = request_thread
                        while true do
                            local status, err = runner:status()
                            if not err then
                                if status == 'completed' then
                                    local result, response = runner:get()
                                    if result then resolve(response) else reject(response) end
                                    return
                                elseif status == 'canceled' then return reject(status) end
                            else return reject(err) end
                            wait(0)
                        end
                    end)
                end,
                __buildHeaders = function(encodeToJson)
                    local headers = {
                        ['Authorization'] = 'Bearer '..self.token,
                        ['Content-Type'] = 'application/json'
                    }
                    return encodeToJson and encodeJson(headers) or headers
                end,
                __buildData = function(prompt, parameters, encodeToJson)
                    local data = {
                        model = parameters.model or self.MODEL.GPT3_5TURBO,
                        prompt = prompt,
                        temperature = parameters.temperature or 0.9,
                        max_tokens = parameters.max_tokens or 150,
                        top_p = parameters.top_p or 1,
                        frequency_penalty = parameters.frequency_penalty or 0,
                        presence_penalty = parameters.presence_penalty or 0.6,
                        stop = parameters.stop or {'You:'}
                    }
                    return encodeToJson and encodeJson(data) or data
                end
            })[key]
        end
    })
end
Пример использования:
Lua:
--// тут функция OpenAPI и прочая хуйня

local api = OpenAI('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') -- токен не рабочий

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('openai', function(prompt)
        local response = api:createCompletion(prompt, { model = api.MODEL.GPT3_5TURBO })
        if response.status_code ~= 200 then
            print('Code:', response.status_code)
            print('Text:', response.text)
            return
        end
        print(response.text)
    end)
    sampRegisterChatCommand('openaiAsync', function(prompt)
        local callback = {
            ok = function(response)
                print('Code:', response.status_code)
                print('Text:', response.text)
            end,
            error = function(message)
                print('Error sending async request:', message)
            end
        }
        api:createCompletionAsync(prompt, { model = api.MODEL.GPT3_5TURBO }, callback.ok, callback.error)
    end)
    wait(-1)
end
Самое интересное что я и не присваивал код себе, а указывал темы откуда брал код :)
Моя тема: https://www.blast.hk/threads/174324/#post-1293248
Так-же обрати внимание что и @JasonEllison указывал источником кода на твою тему https://www.blast.hk/threads/171743/#post-1287059
 
  • Эм
Реакции: lorgon