Interface GameAPI
- All Superinterfaces:
ActionAPI, DrawAPI, NavigationAPI, SystemAPI, VariableAPI
GameSnapshot (obtained via
Client.snapshot()); only mutations, the two state probes that
the producer always handles, and the cache-type lookups (slice 5
stubs) live here.
Domain split:
SystemAPI— pipe ping / introspectionActionAPI— action queue + behavior modifiersNavigationAPI— walker, pathfinder queries, region cacheVariableAPI— on-demand varp / varbit / varc readsDrawAPI— debug drawing over the client (api.draw())
Per-tick reads of game state (local player, NPCs, players, inventories)
go through Client.snapshot(); transient changes (varp/varbit deltas,
chat) arrive as events on the EventBus.
On-demand variable reads (current value of an arbitrary varp/varbit/varc)
live on VariableAPI below.
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intSub-component id meaning "the component itself" in a component trigger.static final intValue the gameval-named variable reads return when the name does not resolve — the same "no value" sentinelVariableAPI.getVarp(int)yields for a varp that does not exist or could not be read. -
Method Summary
Modifier and TypeMethodDescriptionbackpack()Backpack facade.bank()Bank facade.voidchangeLoginState(int oldState, int newState) Requests a login state transition.Interface-component query facade — the high-level, fluent entry point for inspecting interface components (parallel tonpcs()/mapElements()).voiddestroyScriptHandle(long handle) Releases a script handle.Worn equipment facade.executeScript(long handle, int[] intArgs, String[] stringArgs, String[] returns) Executes a previously-obtained client script handle.findComponentAt(int screenX, int screenY) Locate the deepest visible component under a screen-space coordinate, ornullwhen nothing is there.voidfireComponentTrigger(int interfaceId, int componentId, int subId, int triggerType, int arg) Fires a component's CS2 event trigger (click / key / ...) by event type, reproducing the engine's own component-event path.default intFires a component's key (type-10) CS2 trigger once per stroke, in order, as a single batched action-queue request (one RPC round-trip).default voidfireKeyTrigger(int interfaceId, int componentId, String input) Typesinputinto a component through its key (type-10) CS2 trigger, oneKeyStroke.character(char)per character, batched as byfireKeys(int, int, List).default GamevalIndexgamevals()Resolves gameval symbolic names — the game's own stable names for items, scenery, NPCs, interfaces, components and variables — to ids.booleanReturns whether the producer's auto-login state machine is enabled.getComponent(int interfaceId, int componentId) Returns the component at(interfaceId, componentId)ornullwhen no such component is loaded.getComponents(List<ComponentRef> refs) Batch counterpart ofgetComponent(int, int).getDynamicChildren(int interfaceId, int componentId) Returns the dynamic (script-spawned) child component ids of(interfaceId, componentId).getEnumType(int id) intReturns the producer's monotonically increasing game cycle counter.getInterfaceTree(int interfaceId, int componentId) Returns the component at(interfaceId, componentId)and its entire descendant subtree, flattened breadth-first, in a single pipe round-trip.getItemType(int id) The local player, withLocalPlayer.currentHealth()andLocalPlayer.maxHealth()filled in.getLocationType(int id) Returns the producer's current login state.getNpcType(int id) getObjVars(int invId) Per-item obj vars for every filled slot of a container — the per-instance variables an item carries in its slot'sObjVarDomain(augmentation XP, charges, etc.), distinct from the global player/client var domains.getObjVars(int invId, int slot) Per-item obj vars for a single container slot.getPlayerStat(int skillId) Returns one of the local player's skill stats by skill type id.getQuestType(int id) longgetScriptHandle(int scriptId) Obtains a producer-side handle to a client script for repeated execution.getSequenceType(int id) getStaticChildren(int interfaceId, int componentId) Returns the static (cache-defined) child component ids of(interfaceId, componentId).getStructType(int id) default intValue of a variable bit named by its gameval, e.g.default intgetVarcInt(String gameval) Value of an integer client variable named by its gameval.default intValue of a player variable named by its gameval, e.g.default longgetVarpLong(String gameval) Full 64-bit value of a player variable named by its gameval.default WorldMapElementgetWorldMapElement(int id) Single world-map element byid, ornullwhen not found.Ground-item query facade.The game's text/amount input dialog (withdraw-X, add-friend, ...).voidInterrupts any currently active break.default booleanisInterfaceOpen(int ifaceId) Convenience shim — delegates tosnapshot().isInterfaceOpen(ifaceId).voidTriggers a login from the login screen to the lobby.World-map element query facade.npcs()NPC query facade.objects()Scene-object query facade.players()Player query facade.In-flight projectile query facade (v17+).queryWorldMapElements(Map<String, Object> filter) Low-level RPC: ask the producer for cache-resident world map elements matchingfilter.voidscheduleBreak(int durationMs) Schedules a break (action-queue gate) for the given duration.voidsetAutoLogin(boolean enabled) Enables or disables the producer's auto-login state machine.voidsetWorld(int worldId) Initiates a world hop to the given world id.snapshot()Returns a tick-scoped read view over the producer's published snapshot, ornullif no shared-memory region is bound (e.g.default voidwalkWorldPath(int x, int y) No-plane convenience forNavigationAPI.walkWorldPathAsync(int, int, int)— uses the local player's current plane, falling back to plane 0 when not in-game.Methods inherited from interface ActionAPI
areActionsBlocked, clearActionQueue, getActionHistory, getActionQueueSize, getLastActionTime, queueAction, queueActions, setActionsBlockedMethods inherited from interface DrawAPI
draw, drawClear, drawClearAll, drawHighlight, drawHighlights, drawList, drawSet, drawSetBatch, drawStats, isDrawEnabled, setDrawEnabledMethods inherited from interface NavigationAPI
clearRegionCache, findPath, findPath, findWorldPath, findWorldPath, getRegionCacheSize, getWalkStatus, isReachable, isReachable, walkCancel, walkRefusalCount, walkToAsync, walkWorldPath, walkWorldPathAsync, walkWorldPathAsync, walkWorldPathAsyncMethods inherited from interface SystemAPI
getClientCount, listMethods, pingMethods inherited from interface VariableAPI
getVarbit, getVarcInt, getVarcInts, getVarcString, getVarcStrings, getVarp, getVarpLong, getVarps, queryVarbits, readVarbit, readVarbits, readVarp, readVarps, varpState
-
Field Details
-
UNRESOLVED_VARIABLE
static final int UNRESOLVED_VARIABLEValue the gameval-named variable reads return when the name does not resolve — the same "no value" sentinelVariableAPI.getVarp(int)yields for a varp that does not exist or could not be read.It is not the value of an unset varp. An unset varp reads its type default, which is usually
0and, for object-typed varps, is itself-1; a set varp can hold-1too. So-1never means "unset" on its own: askVariableAPI.readVarp(int)orVariableAPI.varpState(int).- See Also:
-
TOP_LEVEL_COMPONENT
static final int TOP_LEVEL_COMPONENTSub-component id meaning "the component itself" in a component trigger.- See Also:
-
-
Method Details
-
snapshot
GameSnapshot snapshot()Returns a tick-scoped read view over the producer's published snapshot, ornullif no shared-memory region is bound (e.g. tests using the legacy 1-/2-argGameAPIImplconstructor). Same instance shape asClient.snapshot(); surfaced here so the entity query facades (npcs(),players()) and skill helpers (getLocalPlayer(),getPlayerStat(int)) can read snapshot fields without forcing scripts to threadClientthrough every helper.The returned view is bounded to the current tick — don't cache it. Each call resolves the published front buffer.
-
isInterfaceOpen
default boolean isInterfaceOpen(int ifaceId) Convenience shim — delegates tosnapshot().isInterfaceOpen(ifaceId). Kept so call sites that pre-date the rewrite (api.isInterfaceOpen(...)) keep compiling. New code should go throughGameSnapshotdirectly. -
gamevals
Resolves gameval symbolic names — the game's own stable names for items, scenery, NPCs, interfaces, components and variables — to ids. Nevernull: when no index is deployed this returnsGamevalIndex.empty(), whose lookups all come back empty.Backed by an out-of-band
gameval.sqlitein~/.botwithus/native/, so a game renumber is fixed by refreshing that file rather than by editing scripts. The same instance is shared by every connected client.int yew = api.gamevals().require(GamevalType.ITEM, "YEW_LOGS"); -
getVarp
Value of a player variable named by its gameval, e.g."WOODCUTTING_WOODBOX_LASTUSED_TIER". Convenience overVariableAPI.getVarp(int).Returns
UNRESOLVED_VARIABLEwhen the name does not resolve — the same valueVariableAPI.getVarp(int)yields for a varp that does not exist or could not be read — so a host with no gameval index deployed degrades rather than killing the script. An unset varp is different: it reads its type default. Usegamevals().require(...)explicitly when you would rather fail fast. -
getVarpLong
Full 64-bit value of a player variable named by its gameval. Convenience overVariableAPI.getVarpLong(int);UNRESOLVED_VARIABLEwhen the name does not resolve. -
getVarbit
Value of a variable bit named by its gameval, e.g."ZAROS_SPELLBOOK". Convenience overVariableAPI.getVarbit(int);UNRESOLVED_VARIABLEwhen the name does not resolve. -
getVarcInt
Value of an integer client variable named by its gameval. Convenience overVariableAPI.getVarcInt(int);UNRESOLVED_VARIABLEwhen the name does not resolve. -
npcs
-
players
-
backpack
-
bank
-
equipment
-
getObjVars
Per-item obj vars for every filled slot of a container — the per-instance variables an item carries in its slot'sObjVarDomain(augmentation XP, charges, etc.), distinct from the global player/client var domains. Read on demand over the RPC pipe (the obj-var hashmaps are walked on the game thread). Returnsslot -> (varId -> value); an empty map when nothing in the container carries obj vars.- Parameters:
invId- container id (e.g. 93 = backpack, 94 = equipment)
-
getObjVars
-
objects
SceneObjects objects()Scene-object query facade. Singleton perGameAPI. -
groundItems
GroundItems groundItems()Ground-item query facade. Singleton perGameAPI. -
projectiles
Projectiles projectiles()In-flight projectile query facade (v17+). Singleton perGameAPI.Read-only: projectiles carry no menu actions and no cache definition, so the entities this yields have no
interact()and noname(). SeeProjectile. -
mapElements
WorldMapElements mapElements()World-map element query facade. Singleton perGameAPI. -
queryWorldMapElements
Low-level RPC: ask the producer for cache-resident world map elements matchingfilter. The map shape is the same oneWorldMapElements.Queryaccumulates. Most scripts go throughmapElements()instead. Stub-empty until producer iteration lands. -
getWorldMapElement
Single world-map element byid, ornullwhen not found. Default implementation scans theunfiltered queryresult client-side, so it inherits the producer-side stub-empty behaviour — once cache iteration lands, this returns real data without a code change.Convenience for callers that already know the id (e.g. resolving a named-location catalog entry). For map searches with filters use
mapElements(). -
getLocalPlayer
LocalPlayer getLocalPlayer()The local player, withLocalPlayer.currentHealth()andLocalPlayer.maxHealth()filled in. Returnsnullwhen not in-game (matches snapshot semantics).Otherwise the same record
snapshot().self()returns — but health is not in the mapping, so filling it costs one batched varp read over the pipe. That read is cached per server tick, so calling this in a loop costs at most one round-trip per 600ms tick; both values degrade toLocalPlayer.HEALTH_UNKNOWNif the read doesn't land. Callers that only want position, skills or animation should prefersnapshot().self(), which never touches the pipe. -
walkWorldPath
default void walkWorldPath(int x, int y) No-plane convenience forNavigationAPI.walkWorldPathAsync(int, int, int)— uses the local player's current plane, falling back to plane 0 when not in-game. Lives here (not onNavigationAPI) because it needssnapshot().Reads the plane off the snapshot rather than
getLocalPlayer(): only the plane is wanted, and the health read that accessor pays for would be a round-trip spent on nothing. -
getPlayerStat
Returns one of the local player's skill stats by skill type id.nullwhen not in-game or the skill isn't in the published skills array. Ids match the in-gameStatType.id(e.g. 25 for Divination, 26 for Invention, 6 for Magic); take them fromSkillsrather than writing the number.Read out of the snapshot — no RPC round-trip.
-
getGameCycle
int getGameCycle()Returns the producer's monotonically increasing game cycle counter. Backed by theget_game_cycleRPC. -
getLoginState
LoginState getLoginState()Returns the producer's current login state. Backed by theget_login_stateRPC. -
setWorld
void setWorld(int worldId) Initiates a world hop to the given world id. -
changeLoginState
void changeLoginState(int oldState, int newState) Requests a login state transition.- Parameters:
oldState- the expected current state, or<= 0to skip the checknewState- the desired new state
-
loginToLobby
void loginToLobby()Triggers a login from the login screen to the lobby.- Throws:
RuntimeException- if the client is not on the login screen
-
scheduleBreak
void scheduleBreak(int durationMs) Schedules a break (action-queue gate) for the given duration. -
interruptBreak
void interruptBreak()Interrupts any currently active break. -
getAutoLogin
boolean getAutoLogin()Returns whether the producer's auto-login state machine is enabled. -
setAutoLogin
void setAutoLogin(boolean enabled) Enables or disables the producer's auto-login state machine. -
getScriptHandle
long getScriptHandle(int scriptId) Obtains a producer-side handle to a client script for repeated execution. Release withdestroyScriptHandle(long)when done. -
executeScript
Executes a previously-obtained client script handle.- Parameters:
handle- handle fromgetScriptHandle(int)intArgs- integer args, ornullstringArgs- string args, ornullreturns- expected return-type descriptors, ornull
-
destroyScriptHandle
void destroyScriptHandle(long handle) Releases a script handle. -
fireComponentTrigger
void fireComponentTrigger(int interfaceId, int componentId, int subId, int triggerType, int arg) Fires a component's CS2 event trigger (click / key / ...) by event type, reproducing the engine's own component-event path. Enqueued on the action queue and run on the game thread; a component that carries no trigger of the requested type is a silent no-op.- Parameters:
interfaceId- owning interface idcomponentId- component idsubId- sub-component id, or-1for the top-level componenttriggerType- event type —9= click,10= key (seeActionTypes.TRIGGER_TYPE_*)arg- type-dependent argument. For key triggers, either form:- a bare Jagex key code (
0..0xFFFF, e.g.KeyStroke.CODE_ENTER): sent as a key-down with no character,(arg << 16) | 0; - a packed
KeyStroke.packed()((keyCode << 16) | keyChar, non-zero high half): sent unchanged. Use this to type a character (KeyStroke.character(c).packed()).
KeyStroke.keyTriggerArg(int). For click triggers, packed(x << 16) | ycomponent-relative press coordinates.0if unused.- a bare Jagex key code (
-
fireKeys
Fires a component's key (type-10) CS2 trigger once per stroke, in order, as a single batched action-queue request (one RPC round-trip). The agent dispatches one queued action per game tick, sonstrokes takenticks to land. A component with no key trigger — an input dialog that has already closed, for one — drops the strokes silently.For the game's own input dialog,
inputDialog()is the checked way in: it validates what it types against the dialog's mode and submits.- Returns:
- the number of strokes queued
-
fireKeyTrigger
Typesinputinto a component through its key (type-10) CS2 trigger, oneKeyStroke.character(char)per character, batched as byfireKeys(int, int, List). Types only — it does not submit; follow it withfireKeys(interfaceId, componentId, List.of(KeyStroke.ENTER)), or useinputDialog(), which types and submits in one batch. Anullor emptyinputqueues nothing.- Throws:
IllegalArgumentException- wheninputholds a character that is not printable ASCII
-
inputDialog
InputDialog inputDialog()The game's text/amount input dialog (withdraw-X, add-friend, ...). Singleton perGameAPI. -
components
Components components()Interface-component query facade — the high-level, fluent entry point for inspecting interface components (parallel tonpcs()/mapElements()). Singleton perGameAPI. Most scripts use this rather than the low-levelgetComponent(int, int)/getInterfaceTree(int, int)primitives below. -
getComponent
Returns the component at(interfaceId, componentId)ornullwhen no such component is loaded. Each call is a pipe round-trip — Phase 1 has no consumer-side cache.Phase 1 starter set covers identity + post-layout geometry only; text, item, sprite, hidden, color, font and other per-type fields are not yet surfaced and arrive in later slices.
-
getComponents
Batch counterpart ofgetComponent(int, int). The producer walks every target on a single game-thread visit, collapsing the latency of N independentgetComponentcalls (one tick each) into one tick total.The producer hard-caps the per-call batch (currently 64). Oversize inputs are silently truncated by the producer, so the returned list may be shorter than
refs; callers that need more than the cap should split into chunks themselves.- Parameters:
refs- components to resolve, in the desired result order- Returns:
- one element per resolved ref, in input order;
nullentries signal "not found" (matches the single-component contract). Length may be less thanrefs.size()when the producer cap is exceeded.
-
getStaticChildren
Returns the static (cache-defined) child component ids of(interfaceId, componentId). Each call is a pipe round-trip — Phase 1 has no consumer-side cache, so don't loop this in tight code yet.The list contains each child's own
componentIdwithin the same interface; entries equal to-1indicate a child whose packed address slot is unset (the producer surfaces the game's0xFFFFsentinel as -1). Returns an empty list when the parent is unresolvable (interface not loaded, component slot empty, or no static children). -
getDynamicChildren
Returns the dynamic (script-spawned) child component ids of(interfaceId, componentId). Same shape and caveats asgetStaticChildren(int, int); this is the path embedded dropdowns and other transient sub-trees travel through. -
getInterfaceTree
Returns the component at(interfaceId, componentId)and its entire descendant subtree, flattened breadth-first, in a single pipe round-trip. Empty list when the root doesn't resolve.Each
ComponentTreeNodecarries its component plus aparentIndexinto the same list (-1for the root). The producer follows the liveComponent*children vectors, so the walk spans mounted sub-interface boundaries — a child's own interface id rides along incomponent.ifaceId(), which per-nodegetStaticChildren(int, int)cannot follow.Most scripts use
components()instead; this is the seam theComponentsfacade drives. -
findComponentAt
Locate the deepest visible component under a screen-space coordinate, ornullwhen nothing is there. Coordinates are raw screen pixels (the value of Win32GetCursorPos); the producer runs inside the game process and converts to client-window space itself.The producer walks every open sub-interface on the game thread and picks the component with the greatest tree depth whose post-layout AABB contains the point — ties broken by the smaller AABB. Hidden components are excluded. Useful for debugger "pick on screen" tools and for scripters who know a feature's location but not its component id.
-
getItemType
- API Note:
- slice 5 stub — producer returns a sentinel response until the real cache-backed lookup lands.
-
getNpcType
- API Note:
- slice 5 stub — see
getItemType(int).
-
getLocationType
- API Note:
- slice 5 stub — see
getItemType(int).
-
getEnumType
- API Note:
- slice 5 stub — see
getItemType(int).
-
getStructType
- API Note:
- slice 5 stub — see
getItemType(int).
-
getSequenceType
- API Note:
- slice 5 stub — see
getItemType(int).
-
getQuestType
- API Note:
- slice 5 stub — see
getItemType(int).
-