Информация Полезные функции

_=Gigant=_

Известный
134
191
C++:
uint8_t getPlayerWeaponModelID(int iPlayerID)
{
    if (g_Players == NULL || iPlayerID < 0 || iPlayerID > SAMP_MAX_PLAYERS)
        return NULL;
    if (iPlayerID == g_Players->sLocalPlayerID)
    {
        if (g_Players->pLocalPlayer->pSAMP_Actor == NULL)
            return NULL;

        return g_Players->pLocalPlayer->onFootData.byteCurrentWeapon;
    }
    if (g_Players->pRemotePlayer[iPlayerID]->pPlayerData == NULL)
        return NULL;

    return g_Players->pRemotePlayer[iPlayerID]->pPlayerData->onFootData.byteCurrentWeapon;
}

const char* getPlayerWeapon(int iPlayerID)
{
    if (g_Players == NULL || iPlayerID < 0 || iPlayerID > SAMP_MAX_PLAYERS)
        return NULL;

    if (iPlayerID == g_Players->sLocalPlayerID)
    {
        for (int wep = 0; weapon_list[wep].name != nullptr; wep++)
        {
            const struct weapon_entry *weapon = &weapon_list[wep];

            if (weapon->id == getPlayerWeaponModelID(iPlayerID))
                return weapon->name;
        }
    }

    if (g_Players->pRemotePlayer[iPlayerID] == NULL)
        return NULL;

    if (g_Players->pRemotePlayer[iPlayerID]->pPlayerData == NULL)
        return NULL;

    for (int wep = 0; weapon_list[wep].name != nullptr; wep++)
    {
        const struct weapon_entry *weapon = &weapon_list[wep];

        if (weapon->id == getPlayerWeaponModelID(iPlayerID))
            return weapon->name;
    }

    return NULL;
}

here if someone need to get current player weapon name
usage: ("%s", getPlayerWeapon(playerid));

Target Selector with multiple options for samp

