# Re:dive — Lua API

Runtime: **LuaJIT 2.1** (incluye `ffi`, `bit`, `jit` nativos). Los scripts viven en `%APPDATA%\Microsoft\luas`.

Un script típico registra callbacks y dibuja/actúa dentro de ellos:

```lua
callbacks.Register("Draw", function()
    draw.Color(255, 0, 0, 255)
    draw.Text(10, 10, "hola")
end)
```

---

## callbacks

Registro de funciones que el cheat llama por evento.

| Función | Descripción |
|---|---|
| `callbacks.Register(name, fn)` | Registra `fn` para el callback `name`. |
| `callbacks.Unregister(name, fn)` | Quita el registro. |
| `callbacks.RegisterEvent(event, fn)` | Registra para un game-event de L4D2 (ver lista abajo). |

**Callbacks del core:** `Draw`, `DrawMenu`, `CreateMove`, `CreateMoveRaw`, `ClcMove`, `MovePost`, `FrameStageNotify`, `LevelInit`, `LevelShutdown`, `DispatchUserMessage`, `SendStringCmd`, `FireGameEvent`, `Unload`.

**Game-events (con `FireGameEvent` o `RegisterEvent`):** `player_death`, `player_hurt`, `player_spawn`, `player_say`, `player_team`, `player_connect`, `player_disconnect`, `player_use`, `player_jump`, `player_incapacitated`, `player_ledge_grab`, `round_start`, `round_end`, `round_freeze_end`, `mission_lost`, `finale_start`, `weapon_fire`, `weapon_reload`, `ammo_pickup`, `item_pickup`, `witch_spawn`, `tank_spawn`, `revive_begin`, `revive_success`, `heal_begin`, `heal_success`, `pills_used`, `defibrillator_used`, `adrenaline_used`, `survivor_rescued`, `vote_started`, `vote_cast_yes`, `vote_cast_no`.

---

## Vector / Angle (tipos)

Constructores globales: `Vector(x, y, z)` · `Angle(p, y, r)`. Campos: `.x .y .z` / `.p .y .r`. Operadores: `+  -  *  ==  -` (unario), `tostring`.

**Vector** — `Length()`, `Length2D()`, `LengthSqr()`, `Distance(v)` / `Dist(v)`, `Dist2D(v)`, `Dot(v)`, `Cross(v)`, `Normalize()`, `Normalized()`, `ToAngles()`, `Clone()`, `Unpack()` → x,y,z, `Set(x,y,z)`.

**Angle** — `Forward()`, `Right()`, `Up()` (→ Vector), `Normalize()`, `Clone()`, `Unpack()` → p,y,r.

---

## entities

Acceso a entidades del juego (devuelven objetos `Entity`).

| Función | Descripción |
|---|---|
| `entities.GetLocalPlayer()` | Tu jugador. |
| `entities.GetByIndex(i)` | Entidad por índice. |
| `entities.GetPlayers()` | Tabla de jugadores. |
| `entities.FindByClass(name)` | Tabla de entidades por classname. |
| `entities.GetHighestEntityIndex()` | Índice más alto en uso. |

### Entity (métodos)

**Identidad/estado:** `GetIndex()`, `GetAddress()`, `IsValid()`, `IsDormant()`, `GetClassId()`, `GetClassName()`, `GetName()`.
**Posición:** `GetAbsOrigin()`, `SetOrigin(v)`, `GetEyePosition()`, `GetEyeAngles()`, `GetBonePosition(i)`, `GetVelocity()`, `SetVelocity(v)`, `EstimateAbsVelocity()`.
**Vida/equipo:** `GetHealth()`, `GetMaxHealth()`, `GetTeamNumber()`, `IsAlive()`.
**Movimiento:** `IsOnGround()`, `GetMoveType()`, `SetMoveType(n)`.
**L4D2:** `GetZombieClass()`, `GetSurvivorCharacter()`, `IsGhost()`, `IsIncapacitated()`, `IsHangingFromLedge()`, `IsPinned()`.
**Hitbox:** `GetHitboxCount()`, `GetHitboxPosition(i)`.
**Arma:** `GetActiveWeapon()`, `GetClip()`, `GetClip2()`, `GetAmmoType()`, `IsMeleeWeapon()`.
**Netvars (prop):** `HasProp(name)`, `GetPropInt/Float/Bool/Vector/String/Entity(name)`, `SetPropInt/Float/Bool/Vector(name, val)`.

