docs.dev

SDK Queries Reference

The dev.n3u.queries package — AbstractQuery shaping and terminals, actor queries, all concrete query classes, thread affinity, and a looting example.

Fluent, chainable filtering over live game state. Queries are the read side of the SDK; the interaction APIs (SDK Game Reference, SDK Widgets Reference) are the write side. Source of truth: docs/sdk-queries-reference.md in the n3Client repository.

Purpose

Every concrete query extends AbstractQuery<N, Q> (api/src/main/java/dev/n3u/queries/abstractions/AbstractQuery.java), which stores predicates, comparators, limit/skip/distinct and a post-processor, then applies them when a terminal operation runs. Constructing a query fetches its GameManager entity list immediately (refreshing it if stale for the current tick, e.g. GameManager.npcList() at api/src/main/java/dev/n3u/services/GameManager.java:135-157); predicates, sorts, shaping and result copying are applied only when a terminal operation runs — calling first(), collect(), count(), etc. snapshots and evaluates.

Public surfaces

AbstractQuery<N, Q> (all queries inherit)

From api/src/main/java/dev/n3u/queries/abstractions/AbstractQuery.java:

  • Filters: removeIf(Predicate), keepIf(Predicate)
  • Ordering: sort(Comparator)
  • Shaping: limit(int), skip(int), distinct(), peek(Consumer), postProcess(Function)
  • Terminals: first(), last(), random(), collect(), collect(Collector), aggregate(Function), forEach(Consumer), count(), isEmpty(), any/all/none(Predicate), firstOrElse(2), lastOrElse(2), firstIfPresent(Consumer)
  • AbstractQuery captures Static.getClient() at construction and evaluates against a cached or supplied data source (AbstractQuery.java:24-28) — see thread-affinity note below.

AbstractActorQuery<N, Q> (actor queries inherit)

withName(1), withNameContains(1), canAttack(), isReachable(), hasLos(), free(), interactingWith(1), within(1), within(2), atLocation(1), sortNearest(0/1), sortFurthest(0/1), sortShortestPath(0/1), sortLongestPath(0/1), nearest(0/1), farthest(0/1), shortestPath(), longestPath() (abstractions/AbstractActorQuery.java).

The sortShortestPath/shortestPath members invoke the pathfinder, so they are far more expensive than distance sorts.

Concrete queries (api/src/main/java/dev/n3u/queries/)

QueryElementDistinct members beyond the baseSource data
NpcQueryNpcExwithIds, withIndex, withAction, withNames, alive, walkable, withinWorldAreaNpcQuery.java
PlayerQueryPlayerExbase actor members onlyPlayerQuery.java
TileItemQueryTileItemExwithId, withCanonicalId, withNames, price filters (greaterThanGePrice etc., alch values), location (within, atLocation), path sortsTileItemQuery.java
TileObjectQueryTileObjectExfromWorldView(), withAction, withAnyOfActions, withOpVisible, withActionVisible, withPartialAction, reachability, sortGreedyShortestPath(0/1)TileObjectQuery.java
InventoryQueryItemExfactories fromContainer(1), fromInventoryId(1), fromShop(1), fromCurrentShop(); withCanonicalId, price/value filters, fromSlot, aggregates getQuantity, getTotalGeValue, getTotalShopValue, getTotalHighAlchValue, unique()InventoryQuery.java
WidgetQueryWidget (RuneLite)withName/withId/withItemId/withParentId, withText, withTextContains, withActions, isVisible/isHidden/isSelfVisible/isSelfHidden, withType, withChildren/withNoChildren, withModelId, quantity filtersWidgetQuery.java
LocationQueryTileisReachable, hasLosTo, distance and pathing-distance filters, withinArea/outsideArea, hasTileObject, toWorldPointList, toLocalPointListLocationQuery.java
WorldQueryWorldisF2p/isP2p, withId/withActivity/withOutActivity/withTypes/withOutTypes/withRegion, withPlayerCount, ordering members, skill-total worlds, notPvp, isMainGame, next()/previous()WorldQuery.java
ShopQueryShopwithInventoryId, shopkeeper filters, canAccess, requirement filters, location and both local and global path sorts, getCurrent()ShopQuery.java
EntityQuery (combined/)Entityunion of players, NPCs, tile items and tile objects: ofTypes, removePlayers/removeNpcs/removeTileItems/removeTileObjects, name/action/distance filters, path sortscombined/EntityQuery.java