C++:
void renderTargetSelector(int PlayerID, byte BONE_ID_BOX, byte BONE_ID_TARGET, byte BONE_ID_MY, byte HP_BAR_BONE, float box_width, float box_add_x_pos, float box_height, float box_add_y_pos
    , bool DrawLine, bool DrawBox, bool bShowTargetPos, int pos_text_add_x, int pos_text_add_y, bool AddHealthBar, bool bShowHPValue, float hp_bar_width, float hp_bar_height
    , bool bCopyTargetRotation, bool bFollowTarget
    , D3DCOLOR COLOR_HP_BAR, D3DCOLOR COLOR_POS_TEXT, D3DCOLOR COLOR_SAME, D3DCOLOR COLOR_BOX, D3DCOLOR COLOR_LINE
    , bool bUseSameColors, bool bUseTargetColor, bool bUseCustomColors)
{
    traceLastFunc("renderTargetSelector()");

    if (cheat_state->_generic.cheat_panic_enabled)
        return;

    if (!pGameInterface)
        return;

    if (!g_dwSAMP_Addr || !g_SAMP || !g_Players)
        return;

    if (gta_menu_active())
        return;

    actor_info * me = actor_info_get(ACTOR_SELF, NULL);
    actor_info * target = getGTAPedFromSAMPPlayerID(PlayerID);

    if (!me)
        return;

    if (!target)
        return;

    CPed *pPedTarget = pGameInterface->GetPools()->GetPed((DWORD*)target);
    CPed *pPedSelf = pGameInterface->GetPools()->GetPed((DWORD*)me);

    D3DXVECTOR3 box_get_vec, target_vec_box_set, target_pos_get, render_pos, hp_bar_check, hp_bar_render;
    CVector target_bone_for_box_vec = GetBonePosition(PlayerID, BONE_ID_BOX);
    CVector target_mainbone_vec = GetBonePosition(PlayerID, BONE_ID_TARGET);
    CVector target_hpbar_bone_vec = GetBonePosition(PlayerID, HP_BAR_BONE); // hp bar set
    CVector my_bone_vec = GetBonePosition(ACTOR_SELF, BONE_ID_MY);

    float * f_pos = &target->base.matrix[4 * 3];

    box_get_vec.x = CVecToD3DXVEC(target_bone_for_box_vec).x;
    box_get_vec.y = CVecToD3DXVEC(target_bone_for_box_vec).y;
    box_get_vec.z = CVecToD3DXVEC(target_bone_for_box_vec).z;
    CalcScreenCoors(&box_get_vec, &target_vec_box_set);

    D3DCOLOR color_target = samp_color_get(PlayerID);

    if (render)
    {

        if (bShowTargetPos)
        {
            char print_pos[128];
            target_pos_get.x = f_pos[0];
            target_pos_get.y = f_pos[1];
            target_pos_get.z = f_pos[2];
            CalcScreenCoors(&target_pos_get, &render_pos);

            if (render_pos.z < 1.0f)
            {
                sprintf(print_pos, "Pos X %0.02f Y %0.02f Z %0.02f", target_pos_get.x, target_pos_get.y, target_pos_get.z);

                if (bUseSameColors)
                {
                    pD3DFont_3DInformer->PrintShadow(render_pos.x + pos_text_add_x, render_pos.y + pos_text_add_y, COLOR_SAME, print_pos);
                }
                else if (bUseTargetColor)
                {
                    pD3DFont_3DInformer->PrintShadow(render_pos.x + pos_text_add_x, render_pos.y + pos_text_add_y, color_target, print_pos);
                }
                else if (bUseCustomColors)
                {
                    pD3DFont_3DInformer->PrintShadow(render_pos.x + pos_text_add_x, render_pos.y + pos_text_add_y, COLOR_POS_TEXT, print_pos);
                }
            }
        }

        if (bUseSameColors)
        {
            if (DrawBox)
                render->D3DBox(target_vec_box_set.x + box_add_x_pos, target_vec_box_set.y + box_add_y_pos, box_width, box_height, COLOR_SAME);

            if (DrawLine)
                render->DrawLine(CVecToD3DXVEC(target_mainbone_vec), CVecToD3DXVEC(my_bone_vec), COLOR_SAME);
        }
        else if (bUseTargetColor)
        {
            if (DrawBox)
                render->D3DBox(target_vec_box_set.x + box_add_x_pos, target_vec_box_set.y + box_add_y_pos, box_width, box_height, color_target);

            if (DrawLine)
                render->DrawLine(CVecToD3DXVEC(target_mainbone_vec), CVecToD3DXVEC(my_bone_vec), color_target);
        }
        else if (bUseCustomColors)
        {
            if (DrawBox)
                render->D3DBox(target_vec_box_set.x + box_add_x_pos, target_vec_box_set.y + box_add_y_pos, box_width, box_height, COLOR_BOX);

            if (DrawLine)
                render->DrawLine(CVecToD3DXVEC(target_mainbone_vec), CVecToD3DXVEC(my_bone_vec), COLOR_LINE);
        }

        if (AddHealthBar)
        {
            hp_bar_check.x = CVecToD3DXVEC(target_hpbar_bone_vec).x;
            hp_bar_check.y = CVecToD3DXVEC(target_hpbar_bone_vec).y;
            hp_bar_check.z = CVecToD3DXVEC(target_hpbar_bone_vec).z;
            CalcScreenCoors(&hp_bar_check, &hp_bar_render);

            char hp_bar[128];
            float hp_bar_lenght = g_Players->pRemotePlayer[PlayerID]->pPlayerData->fActorHealth + hp_bar_width;
        
            if (bShowHPValue)
                _snprintf_s(hp_bar, sizeof(hp_bar) - 1, "%u", g_Players->pRemotePlayer[PlayerID]->pPlayerData->onFootData.byteHealth);

            if (bUseCustomColors)
            {
                render->D3DBox(hp_bar_render.x, hp_bar_render.y, hp_bar_lenght, hp_bar_height, COLOR_HP_BAR);
                if(bShowHPValue)
                    pD3DFont_Nametags->PrintShadow(hp_bar_render.x + hp_bar_lenght, hp_bar_render.y, COLOR_HP_BAR, hp_bar);
            }
            else if (bUseTargetColor)
            {
                render->D3DBox(hp_bar_render.x, hp_bar_render.y, hp_bar_lenght, hp_bar_height, color_target);
                if (bShowHPValue)
                    pD3DFont_Nametags->PrintShadow(hp_bar_render.x + hp_bar_lenght, hp_bar_render.y, color_target, hp_bar);
            }
            else if (bUseSameColors)
            {
                render->D3DBox(hp_bar_render.x, hp_bar_render.y, hp_bar_lenght, hp_bar_height, COLOR_SAME);
                if (bShowHPValue)
                    pD3DFont_Nametags->PrintShadow(hp_bar_render.x + hp_bar_lenght, hp_bar_render.y, COLOR_SAME, hp_bar);

            }
        }
    }

    if (bCopyTargetRotation)
    {
        vect3_copy(&target->fCurrentRotation, &me->fCurrentRotation);
    }

    if (bFollowTarget)
    {
        float follow_pos_copy[3];
        vect3_copy(&target->base.matrix[4 * 3], follow_pos_copy);

        follow_pos_copy[2] -= 1.0f;

        cheat_actor_teleport(me, follow_pos_copy, gta_interior_id_get());
    }
}
 