---

## engine

| Función | Descripción |
|---|---|
| `engine.GetViewAngles()` / `SetViewAngles(a)` | Ángulos de vista. |
| `engine.GetLastFireAngles()` | Hacia dónde salió la última bala (post-aimbot). |
| `engine.IsInGame()` / `IsConnected()` / `ConIsVisible()` | Estado. |
| `engine.GetScreenSize()` → w,h | Resolución. |
| `engine.GetMaxClients()` / `GetLocalPlayerIndex()` / `GetMapName()` | Info. |
| `engine.ExecuteClientCmd(s)` / `ClientCmd(s)` | Comando de consola. |
| `engine.GetPlayerInfo(i)` | Info de jugador. |
| `engine.GetNetChannel()` | Puntero al netchannel. |

## client

Atajos estilo LMAOBOX: `client.ChatPrintf(s)`, `client.Command(s)`, `client.GetPlayerInfo(i)`, `client.GetLocalPlayerIndex()`, `client.GetMapName()`.

## globals

`globals.TickCount()`, `globals.CurTime()`, `globals.FrameTime()`, `globals.RealTime()`.

## input

`input.IsBindDown(key)`, `input.IsButtonDown(vk)`, `input.IsButtonPressed(vk)`, `input.IsKeyToggled(vk)`, `input.GetMousePos()` → x,y.

---

## trace

| Función | Descripción |
|---|---|
| `trace.Line(from, to [, skip])` | Rayo. Devuelve tabla con resultado (fraction, hit, endpos, entity…). |
| `trace.Hull(from, to, min, max [, skip])` | Trace con caja. |

## playerresource

Datos por índice sin iterar entidades: `playerresource.Exists(i)`, `GetPing(i)`, `GetHealth(i)`, `GetScore(i)`, `GetDeaths(i)`, `GetTeam(i)`, `IsAlive(i)`, `IsConnected(i)`.

## playerlist

El aimbot/ESP nativos respetan estos ajustes por jugador:
`playerlist.SetPriority(i, n)` / `GetPriority(i)`, `SetIgnored(i, bool)` / `GetIgnored(i)`, `SetColor(i, r,g,b,a)` / `GetColor(i)` / `ClearColor(i)`, `Reset()`.

## chams

Fuerza chams sobre entidades (reusa el sistema nativo):
`chams.SetEntity(ent, style, wallhack, r,g,b,a)`, `chams.SetOccludedColor(ent, r,g,b,a)`, `chams.ClearEntity(ent)`, `chams.Reset()`.

---

## draw — 2D (usar en el callback `Draw`)

| Función | Descripción |
|---|---|
| `draw.Color(r,g,b,a)` | Color actual. |
| `draw.Text(x,y,s)` | Texto. |
| `draw.Line(x1,y1,x2,y2)` | Línea. |
| `draw.FilledRect(x,y,w,h)` / `OutlinedRect(x,y,w,h)` | Rectángulos. |
| `draw.RoundedRect(x,y,w,h,rad)` | Rect redondeado. |
| `draw.Circle(x,y,r,seg)` / `FilledCircle(...)` | Círculos. |
| `draw.Triangle(x1,y1,x2,y2,x3,y3)` | Triángulo. |
| `draw.Arc(x,y,r,start,end,seg)` | Arco. |
| `draw.Gradient(x,y,w,h,c1,c2,horizontal)` | Degradado. |
| `draw.GetScreenSize()` → w,h | Pantalla. |
| `draw.GetTextSize(s)` → w,h | Medir texto. |
| `draw.WorldToScreen(v)` → x,y,visible | Mundo→pantalla. |
| `draw.CreateFont(name,size,weight,flags)` → id | Fuente (ver `FONTFLAG`). |
| `draw.SetFont(id)` | Fuente activa. |
| `draw.CreateTexture(path)` / `CreateTextureRGBA(data,w,h)` → id | Texturas. |
| `draw.Texture(id,x,y,w,h)` | Dibuja textura. |
| `draw.Shadow(...)` / `draw.Glow(...)` | Efectos de texto/caja. |

## render — 3D en espacio-mundo (usa `draw.Color`)

`render.Line3D(v1,v2)`, `render.Box3D(min,max)`, `render.Circle3D(center,r,seg)`, `render.Text3D(pos,s)`.