Data and control flow

Construct → chain filters/sorts → terminate. Example verified call path: NpcAPI.search() returns a fresh NpcQuery (api/src/main/java/dev/n3u/api/entities/NpcAPI.java), withNameContains adds a predicate, nearest() sorts by distance and returns one NpcEx. TileObjectQuery.fromWorldView() lazily filters to the local player's current world view at evaluation time (TileObjectQuery.java:33-36); the entity queries aggregate every world view registered in GameManager.worldViews (GameManager.java:99, maintained at :625/:631, enumerated at :118/:142/:216).

Callers

The api module is its own largest consumer — WalkerPath uses InventoryQuery/TileObjectQuery/WidgetQuery during walking (api/src/main/java/dev/n3u/services/pathfinder/model/WalkerPath.java imports), handlers and the Script DSL examples query before interacting. Bundled plugins are not query-package consumers across the board: the bank valuation plugin reads through the BankCache service and reacts to BankCacheChanged events instead (plugins/src/main/java/dev/n3u/plugins/bankvaluer/ imports dev.n3u.services.BankCache, dev.n3u.events.BankCacheChanged; verified 2026-11-06).

Thread affinity

Query construction runs on the calling thread: it captures Static.getClient() immediately and fetches the GameManager entity list, refreshing it if stale for the current tick — so construction itself touches live client state. All terminals — the execute()-backed first/last/random/collect/firstOrElse/lastOrElse/firstIfPresent and the direct forEach/count/isEmpty/any/all/none/aggregate/collect(Collector) — dispatch onto the client thread via Static.invoke and block the calling thread (AbstractQuery.java:103-141, direct wraps at :214,238,252,267-303,311,326). Evaluate queries from NPlugin.loop() or a GameTick subscriber; do not cache query results across ticks. Off-thread hazards are chain-time reads such as isReachable()/hasLos()/sortNearest(), which call PlayerEx.getLocal() at chain time (e.g. isReachable() at AbstractActorQuery.java:54-57).

Worked example — looting with a fallback

import dev.n3u.api.entities.TileItemAPI;
import dev.n3u.data.wrappers.TileItemEx;
import net.runelite.api.coords.WorldPoint;

public void lootValuables(WorldPoint here)
{
    TileItemEx loot = TileItemAPI.search()          // TileItemQuery
            .withName("Dragon bones")
            .within(here, 8)
            .sortNearest()
            .first();

    if (loot == null) {
        return;                                      // expected: nothing matched
    }
    TileItemAPI.interact(loot, "Take");              // packet send on client thread
}

Expected result: one Take action on the nearest stack within 8 tiles. Failure handling: every terminal returns an empty result rather than throwing when nothing matches; interact methods null-check their target (verified pattern in NpcAPI.interact, NpcAPI.java:29-33). Price filters use GE/shop/alch values from item compositions; unknown items price as 0 (inference from filter naming — verify per item if value-critical).

Tests

git ls-files "api/src/test/java" (run 2026-11-06) shows only BankQuantityResolverTest, MapResourcesTest, NOverlayTest, NExternalsPanelTest. No query class has a dedicated automated test.

Known limits

  • Path-based sorts (sortShortestPath, shortestPath) are orders of magnitude costlier than distance sorts; they call the pathfinder per comparison candidate.
  • Queries snapshot when terminated, not when chained; long chains over fast-moving scenes can observe a mix of states if evaluated off the client thread.
  • WorldQuery members operate on the world list refreshed by the client; stale lists are possible right after login (open question — refresh timing lives in injected code, not in this repository's sources).

On this page