Последнее редактирование:

ALF

Известный
Проверенный
320
537
удобная функция для установки таймеров
C++:
#include <chrono> // если не хотите тащить chrono, можно использовать GetTickCount() или другую аналогичную функцию

template <typename T>
void addTimer(T Func, int64_t Wait)
{
    using std::chrono::duration_cast;
    using std::chrono::milliseconds;
    using std::chrono::steady_clock;

    static int64_t iTime = 0;

    if (duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count() - iTime > Wait)
    {
        Func();
        iTime = duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
    }
}
C++:
void Foo() {
    std::cout << "timer1" << std::endl;
}

int main()
{
    auto func = []()
    {
        std::cout << "timer2" << std::endl;
    };

    while (true)
    {
        addTimer(Foo, 5000);
        addTimer(func, 2000);
        addTimer(
            []() {
                std::cout << "timer3" << std::endl;
            }, 8000);
    }

    return 0;
}

чуть-чуть информации которая может пригодиться при использовании лямбда-выражений
Код:
[] - без захвата переменных
[=] - все переменные захватываются по значению
[&] - все переменные захватываются по ссылке
 

Cake_

Известный
Проверенный
263
313
Круглый слайдер для "ImGui"
C++:
static bool MyKnob(const char* label, float* p_value, float v_min, float v_max)
{
    ImGuiIO& io = ImGui::GetIO();
    ImGuiStyle& style = ImGui::GetStyle();

    float radius_outer = 20.0f;
    ImVec2 pos = ImGui::GetCursorScreenPos();
    ImVec2 center = ImVec2(pos.x + radius_outer, pos.y + radius_outer);
    float line_height = ImGui::GetTextLineHeight();
    ImDrawList* draw_list = ImGui::GetWindowDrawList();

    float ANGLE_MIN = 3.141592f * 0.75f;
    float ANGLE_MAX = 3.141592f * 2.25f;

    ImGui::InvisibleButton(label, ImVec2(radius_outer*2, radius_outer*2 + line_height + style.ItemInnerSpacing.y));
    bool value_changed = false;
    bool is_active = ImGui::IsItemActive();
    bool is_hovered = ImGui::IsItemActive();
    if (is_active && io.MouseDelta.x != 0.0f)
    {
        float step = (v_max - v_min) / 200.0f;
        *p_value += io.MouseDelta.x * step;
        if (*p_value < v_min) *p_value = v_min;
        if (*p_value > v_max) *p_value = v_max;
        value_changed = true;
    }

    float t = (*p_value - v_min) / (v_max - v_min);
    float angle = ANGLE_MIN + (ANGLE_MAX - ANGLE_MIN) * t;
    float angle_cos = cosf(angle), angle_sin = sinf(angle);
    float radius_inner = radius_outer*0.40f;
    draw_list->AddCircleFilled(center, radius_outer, ImGui::GetColorU32(ImGuiCol_FrameBg), 16);
    draw_list->AddLine(ImVec2(center.x + angle_cos*radius_inner, center.y + angle_sin*radius_inner), ImVec2(center.x + angle_cos*(radius_outer-2), center.y + angle_sin*(radius_outer-2)), ImGui::GetColorU32(ImGuiCol_SliderGrabActive), 2.0f);
    draw_list->AddCircleFilled(center, radius_inner, ImGui::GetColorU32(is_active ? ImGuiCol_FrameBgActive : is_hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
    draw_list->AddText(ImVec2(pos.x, pos.y + radius_outer * 2 + style.ItemInnerSpacing.y), ImGui::GetColorU32(ImGuiCol_Text), label);

    if (is_active || is_hovered)
    {
        ImGui::SetNextWindowPos(ImVec2(pos.x - style.WindowPadding.x, pos.y - line_height - style.ItemInnerSpacing.y - style.WindowPadding.y));
        ImGui::BeginTooltip();
        ImGui::Text("%.3f", *p_value);
        ImGui::EndTooltip();
    }
    return value_changed;
}
https://imgur.com/a/c0B3A9s
 
Последнее редактирование:

_=Gigant=_

Известный
134
191
C++:
bool IsPlayerInCar(int PlayerID)
{
    if (g_Players == NULL)
        return NULL;
    if(PlayerID == g_Players->sLocalPlayerID)
        return NULL;
    if (g_Players->pRemotePlayer == NULL)
        return NULL;
    if (g_Players->pRemotePlayer[PlayerID]->pPlayerData == NULL)
        return NULL;
    if (g_Players->pRemotePlayer[PlayerID]->pPlayerData->pSAMP_Actor == NULL)
        return NULL;

    return g_Players->pRemotePlayer[PlayerID]->pPlayerData->pSAMP_Actor->pGTA_Ped->pedFlags.bInVehicle;
};

C++:
bool IsOurPlayerInCar()
{
    if (g_Players == NULL)
        return NULL;
    if (g_Players->pLocalPlayer == NULL)
        return NULL;
    if (g_Players->pLocalPlayer->pSAMP_Actor == NULL)
        return NULL;

    return g_Players->pLocalPlayer->pSAMP_Actor->pGTA_Ped->pedFlags.bInVehicle;
};

C++:
//usage "%u" getPlayerVehicleModelID_V2(id...)
uint16_t getPlayerVehicleModelID_V2(int iPlayerID)
{
    if (g_Players == NULL || iPlayerID < 0 || iPlayerID > SAMP_MAX_PLAYERS)
        return NULL;
    if (iPlayerID == g_Players->sLocalPlayerID)
    {
        if (g_Players->pLocalPlayer->pSAMP_Actor == NULL
            || g_Players->pLocalPlayer->pSAMP_Actor->pGTA_Ped->vehicle == NULL)
            return NULL;

       if (IsOurPlayerInCar())
        return g_Players->pLocalPlayer->pSAMP_Actor->pGTA_Ped->vehicle->base.model_alt_id;
    }
    if (g_Players->pRemotePlayer[iPlayerID]->pPlayerData == NULL)
        return NULL;
    if (g_Players->pRemotePlayer[iPlayerID]->pPlayerData->pSAMP_Vehicle == NULL)
        return NULL;
    if (g_Players->pRemotePlayer[iPlayerID]->pPlayerData->pSAMP_Vehicle->pGTA_Vehicle == NULL)
        return NULL;

    if (IsPlayerInCar(iPlayerID))
    return g_Players->pRemotePlayer[iPlayerID]->pPlayerData->pSAMP_Vehicle->pGTA_Vehicle->base.model_alt_id;

    return NULL;
}

C++:
// usage "%s" getPlayerVehicleName(id...);
const char * getPlayerVehicleName(int PlayerID)
{
    if (g_Players == NULL || PlayerID < 0 || PlayerID > SAMP_MAX_PLAYERS)
        return NULL;

    const struct vehicle_entry    *get_vehicles;

    if (PlayerID == g_Players->sLocalPlayerID)
    {
        if (g_Players->pLocalPlayer->pSAMP_Actor == NULL
            || g_Players->pLocalPlayer->pSAMP_Actor->pGTA_Ped->vehicle == NULL)
            return NULL;

        if (IsOurPlayerInCar())
        {
            get_vehicles = gta_vehicle_get_by_id(getPlayerVehicleModelID_V2(PlayerID));
            return get_vehicles->name;
        }
    }
    if (g_Players->pRemotePlayer[PlayerID]->pPlayerData == NULL)
        return NULL;
    if (g_Players->pRemotePlayer[PlayerID]->pPlayerData->pSAMP_Vehicle == NULL)
        return NULL;
    if (g_Players->pRemotePlayer[PlayerID]->pPlayerData->pSAMP_Vehicle->pGTA_Vehicle == NULL)
        return NULL;

    if (IsPlayerInCar(PlayerID))
    {
        get_vehicles = gta_vehicle_get_by_id(getPlayerVehicleModelID_V2(PlayerID));
        return get_vehicles->name;
    }

    return NULL;
}
 
Последнее редактирование:
  • Нравится
Реакции: sc6ut

Cake_

Известный
Проверенный
263
313
Конвертация utf8 в ansi
C++:
char* utf8_to_ansi(char* szU8)
{
    int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), NULL, 0);
    wchar_t* wszString = new wchar_t[wcsLen + 1];
    ::MultiByteToWideChar(CP_UTF8, NULL, szU8, strlen(szU8), wszString, wcsLen);
    wszString[wcsLen] = '\0';

    int ansiLen = ::WideCharToMultiByte(CP_ACP, NULL, wszString, wcslen(wszString), NULL, 0, NULL, NULL);
    char* szAnsi = new char[ansiLen + 1];
    ::WideCharToMultiByte(CP_ACP, NULL, wszString, wcslen(wszString), szAnsi, ansiLen, NULL, NULL);
    szAnsi[ansiLen] = '\0';

    return szAnsi;
}
 