## material — tintar cielo/agua/mundo (materiales ya cargados)

| Función | Descripción |
|---|---|
| `material.List("skybox")` | Lista `{ {name=,group=}, ... }`. |
| `material.ColorModulate(name, r,g,b [,a])` | Tinte (0..1). |
| `material.SetVar(name, "$var", n1 [,n2,n3,n4])` / `GetVar(name,"$var")` | Variables del material. |
| `material.Sky(r,g,b [,a])` | Tiñe el cielo (0..1). |
| `material.Restore()` | Deshace todo lo tocado. |

## sound

`sound.Play(path)`.

---

## ui — controles del script en el menú del cheat

`ui.SetPage(name)` (Aim/Visuals/World/Exploits/Misc/Lua), `ui.Section(name)`, `ui.Checkbox(label, default)`, `ui.Keybind(label)`, `ui.Slider(label, min, max, default)`, `ui.Button(label, fn)`.

## imgui — ventana propia del script (usar en `DrawMenu`)

Wrapper de Dear ImGui. **Layout:** `Begin/End`, `BeginChild/EndChild`, `BeginGroup/EndGroup`, `Separator`, `SameLine`, `Spacing`, `NewLine`, `Dummy`, `Indent/Unindent`, `SetNextWindowSize/Pos`, `GetWindowSize/Pos`, `GetContentRegionAvail`, `PushItemWidth/PopItemWidth`, `SetCursorPos/GetCursorPos/GetCursorScreenPos`.
**Texto:** `Text`, `TextColored`, `TextDisabled`, `TextWrapped`, `BulletText`.
**Controles:** `Button`, `SmallButton`, `Checkbox`, `RadioButton`, `SliderFloat`, `SliderInt`, `DragFloat`, `DragInt`, `InputText`, `InputFloat`, `InputInt`, `Selectable`, `ColorEdit4`, `ProgressBar`, `CollapsingHeader`, `TreeNode/TreePop`, `Combo`.
**Estado/input:** `IsItemHovered/Clicked/Active`, `IsMouseClicked/Down/DoubleClicked`, `GetMousePos`, `GetMouseWheel`, `SetTooltip`, `BeginTooltip/EndTooltip`, `CalcTextSize`.
**Draw list:** `DrawLine`, `DrawRect`, `DrawRectFilled`, `DrawCircle`, `DrawCircleFilled`, `DrawTriangleFilled`, `DrawText`, `Image`.

## overlay — ventanas HUD siempre visibles (fuera del menú)

`overlay.add(id, drawFn, w, h, x, y, flags)`, `overlay.remove(id)`, `overlay.set_visible(id, bool)`, `overlay.set_input(id, bool)` (recibe clicks), `overlay.style(id, { title_bg=, bg=, ... })`, `overlay.screen_size()` → w,h.

---

## web — navegador embebido (WebView2)

`web.Show(bool)`, `web.Navigate(url)`, `web.SetBounds(x,y,w,h)`, `web.SetLocked(bool)` (click-through), `web.Reload()`, `web.GoBack()`, `web.GoForward()`, `web.IsReady()`, `web.IsVisible()`.

## capture — captura de una ventana a textura

`capture.Start("parte del titulo")` → bool, `capture.Stop()`, `capture.IsRunning()`, `capture.Error()`, `capture.SetFps(1..60)`, `capture.Size()` → w,h, `capture.Draw(w [,h])` → bool.
**Input al area capturada:** `capture.MouseMove(nx,ny)`, `MouseButton(nx,ny,btn,down)`, `Wheel(nx,ny,delta)`, `Key(vk,down)`, `Char(code)` (coords `0..1`).

## nowplaying — música (SMTC: Spotify/YouTube/…)

`nowplaying.Start()`, `Stop()`, `IsRunning()`, `Info()` → `{title,artist,app,playing,hasSession}`, `Cover()` → texId,w,h (para `draw.Texture`), `CoverImgui()` → handle,w,h (para `imgui.Image`), `Sources()`, `SetSource(exe)` / `GetSource()`, `Play()`, `Pause()`, `Toggle()`, `Next()`, `Prev()`.

---

## exploits

`exploits.set_extra_commands(n)` (re-predicción / rapid fire), `exploits.set_send_packet(bool)` (-1 = sin tocar), `exploits.set_choke(n)` (choke persistente por comando).

## cheat / ref — toggles y valores del cheat por nombre

(`cheat` es alias de `ref`.) `cheat.Get(key)`, `cheat.Set(key, val)`, `cheat.Type(key)`, `cheat.List()`, `cheat.Exists(key)`, `cheat.Toggle(key)`.

## cvar — ConVars del juego

`cvar.Find(name)` → objeto `ConVar`. Directos: `cvar.GetFloat/GetInt/GetBool/GetString(name)`, `cvar.SetFloat/SetInt/SetBool/SetString(name, val)`.
**ConVar (objeto):** `GetFloat/GetInt/GetBool/GetString/GetName()`, `SetFloat/SetInt/SetBool/SetString(val)`.

## hooks — enganchar funciones del juego

`hooks.Detour(module, signature, fn)`, `hooks.VTable(interface, index, fn)`, `hooks.Remove(h)`, `hooks.RemoveAll()`, `hooks.List()`.

## memory — lectura/escritura cruda

`memory.get_module_base(name)`, `find_signature(module, sig)`, `follow(addr, ...offs)`, `get_interface(module, version)`, `protect(addr,size,flags)`, `alloc(size)`, `free(addr)`.
**Leer:** `read_int/uint/float/double/byte/short/ptr/vector/string/bytes(addr [,len])`.
**Escribir:** `write_int/uint/float/double/byte/short/vector/string/bytes(addr, val)`.

---

## fs / json / http

`fs.Read(path)`, `fs.Write(path, data)`, `fs.Exists(path)`, `fs.Delete(path)`, `fs.List(path)`.
`json.encode(tbl)` → string, `json.decode(string)` → tbl.
`http.Get(url)` → body, `http.Post(url, body)` → body.

---

## UserCmd (arg de `CreateMove`)

Getters/setters: `GetViewAngles/SetViewAngles`, `GetButtons/SetButtons`, `GetForwardMove/SetForwardMove`, `GetSideMove/SetSideMove`, `GetUpMove/SetUpMove`, `GetTickCount/SetTickCount`, `GetCommandNumber/SetCommandNumber`, `GetImpulse/SetImpulse`, `GetRandomSeed/SetRandomSeed`, `GetWeaponSelect/SetWeaponSelect`, `GetMouseDX/SetMouseDX`, `GetMouseDY/SetMouseDY`.
Campos directos también: `cmd.forwardmove = 400`, `cmd.buttons`, etc.

## GameEvent (arg de `FireGameEvent`)

`GetName()`, `GetInt(key)`, `GetFloat(key)`, `GetBool(key)`, `GetString(key)`.

---

## Constantes (enums globales)

| Tabla | Valores |
|---|---|
| `IN` | `ATTACK, JUMP, DUCK, FORWARD, BACK, USE, ATTACK2, RELOAD, SPEED, WALK, ZOOM, RUN, MOVELEFT, MOVERIGHT, …` (también `IN.IN_JUMP`). |
| `keys` | `A..Z`, `0..9`, `F1..F12`, `SPACE, ENTER, ESCAPE, TAB, SHIFT, CTRL, ALT, ARROWS, INSERT, DELETE, HOME, END, PAGEUP, PAGEDOWN`, `MOUSE1..MOUSE5`. |
| `TEAM` | `SPECTATOR=1, SURVIVORS=2, INFECTED=3`. |
| `ZOMBIE` | `SMOKER=1, BOOMER=2, HUNTER=3, SPITTER=4, JOCKEY=5, CHARGER=6, WITCH=7, TANK=8`. |
| `HITGROUP` | `GENERIC=0, HEAD=1, CHEST=2, STOMACH=3, LEFTARM=4, RIGHTARM=5, LEFTLEG=6, RIGHTLEG=7, GEAR=10`. |
| `FONTFLAG` | `NONE, ITALIC, UNDERLINE, OUTLINE, DROPSHADOW, ANTIALIAS, GAUSSIANBLUR, ADDITIVE, BITMAP, …` |

---

## LuaJIT nativo

`ffi` (FFI completo: `ffi.cdef`, `ffi.cast`, `ffi.new`, …), `bit` (operaciones bit a bit), `jit`. Más la stdlib de Lua 5.1 (`string`, `table`, `math`, `os`, `io`, …).

## Otros globales

`print(...)` → consola del menú.