_=Gigant=_

Известный
134
191
C++:
struct Color2
{
    int r;
    int g;
    int b;
    int a;

    Color2()
    {
        this->r = 0;
        this->g = 0;
        this->b = 0;
        this->a = 255;
    }

    Color2(int r, int g, int b)
    {
        this->r = r;
        this->g = g;
        this->b = b;
        this->a = 255;
    }

    Color2(int r, int g, int b, int a)
    {
        this->r = r;
        this->g = g;
        this->b = b;
        this->a = a;
    }

    Color2 operator / (float div)
    {
        Color2 color = *this;
        color.r = color.r / div;
        color.g = color.g / div;
        color.b = color.b / div;
        return color;
    }

    Color2& operator /= (float div)
    {
        Color2& color = *this;
        color.r /= div;
        color.g /= div;
        color.b /= div;
        return color;
    }

    Color2& operator *= (float coeff)
    {
        Color2& color = *this;
        color.r *= coeff;
        color.g *= coeff;
        color.b *= coeff;
        return color;
    }

    static Color2 FromHSB(float hue, float saturation, float brightness)
    {
        float h = hue == 1.0f ? 0 : hue * 6.0f;
        float f = h - (int)h;
        float p = brightness * (1.0f - saturation);
        float q = brightness * (1.0f - saturation * f);
        float t = brightness * (1.0f - (saturation * (1.0f - f)));

        if (h < 1)
        {
            return Color2(
                (unsigned char)(brightness * 255),
                (unsigned char)(t * 255),
                (unsigned char)(p * 255)
            );
        }
        else if (h < 2)
        {
            return Color2(
                (unsigned char)(q * 255),
                (unsigned char)(brightness * 255),
                (unsigned char)(p * 255)
            );
        }
        else if (h < 3)
        {
            return Color2(
                (unsigned char)(p * 255),
                (unsigned char)(brightness * 255),
                (unsigned char)(t * 255)
            );
        }
        else if (h < 4)
        {
            return Color2(
                (unsigned char)(p * 255),
                (unsigned char)(q * 255),
                (unsigned char)(brightness * 255)
            );
        }
        else if (h < 5)
        {
            return Color2(
                (unsigned char)(t * 255),
                (unsigned char)(p * 255),
                (unsigned char)(brightness * 255)
            );
        }
        else
        {
            return Color2(
                (unsigned char)(brightness * 255),
                (unsigned char)(p * 255),
                (unsigned char)(q * 255)
            );
        }
    }

    static Color2 FromImColor(ImColor color)
    {
        return Color2(
            (int)(color.Value.x * 255),
            (int)(color.Value.y * 255),
            (int)(color.Value.z * 255),
            (int)(color.Value.w * 255)
        );
    }

    static ImColor ToImColor(Color2 color)
    {
        return ImColor(
            color.r / 255.f,
            color.g / 255.f,
            color.b / 255.f,
            color.a / 255.f
        );
    }

}; //By StickeyAdv

C++:
ImVec4 TotalRainbow(int speed)
{
    ImVec4 color;
    static float rainbow;
    float misc;
    DWORD rainbow_x;
    rainbow += misc = 0.0001f * speed;
    rainbow_x = Color2::ToImColor(Color2::FromHSB(rainbow, 1.0f, 1.0f));
    if (rainbow > 1.f) rainbow = 0.0f;
    return color = Color2::ToImColor(Color2::FromHSB(rainbow, 1.0f, 1.0f));
}

example usage

ImGui::PushStyleColor(ImGuiCol_Text, TotalRainbow(20)); //or in your header file: extern ImVec4 TotalRainbow(int speed = 20)
ImGui::Text("vodka");
ImGui::PopStyleColor(1);


C++:
D3DCOLOR CustomImVec4_D3DCOLOR(ImVec4 color) //use in ImGui::ColorEdit's
{
    return D3DCOLOR_RGBA((int)(color.x * 255), (int)(color.y * 255), (int)(color.z*255),(int)(color.w*255));
}

example use

ImVec4 color;
render->D3DBox(,,,CustomImVec4_D3DCOLOR(color));
ImGui::ColorEdit3("##BoxColor", (float*)&color);
 
Последнее редактирование:
  • Нравится
Реакции: corruptmemory и Rjx13

Carrentine

Потрачен
569
460
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Описание: находит ближайшего к вашему педу игрока, на определенном радиусе от прицела.
Код:
C++:
void vect3_copy(const float in[3], float out[3])
{
    memcpy(out, in, sizeof(float) * 3);
}

float GetDistance(D3DXVECTOR3 target_1, D3DXVECTOR3 target_2)
{
    return sqrt((target_2.x - target_1.x) * (target_2.x - target_1.x) + (target_2.y - target_1.y) * (target_2.y - target_1.y) + (target_2.z - target_1.z) * (target_2.z - target_1.z));
}

int GetNearestPed(float radius)
{
    int nearestPED = -1;
    float maxRadius = 20000.0f, currentRadius;
    D3DXVECTOR3 posPed, myPosPed, screenPos;
    actor_info *MyActorInfo = SF->getSAMP()->getPlayers()->pLocalPlayer->pSAMP_Actor->pGTA_Ped;
    vect3_copy(MyActorInfo->base.matrix + 12, myPosPed);
    for (int i = 0; i < SAMP_MAX_PLAYERS; i++)
    {
        if (SF->getSAMP()->getPlayers()->iIsListed[i] != 1 || SF->getSAMP()->getPlayers()->pRemotePlayer[i] == NULL || SF->getSAMP()->getPlayers()->pRemotePlayer[i]->pPlayerData == NULL  || SF->getSAMP()->getPlayers()->pRemotePlayer[i]->pPlayerData->pSAMP_Actor == NULL || SF->getSAMP()->getPlayers()->pRemotePlayer[i]->pPlayerData->pSAMP_Actor->pGTA_Ped == NULL) continue;
        actor_info *ActorInfo = SF->getSAMP()->getPlayers()->pRemotePlayer[i]->pPlayerData->pSAMP_Actor->pGTA_Ped;
        vect3_copy(ActorInfo->base.matrix + 12, posPed);
        SF->getGame()->convert3DCoordsToScreen(posPed.x, posPed.y, posPed.z, &screenPos.x, &screenPos.y);
        static float iX = GetSystemMetrics(SM_CXSCREEN) * 0.5299999714f;
        static float iY = GetSystemMetrics(SM_CYSCREEN) * 0.4f;
        if (((abs(iX - screenPos.x)) > radius) || ((abs(iY - screenPos.y)) > radius))
            continue;
        currentRadius = GetDistance(myPosPed, posPed);
        if (currentRadius < maxRadius) nearestPED = i, maxRadius = currentRadius;
    }
    return nearestPED;
}

Пример:
C++:
int id = GetNearestPed(100);
if (id < 0) continue;
 

astap_

Известный
Всефорумный модератор
626
597
поворачивает камеру на координаты
C++:
float* xCam = (float*)0xB6F258;
DWORD* ptrActor = (DWORD*)0xB6F5F0;
// global vars

void rotateCamToXY(float x, float y) {

    DWORD* pActorMtrx = (DWORD*)((*ptrActor) + 0x14);

    CVector2D pPos(*(float*)((*pActorMtrx) + 0x30), *(float*)((*pActorMtrx) + 0x34));
    CVector2D cPos(*(float*)(0xB6F9CC), *(float*)(0xB6F9D0));

    float ac = sqrt(pow(fabs(cPos.fX - x), 2) + pow(fabs(cPos.fY - y), 2));
    float alpha = asin(fabs(cPos.fX - x) / ac);
    float beta = acos(fabs(cPos.fX - x) / ac);

    if ((pPos.fX > x) && (pPos.fY < y))
        *xCam = -beta;
    if ((pPos.fX > x) && (pPos.fY > y))
        *xCam = beta;
    if ((pPos.fX < x) && (pPos.fY > y))
        *xCam = (alpha + (1.57));
    if ((pPos.fX < x) && (pPos.fY < y))
        *xCam = (-alpha - (1.57));
}
 

Cake_

Известный
Проверенный
263
313
поворачивает камеру на координаты
C++:
float* xCam = (float*)0xB6F258;
DWORD* ptrActor = (DWORD*)0xB6F5F0;
// global vars

void rotateCamToXY(float x, float y) {

    DWORD* pActorMtrx = (DWORD*)((*ptrActor) + 0x14);

    CVector2D pPos(*(float*)((*pActorMtrx) + 0x30), *(float*)((*pActorMtrx) + 0x34));
    CVector2D cPos(*(float*)(0xB6F9CC), *(float*)(0xB6F9D0));

    float ac = sqrt(pow(fabs(cPos.fX - x), 2) + pow(fabs(cPos.fY - y), 2));
    float alpha = asin(fabs(cPos.fX - x) / ac);
    float beta = acos(fabs(cPos.fX - x) / ac);

    if ((pPos.fX > x) && (pPos.fY < y))
        *xCam = -beta;
    if ((pPos.fX > x) && (pPos.fY > y))
        *xCam = beta;
    if ((pPos.fX < x) && (pPos.fY > y))
        *xCam = (alpha + (1.57));
    if ((pPos.fX < x) && (pPos.fY < y))
        *xCam = (-alpha - (1.57));
}
C++:
void cameraset(float X, float Y) {

  CVector mypos;
  CVector enpos;
  CVector vector;
  enpos.fX = X;
  enpos.fY = Y;
 
  CCamera* pCamera = GAME->GetCamera();
  mypos = *pCamera->GetCam(pCamera->GetActiveCam())->GetSource();
  vector = mypos - enpos;
  float AngleX = atan2f(vector.fY, -vector.fX) - M_PI / 2;

  *(float*)0xB6F258 = -(AngleX - M_PI / 2);
}
 

Carrentine

Потрачен
569
460
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Описание: находит ближайшую кость противника к прицелу.
Код:
C++:
CVector GetBonePos(INT ID, eBone eBone, BOOL isOnScreen)
{
    if (SF->getSAMP()->getPlayers()->iIsListed[ID] != 1 || SF->getSAMP()->getPlayers()->pRemotePlayer[ID] == NULL || SF->getSAMP()->getPlayers()->pRemotePlayer[ID]->pPlayerData == NULL || SF->getSAMP()->getPlayers()->pRemotePlayer[ID]->pPlayerData->pSAMP_Actor == NULL || SF->getSAMP()->getPlayers()->pRemotePlayer[ID]->pPlayerData->pSAMP_Actor->pGTA_Ped == NULL) return CVector(0.0F, 0.0F, 0.0F);
    if (isOnScreen)
    {
        CVector BonePosition;
        CVector2D BonePositionOnScreen;
        GAME->GetPools()->GetPed((DWORD*)SF->getSAMP()->getPlayers()->pRemotePlayer[ID]->pPlayerData->pSAMP_Actor->pGTA_Ped)->GetTransformedBonePosition(eBone, &BonePosition);
        SF->getGame()->convert3DCoordsToScreen(BonePosition.fX, BonePosition.fY, BonePosition.fZ, &BonePositionOnScreen.fX, &BonePositionOnScreen.fY);
        return CVector(BonePositionOnScreen.fX, BonePositionOnScreen.fY, 0.0F);
    }
    else
    {
        CVector BonePosition;
        GAME->GetPools()->GetPed((DWORD*)SF->getSAMP()->getPlayers()->pRemotePlayer[ID]->pPlayerData->pSAMP_Actor->pGTA_Ped)->GetTransformedBonePosition(eBone, &BonePosition);
        return CVector(BonePosition.fX, BonePosition.fY, BonePosition.fZ);
    }
}

eBone GetNearestBone(int iID)
{
    eBone
        currentBone[] = {BONE_RIGHTKNEE, BONE_LEFTKNEE, BONE_RIGHTELBOW, BONE_LEFTELBOW, BONE_SPINE1, BONE_RIGHTSHOULDER, BONE_LEFTSHOULDER, BONE_HEAD},
        nearestBone;
    float
        currentRadius,
        maxRadius = 20000;
    CVector posBone;
    for (int i = 0; i < 8; i++)
    {
        posBone = GetBonePos(iID, currentBone[i], TRUE);
        static float iX = GetSystemMetrics(SM_CXSCREEN) * 0.5299999714f;
        static float iY = GetSystemMetrics(SM_CYSCREEN) * 0.4f;
        currentRadius = sqrt((pow((posBone.fX - iX), 2) + pow((posBone.fY - iY), 2)));
        if (currentRadius < maxRadius)
            nearestBone = currentBone[i],
            maxRadius = currentRadius;
    }
    return nearestBone;
}
Пример:
C++:
eBone nearestBone = GetNearestBone(playerID);
 
Последнее редактирование:
  • Нравится
Реакции: BASS_DEVSOFTWARE

BlackKnigga

Известный
BH Team
922
444
Разработчики, только перешедшие с клео\луа на C++ негодуют из-за необходимости использовать разного рода таймеры и лапшу из GetTickCount'ов вместо полюбившихся функций wait. Но особо ярых фанатов клео это не устраивает, отчего они начинают использовать потоки ради функций вроде Sleep для того чтобы не блокировать цикл игры. Однако это не безопасно. Функции ни GTA ни SAMP'а абсолютно не предназначены для использования в разных потоках и их использование может привести к рандомным крашам.

Выход есть!

Example:
#include <string>
#include <chrono>

#include "Yet-another-hook-library/hook.h"
#include "sampapi/CChat.h"

#include "coro_wait/coro_wait.h"

using namespace sampapi::v037r1;

void foo() {
    using namespace std::chrono_literals;
    CChat *&pChat = RefChat();

    while (!pChat) {
        this_coro::wait(100ms);
    }

    unsigned int counter = 0;
    while (true) {
        pChat->AddMessage(-1, (std::string("Hello ") + std::to_string(counter)).c_str());
        counter++;

        this_coro::wait(1s);
    }
}

void CGame_Process_hk() {
    static coro_wait instance{ foo };

    instance.process();
}

class coro_wait_example {
public:
    coro_wait_example() {
        using CGame_Process_t = void(__cdecl*)();
        CGame_Process_t CGame_Process = reinterpret_cast<CGame_Process_t>(0x53BEE0);

        static hook CGame_Process_hook(CGame_Process, CGame_Process_hk);
    }
} coro_wait_example;

Выполнение функции foo приостанавливается на время, переданное функции this_coro::wait, и продолжается с того же места. Все это работает в одном потоке, благодаря чему можно не переживать за потокобезопасность вызываемых внутри функций.
В бесконечных или очень больших циклах требуется вызывать wait(0), все по канонам клео.
Функция coro_wait::process должна вызываться в потоке игры (перехваченном как в примере, либо в функции mainloop для SF API).

Требуется библиотека Boost.Context!

Исходный код:


хуки
sampapi
 
Последнее редактирование:

Pakulichev

Software Developer & System Administrator
Друг
1,789
2,131
Простенькая функция, которая позволяет рисовать поле для ввода в ImGUI с текстовой подсказкой на нём. Подсказка пропадает, если пользователь выделяет поле для ввода нажатием на него, либо вводит какую-либо информацию. Может быть проблема с Y-смещением, рекомендуется использовать стандартный стиль ImGUI.
C++:
static bool InputTextWithPH(const char *placeholder, const char *text, char *buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = (ImGuiInputTextCallback)0, void *user_data = (void*)0)
{
    ImVec2 cursor[2];
    cursor[0] = ImGui::GetCursorPos();
    bool result = ImGui::InputText(text, buf, buf_size, flags, callback, user_data);
    if (placeholder != NULL && strlen(placeholder) > 0) {
        if (!ImGui::IsItemActive() && strlen(buf) == 0) {
            cursor[1] = ImGui::GetCursorPos();
            ImGui::SetCursorPos(ImVec2(cursor[0].x + 5, cursor[0].y + 2));
            ImGui::Text(placeholder);
            ImGui::SetCursorPos(cursor[1]);
        }
    }
    return result;
}

// Пример использования
InputTextWithPH(u8"Любой текст", "##t1", testText, sizeof testText);
В новых версиях ImGUI есть стандартная функция InputTextWithHint, использовать лучше её!
 
  • Нравится
Реакции: _raz0r

loganhackerdff

Известный
868
517
Получает название клавиши по id
C++:
GetKeyNameTextA((MapVirtualKeyA(KEYID, MAPVK_VK_TO_VSC) << 16), KEYNAMEBUFFER, 64);