@aifivem/lib 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/package.json +34 -4
  2. package/src/client/action.ts +38 -0
  3. package/src/client/adminWorld.ts +95 -0
  4. package/src/client/appearance.ts +29 -0
  5. package/src/client/areaFollower.ts +41 -0
  6. package/src/client/blip.ts +79 -0
  7. package/src/client/cache.ts +66 -0
  8. package/src/client/callback.ts +70 -0
  9. package/src/client/controls.ts +73 -0
  10. package/src/client/entities.ts +83 -0
  11. package/src/client/entity.ts +26 -0
  12. package/src/client/fuel.ts +18 -0
  13. package/src/client/gestures.ts +18 -0
  14. package/src/client/headshot.ts +26 -0
  15. package/src/client/hud.ts +24 -0
  16. package/src/client/index.ts +131 -0
  17. package/src/client/inventory.ts +117 -0
  18. package/src/client/keyHints.ts +13 -0
  19. package/src/client/keybind.ts +163 -0
  20. package/src/client/localPed.ts +169 -0
  21. package/src/client/location.ts +54 -0
  22. package/src/client/mdt.ts +10 -0
  23. package/src/client/medical.ts +28 -0
  24. package/src/client/membership.ts +41 -0
  25. package/src/client/menu/dialogs.ts +77 -0
  26. package/src/client/menu/minigames.ts +79 -0
  27. package/src/client/menu/requests.ts +65 -0
  28. package/src/client/modelScan/def.ts +29 -0
  29. package/src/client/modelScan/objectIndex.ts +41 -0
  30. package/src/client/modelScan/scan.ts +69 -0
  31. package/src/client/modelScan/scanner.ts +164 -0
  32. package/src/client/netEvent.ts +40 -0
  33. package/src/client/notify.ts +14 -0
  34. package/src/client/nuiScreen.ts +87 -0
  35. package/src/client/player/anim.ts +98 -0
  36. package/src/client/player/fade.ts +17 -0
  37. package/src/client/player/player.ts +80 -0
  38. package/src/client/player/teleport.ts +87 -0
  39. package/src/client/playerData.ts +83 -0
  40. package/src/client/players.ts +44 -0
  41. package/src/client/points/interact.ts +144 -0
  42. package/src/client/points/modelHost.ts +117 -0
  43. package/src/client/points/modelPoint.ts +181 -0
  44. package/src/client/points/point.ts +159 -0
  45. package/src/client/points/points.ts +170 -0
  46. package/src/client/points/targets/adapter.ts +40 -0
  47. package/src/client/points/targets/interactTarget.ts +45 -0
  48. package/src/client/points/targets/optionShape.ts +22 -0
  49. package/src/client/points/targets/oxTarget.ts +42 -0
  50. package/src/client/points/targets/qbTarget.ts +71 -0
  51. package/src/client/points/targets/targets.ts +20 -0
  52. package/src/client/preview.ts +51 -0
  53. package/src/client/progress.ts +132 -0
  54. package/src/client/prompt.ts +26 -0
  55. package/src/client/prop.ts +79 -0
  56. package/src/client/radial.ts +16 -0
  57. package/src/client/raycast.ts +48 -0
  58. package/src/client/scriptCamera.ts +167 -0
  59. package/src/client/seatbelt.ts +18 -0
  60. package/src/client/shot.ts +29 -0
  61. package/src/client/streaming.ts +91 -0
  62. package/src/client/tickLoop.ts +18 -0
  63. package/src/client/vehicleKeys.ts +14 -0
  64. package/src/client/vehicleProps.ts +107 -0
  65. package/src/client/vehicles.ts +46 -0
  66. package/src/client/waypoint.ts +10 -0
  67. package/src/client/world.ts +10 -0
  68. package/src/client/zoneEngine.ts +174 -0
  69. package/src/client/zones.ts +161 -0
  70. package/src/fivem/byResource.ts +146 -0
  71. package/src/fivem/callbackNames.ts +12 -0
  72. package/src/fivem/exports.ts +70 -0
  73. package/src/fivem/index.ts +13 -0
  74. package/src/fivem/locale.ts +57 -0
  75. package/src/fivem/playerData.ts +13 -0
  76. package/src/fivem/scheduler/every.ts +101 -0
  77. package/src/fivem/scheduler/group.ts +97 -0
  78. package/src/fivem/scheduler/scheduler.ts +77 -0
  79. package/src/fivem/state/entityState.ts +75 -0
  80. package/src/fivem/state/globalState.ts +80 -0
  81. package/src/fivem/state/mirror.ts +47 -0
  82. package/src/fivem/state/playerState.ts +60 -0
  83. package/src/server/admin/descriptions.ts +57 -0
  84. package/src/server/admin/edit.ts +127 -0
  85. package/src/server/admin/jsonSchema.ts +156 -0
  86. package/src/server/admin/panel.ts +167 -0
  87. package/src/server/admin/panelFiles.ts +128 -0
  88. package/src/server/admin/patch.ts +46 -0
  89. package/src/server/admin/validate.ts +147 -0
  90. package/src/server/appearance.ts +28 -0
  91. package/src/server/areaStream/areaStream.ts +141 -0
  92. package/src/server/areaStream/followers.ts +154 -0
  93. package/src/server/areaStream/grid.ts +74 -0
  94. package/src/server/areaStream/options.ts +16 -0
  95. package/src/server/banking.ts +15 -0
  96. package/src/server/bans.ts +47 -0
  97. package/src/server/billing.ts +20 -0
  98. package/src/server/buckets.ts +12 -0
  99. package/src/server/callback.ts +112 -0
  100. package/src/server/characters.ts +129 -0
  101. package/src/server/command/addCommand.ts +83 -0
  102. package/src/server/command/command.ts +116 -0
  103. package/src/server/command/commandSet.ts +74 -0
  104. package/src/server/dataFile.ts +81 -0
  105. package/src/server/database.ts +117 -0
  106. package/src/server/definitions.ts +65 -0
  107. package/src/server/dispatch.ts +13 -0
  108. package/src/server/doors.ts +15 -0
  109. package/src/server/ems.ts +15 -0
  110. package/src/server/fuel.ts +15 -0
  111. package/src/server/garages.ts +34 -0
  112. package/src/server/gate.ts +148 -0
  113. package/src/server/index.ts +165 -0
  114. package/src/server/inventory.ts +106 -0
  115. package/src/server/jobs.ts +42 -0
  116. package/src/server/log.ts +21 -0
  117. package/src/server/mdt.ts +12 -0
  118. package/src/server/medical.ts +16 -0
  119. package/src/server/minigameFor.ts +65 -0
  120. package/src/server/money.ts +70 -0
  121. package/src/server/netEntity.ts +19 -0
  122. package/src/server/netEvent.ts +58 -0
  123. package/src/server/notify.ts +17 -0
  124. package/src/server/online/mirror.ts +176 -0
  125. package/src/server/online/online.ts +190 -0
  126. package/src/server/pending.ts +70 -0
  127. package/src/server/phone.ts +22 -0
  128. package/src/server/players.ts +197 -0
  129. package/src/server/position.ts +31 -0
  130. package/src/server/primeTime.ts +7 -0
  131. package/src/server/prison.ts +15 -0
  132. package/src/server/progressFor.ts +62 -0
  133. package/src/server/proximity.ts +98 -0
  134. package/src/server/rateLimit.ts +53 -0
  135. package/src/server/state.ts +45 -0
  136. package/src/server/stress.ts +25 -0
  137. package/src/server/vehicle/nearby.ts +66 -0
  138. package/src/server/vehicle/plate.ts +14 -0
  139. package/src/server/vehicle/spawn.ts +125 -0
  140. package/src/server/vehicle/vehicleType.ts +50 -0
  141. package/src/server/vehicleKeys.ts +23 -0
  142. package/src/server/watchers.ts +46 -0
  143. package/src/server/world.ts +16 -0
  144. package/src/shared/access.ts +94 -0
  145. package/src/shared/action.ts +28 -0
  146. package/src/shared/blipStyle.ts +26 -0
  147. package/src/shared/clock.ts +22 -0
  148. package/src/shared/format.ts +36 -0
  149. package/src/shared/grid.ts +20 -0
  150. package/src/shared/index.ts +179 -0
  151. package/src/shared/lang.ts +39 -0
  152. package/src/shared/placePed.ts +96 -0
  153. package/src/shared/random.ts +11 -0
  154. package/src/shared/read.ts +60 -0
  155. package/src/shared/records.ts +148 -0
  156. package/src/shared/spec.ts +20 -0
  157. package/src/shared/strict.ts +70 -0
  158. package/src/shared/vec.ts +48 -0
  159. package/src/shared/vehicleProps.ts +138 -0
  160. package/src/shared/wait.ts +27 -0
  161. package/src/shared/zone.ts +144 -0
  162. package/README.md +0 -3
@@ -0,0 +1,40 @@
1
+ import { createLogger } from "../shared";
2
+
3
+ const log = createLogger(GetCurrentResourceName());
4
+
5
+ /**
6
+ * Whether the net event being handled came from the server (read it before the first `await`). On a client only
7
+ * events from the server carry a numeric source: 65535 for a normal event, 0 for a latent one (the client
8
+ * registers the server as reassembly target 0); a local emit by any resource carries a string.
9
+ */
10
+ export const fromServer = (): boolean => typeof globalThis.source === "number";
11
+
12
+ /**
13
+ * A net event the server sends: the only way an ai-* client listens to the server (never bare `onNet`). Calls that
14
+ * did not come from the server (another script's local emit) are dropped. A handler that takes arguments gets them
15
+ * only through `args` (`(name, { args }, handler)`; `null` drops the call). A thrown error is logged.
16
+ */
17
+ export function onServerEvent(name: string, handler: () => unknown): void;
18
+ export function onServerEvent<const A extends readonly unknown[]>(
19
+ name: string,
20
+ options: { args: (raw: unknown[]) => A | null },
21
+ handler: (...args: A) => unknown,
22
+ ): void;
23
+ export function onServerEvent(
24
+ name: string,
25
+ first:
26
+ (() => unknown) | { args: (raw: unknown[]) => readonly unknown[] | null },
27
+ second?: (...args: readonly unknown[]) => unknown,
28
+ ): void {
29
+ const [handler, parse] =
30
+ typeof first === "function" ? [first, null] : [second, first.args];
31
+ onNet(name, (...raw: unknown[]) => {
32
+ if (!fromServer() || !handler) return;
33
+ const args = parse ? parse(raw) : [];
34
+ if (!args)
35
+ return log.warn(`event ${name} from the server had invalid arguments`);
36
+ Promise.resolve()
37
+ .then(() => handler(...args))
38
+ .catch((error: unknown) => log.error(`event ${name} failed`, error));
39
+ });
40
+ }
@@ -0,0 +1,14 @@
1
+ import { LIB_UI, type NotificationKind } from "@aifivem/shared";
2
+ import { resourceExport } from "../fivem/exports";
3
+
4
+ const ui = resourceExport(LIB_UI.resource);
5
+
6
+ /** Shows a notification card on this player's screen (ai-lib draws it, `title` above the text); texts are already translated. */
7
+ export function notify(
8
+ text: string,
9
+ kind: NotificationKind = "info",
10
+ duration?: number,
11
+ title?: string,
12
+ ): void {
13
+ ui.Notify({ text, kind, duration, title });
14
+ }
@@ -0,0 +1,87 @@
1
+ import { hud } from "./hud";
2
+
3
+ /** A message to this resource's NUI page: `{ action, data }`. */
4
+ export interface NuiPageMessage {
5
+ action: string;
6
+ data?: unknown;
7
+ }
8
+
9
+ export interface NuiScreenOptions {
10
+ /** Show the mouse cursor while open (default true). */
11
+ cursor?: boolean;
12
+ /** Runs after the screen closed (the page's own close button included): the script's cleanup. */
13
+ onClose?: () => void;
14
+ /** The page's `close` callback closes the screen (default true; false when only the script may close it). */
15
+ closeCallback?: boolean;
16
+ }
17
+
18
+ type Reply = (result: unknown) => void;
19
+
20
+ /**
21
+ * This resource's full-screen NUI: `open` takes the focus, hides every HUD (lib `hud`) and sends the open message;
22
+ * `close` gives the focus back, shows the HUDs, sends `{ action: "close" }` and runs `onClose`. The page's `close`
23
+ * callback closes it. For full-screen UIs (overlays such as a chat box or a wheel keep the HUD and their own focus).
24
+ * One per resource, created once at module level.
25
+ */
26
+ export class NuiScreen<M extends NuiPageMessage = NuiPageMessage> {
27
+ private shown = false;
28
+
29
+ /** `name` is the HUD hide reason (`<resource>:<name>`). */
30
+ constructor(
31
+ private readonly name: string,
32
+ private readonly options: NuiScreenOptions = {},
33
+ ) {
34
+ if (options.closeCallback !== false)
35
+ RegisterNuiCallback("close", (_data: unknown, cb: Reply) => {
36
+ this.close();
37
+ cb({ ok: true });
38
+ });
39
+ }
40
+
41
+ get isOpen(): boolean {
42
+ return this.shown;
43
+ }
44
+
45
+ /** Focuses the page (once) and sends `message`. */
46
+ open(message: M): void {
47
+ if (!this.shown) {
48
+ this.shown = true;
49
+ SetNuiFocus(true, this.options.cursor ?? true);
50
+ hud.hide(this.name);
51
+ }
52
+ this.send(message);
53
+ }
54
+
55
+ close(): void {
56
+ if (!this.shown) return;
57
+ this.shown = false;
58
+ SetNuiFocus(false, false);
59
+ hud.show(this.name);
60
+ SendNUIMessage({ action: "close", data: null });
61
+ this.options.onClose?.();
62
+ }
63
+
64
+ /** A typed message to the page. */
65
+ send(message: M): void {
66
+ SendNUIMessage(message);
67
+ }
68
+
69
+ /**
70
+ * A NUI callback of the page: `parse` checks the data (null answers `{ ok: false }`), the handler's result (awaited)
71
+ * is the reply, `{ ok: true }` when it returns nothing.
72
+ */
73
+ on<A>(
74
+ name: string,
75
+ parse: (data: unknown) => A | null,
76
+ handler: (data: A) => unknown,
77
+ ): void {
78
+ RegisterNuiCallback(name, (raw: unknown, cb: Reply) => {
79
+ const data = parse(raw);
80
+ if (data === null) return cb({ ok: false });
81
+ Promise.resolve(handler(data)).then(
82
+ (result) => cb(result ?? { ok: true }),
83
+ () => cb({ ok: false }),
84
+ );
85
+ });
86
+ }
87
+ }
@@ -0,0 +1,98 @@
1
+ import { every } from "../../fivem/scheduler/every";
2
+ import { cache } from "../cache";
3
+ import { requestAnimDict } from "../streaming";
4
+
5
+ export interface AnimOptions {
6
+ /** `TaskPlayAnim` flag (default 49: upper body, loop, can move). */
7
+ flag?: number;
8
+ /** ms, -1 = until stopped (default -1). */
9
+ duration?: number;
10
+ blendIn?: number;
11
+ blendOut?: number;
12
+ }
13
+
14
+ export interface HoldAnimOptions extends AnimOptions {
15
+ /** Read every half second: the hold ends (and the animation stops) once it answers false. */
16
+ while?: () => boolean;
17
+ }
18
+
19
+ /** Plays an animation on the ped (loads and frees the dictionary); resolves when it started. */
20
+ export async function playAnim(
21
+ dict: string,
22
+ clip: string,
23
+ options: AnimOptions = {},
24
+ ): Promise<void> {
25
+ await requestAnimDict(dict);
26
+ TaskPlayAnim(
27
+ PlayerPedId(),
28
+ dict,
29
+ clip,
30
+ options.blendIn ?? 8,
31
+ options.blendOut ?? -8,
32
+ options.duration ?? -1,
33
+ options.flag ?? 49,
34
+ 0,
35
+ false,
36
+ false,
37
+ false,
38
+ );
39
+ RemoveAnimDict(dict);
40
+ }
41
+
42
+ export function stopAnim(): void {
43
+ ClearPedTasks(PlayerPedId());
44
+ }
45
+
46
+ /** The held animation of this resource: one at a time, put back by one shared job when something interrupts it. */
47
+ class AnimHold {
48
+ private current: {
49
+ dict: string;
50
+ clip: string;
51
+ options: HoldAnimOptions;
52
+ } | null = null;
53
+ private readonly job = every(500, () => this.check(), {
54
+ active: false,
55
+ name: "holdAnim",
56
+ });
57
+
58
+ start(
59
+ dict: string,
60
+ clip: string,
61
+ options: HoldAnimOptions,
62
+ ): { stop(): void } {
63
+ const hold = { dict, clip, options };
64
+ this.current = hold;
65
+ void playAnim(dict, clip, options);
66
+ this.job.set(true);
67
+ return { stop: () => this.end(hold) };
68
+ }
69
+
70
+ private end(hold: AnimHold["current"]): void {
71
+ if (this.current !== hold) return;
72
+ this.current = null;
73
+ this.job.set(false);
74
+ stopAnim();
75
+ }
76
+
77
+ private check(): void {
78
+ const hold = this.current;
79
+ if (!hold) return;
80
+ if (hold.options.while && !hold.options.while()) return this.end(hold);
81
+ if (!IsEntityPlayingAnim(cache.ped, hold.dict, hold.clip, 3))
82
+ void playAnim(hold.dict, hold.clip, hold.options);
83
+ }
84
+ }
85
+
86
+ let holds: AnimHold | null = null;
87
+
88
+ /**
89
+ * Keeps an animation playing (put back within half a second when a fall or a bump interrupts it) until `stop()` or
90
+ * `while` answers false; one hold per resource, a new one replaces the old.
91
+ */
92
+ export function holdAnim(
93
+ dict: string,
94
+ clip: string,
95
+ options: HoldAnimOptions = {},
96
+ ): { stop(): void } {
97
+ return (holds ??= new AnimHold()).start(dict, clip, options);
98
+ }
@@ -0,0 +1,17 @@
1
+ import { waitFor } from "../../shared";
2
+
3
+ /** Fades the screen out and resolves once it is black. */
4
+ export async function fadeOut(ms = 300): Promise<void> {
5
+ DoScreenFadeOut(ms);
6
+ await waitFor(() => IsScreenFadedOut() || undefined, ms + 2000).catch(
7
+ () => undefined,
8
+ );
9
+ }
10
+
11
+ /** Fades the screen back in and resolves when it is clear (or after `ms` + 2 s); the pair of `fadeOut`. */
12
+ export async function fadeIn(ms = 400): Promise<void> {
13
+ DoScreenFadeIn(ms);
14
+ await waitFor(() => IsScreenFadedIn() || undefined, ms + 2000).catch(
15
+ () => undefined,
16
+ );
17
+ }
@@ -0,0 +1,80 @@
1
+ import { cache } from "../cache";
2
+ import {
3
+ holdAnim,
4
+ playAnim,
5
+ stopAnim,
6
+ type AnimOptions,
7
+ type HoldAnimOptions,
8
+ } from "./anim";
9
+ import { teleport, type TeleportOptions } from "./teleport";
10
+
11
+ interface Vec3 {
12
+ x: number;
13
+ y: number;
14
+ z: number;
15
+ }
16
+
17
+ /**
18
+ * The local player's ped, like ox_core's player object: position, moves and animations in one place. Reads use
19
+ * `cache.ped` (loops); one-off actions read the ped fresh, so they also work right after a model change.
20
+ */
21
+ export const player = {
22
+ get ped(): number {
23
+ return cache.ped;
24
+ },
25
+
26
+ coords(): Vec3 {
27
+ const [x = 0, y = 0, z = 0] = GetEntityCoords(cache.ped, false);
28
+ return { x, y, z };
29
+ },
30
+
31
+ heading(): number {
32
+ return GetEntityHeading(cache.ped);
33
+ },
34
+
35
+ /** Distance from the ped to a point, in metres. */
36
+ distanceTo(point: Vec3): number {
37
+ const [x = 0, y = 0, z = 0] = GetEntityCoords(cache.ped, false);
38
+ return Math.hypot(x - point.x, y - point.y, z - point.z);
39
+ },
40
+
41
+ freeze(state: boolean): void {
42
+ FreezeEntityPosition(PlayerPedId(), state);
43
+ },
44
+
45
+ /**
46
+ * Moves the player and waits for the collision there, behind a fade unless `fade: false`. Without `z` (or with
47
+ * `ground: "find"`) the player lands on the ground under x / y.
48
+ */
49
+ teleport(
50
+ to: { x: number; y: number; z?: number },
51
+ options: TeleportOptions = {},
52
+ ): Promise<void> {
53
+ return teleport(to, options);
54
+ },
55
+
56
+ /** Plays an animation on the ped (loads and frees the dictionary); resolves when it started. */
57
+ playAnim(
58
+ dict: string,
59
+ clip: string,
60
+ options: AnimOptions = {},
61
+ ): Promise<void> {
62
+ return playAnim(dict, clip, options);
63
+ },
64
+
65
+ stopAnim(): void {
66
+ stopAnim();
67
+ },
68
+
69
+ /**
70
+ * Keeps an animation playing (put back within half a second when a fall or a bump interrupts it) until `stop()` or
71
+ * `while` answers false; one hold per resource, a new one replaces the old.
72
+ */
73
+ holdAnim(
74
+ dict: string,
75
+ clip: string,
76
+ options: HoldAnimOptions = {},
77
+ ): { stop(): void } {
78
+ return holdAnim(dict, clip, options);
79
+ },
80
+ };
@@ -0,0 +1,87 @@
1
+ import { sleep, waitFor } from "../../shared";
2
+ import { fadeOut } from "./fade";
3
+
4
+ export interface TeleportOptions {
5
+ heading?: number;
6
+ /**
7
+ * `true` (default): `z` is the floor (panel points), the game puts the ped's feet on it. `false`: z is the ped's
8
+ * root (`coords()`). `"find"` (also when `z` is missing): the ground under x / y is searched (map waypoint).
9
+ */
10
+ ground?: boolean | "find";
11
+ /** Behind a screen fade (default true). */
12
+ fade?: boolean;
13
+ /** Take the vehicle the player sits in along (default false). */
14
+ keepVehicle?: boolean;
15
+ }
16
+
17
+ /** Heights tried for the ground under a point, bottom to top. */
18
+ const PROBE_STEP = 25;
19
+ const PROBE_TOP = 1000;
20
+
21
+ /**
22
+ * The lowest ground under a point that is not inside an interior: the (frozen) ped stands at rising heights, each
23
+ * probe waits for the collision there (an unloaded street would be skipped and the roof above taken), and a surface
24
+ * inside an MLO / IPL interior is passed over for the next one up. Null when there is no ground at all.
25
+ */
26
+ async function findGround(
27
+ ped: number,
28
+ x: number,
29
+ y: number,
30
+ keepVehicle: boolean,
31
+ ): Promise<number | null> {
32
+ let indoor: number | null = null;
33
+ for (let height = 0; height <= PROBE_TOP; height += PROBE_STEP) {
34
+ if (keepVehicle) SetPedCoordsKeepVehicle(ped, x, y, height);
35
+ else SetEntityCoordsNoOffset(ped, x, y, height, false, false, false);
36
+ RequestCollisionAtCoord(x, y, height);
37
+ await sleep(50);
38
+ await waitFor(
39
+ () => HasCollisionLoadedAroundEntity(ped) || undefined,
40
+ 500,
41
+ 50,
42
+ ).catch(() => undefined);
43
+ const [found, groundZ] = GetGroundZFor_3dCoord(x, y, height, false);
44
+ if (!found) continue;
45
+ if (GetInteriorAtCoords(x, y, groundZ + 1) === 0) return groundZ;
46
+ indoor ??= groundZ;
47
+ }
48
+ // Every surface is indoors (a covered spot): the lowest one rather than nothing.
49
+ return indoor;
50
+ }
51
+
52
+ /**
53
+ * Moves the player and waits for the collision there, behind a fade unless `fade: false`. Without `z` (or with
54
+ * `ground: "find"`) the player lands on the ground under x / y.
55
+ */
56
+ export async function teleport(
57
+ to: { x: number; y: number; z?: number },
58
+ options: TeleportOptions = {},
59
+ ): Promise<void> {
60
+ const fade = options.fade !== false;
61
+ if (fade) await fadeOut();
62
+ const ped = PlayerPedId();
63
+ let z = to.z ?? 0;
64
+ let ground = options.ground;
65
+ if (to.z === undefined || ground === "find") {
66
+ FreezeEntityPosition(ped, true);
67
+ z =
68
+ ((await findGround(ped, to.x, to.y, options.keepVehicle === true)) ??
69
+ 0) + 1;
70
+ FreezeEntityPosition(ped, false);
71
+ ground = false;
72
+ }
73
+ RequestCollisionAtCoord(to.x, to.y, z);
74
+ if (options.keepVehicle) SetPedCoordsKeepVehicle(ped, to.x, to.y, z);
75
+ else if (ground === false)
76
+ SetEntityCoordsNoOffset(ped, to.x, to.y, z, false, false, false);
77
+ else SetEntityCoords(ped, to.x, to.y, z, false, false, false, false);
78
+ if (options.heading !== undefined) SetEntityHeading(ped, options.heading);
79
+ await waitFor(
80
+ () => HasCollisionLoadedAroundEntity(ped) || undefined,
81
+ 5000,
82
+ ).catch(() => undefined);
83
+ if (fade) {
84
+ await sleep(100);
85
+ DoScreenFadeIn(400);
86
+ }
87
+ }
@@ -0,0 +1,83 @@
1
+ import type { AiPlayerData } from "@aifivem/shared";
2
+ import { isRecord } from "../shared";
3
+ import {
4
+ PLAYER_DATA_EVENT,
5
+ PLAYER_DATA_PATCH_EVENT,
6
+ type PlayerDataKey,
7
+ } from "../fivem/playerData";
8
+ import { CORE } from "@aifivem/shared";
9
+ import { resourceExport } from "../fivem/exports";
10
+ import { onServerEvent } from "./netEvent";
11
+
12
+ const core = resourceExport(CORE.resource);
13
+
14
+ type Handler = (value: unknown) => void;
15
+
16
+ const values = new Map<string, unknown>();
17
+ const handlers = new Map<string, Set<Handler>>();
18
+ let listening = false;
19
+
20
+ function deliver(key: string, value: unknown): void {
21
+ values.set(key, value);
22
+ for (const handler of handlers.get(key) ?? []) handler(value);
23
+ }
24
+
25
+ function listen(): void {
26
+ if (listening) return;
27
+ listening = true;
28
+ // A resource started after the player loaded: the values pushed before come once from ai-core's export.
29
+ try {
30
+ const data: unknown = core.GetPlayerData();
31
+ if (isRecord(data))
32
+ for (const [key, value] of Object.entries(data))
33
+ if (!values.has(key)) values.set(key, value);
34
+ } catch {
35
+ // ai-core's client is not up yet: its pushes fill the values.
36
+ }
37
+ onServerEvent(
38
+ PLAYER_DATA_EVENT,
39
+ { args: ([key, value]) => (typeof key === "string" ? [key, value] : null) },
40
+ (key, value) => deliver(key, value),
41
+ );
42
+ onServerEvent(
43
+ PLAYER_DATA_PATCH_EVENT,
44
+ {
45
+ args: ([key, patch]) =>
46
+ typeof key === "string" && isRecord(patch) ? [key, patch] : null,
47
+ },
48
+ (key, patch) => {
49
+ const current = values.get(key);
50
+ deliver(key, { ...(isRecord(current) ? current : {}), ...patch });
51
+ },
52
+ );
53
+ }
54
+
55
+ /**
56
+ * Calls `handler` every time ai-core pushes `key` for this player. Returns an unsubscribe function. Values pushed
57
+ * before this resource started are read once from ai-core (`getPlayerData` has them), not replayed to `handler`.
58
+ */
59
+ export function onPlayerData<K extends PlayerDataKey>(
60
+ key: K,
61
+ handler: (value: AiPlayerData[K]) => void,
62
+ ): () => void {
63
+ listen();
64
+ const set = handlers.get(key) ?? new Set<Handler>();
65
+ set.add(handler as Handler);
66
+ handlers.set(key, set);
67
+ return () => set.delete(handler as Handler);
68
+ }
69
+
70
+ /** The last value pushed since this resource started, or undefined. */
71
+ export function getPlayerData<K extends PlayerDataKey>(
72
+ key: K,
73
+ ): AiPlayerData[K] | undefined {
74
+ listen();
75
+ return values.get(key) as AiPlayerData[K] | undefined;
76
+ }
77
+
78
+ /** Seeds the values by hand (the lib already seeds itself from ai-core's `GetPlayerData` on first use). */
79
+ export function seedPlayerData(data: Partial<AiPlayerData>): void {
80
+ listen();
81
+ for (const [key, value] of Object.entries(data))
82
+ if (!values.has(key)) values.set(key, value);
83
+ }
@@ -0,0 +1,44 @@
1
+ import type { Vec3 } from "../shared/vec";
2
+ import { cache } from "./cache";
3
+
4
+ /**
5
+ * The closest other player within `metres` of the local ped (or of `from`: a point in front for a tackle), as a server
6
+ * id; `filter` gets the server id and the ped (alive, on foot...). null when none. Walks the streamed players only.
7
+ */
8
+ export function nearestPlayer(
9
+ metres: number,
10
+ options: {
11
+ from?: Vec3;
12
+ filter?: (serverId: number, ped: number) => boolean;
13
+ } = {},
14
+ ): number | null {
15
+ let x: number;
16
+ let y: number;
17
+ let z: number;
18
+ if (options.from) ({ x, y, z } = options.from);
19
+ else [x = 0, y = 0, z = 0] = GetEntityCoords(cache.ped, false);
20
+ let best: number | null = null;
21
+ let bestDistance = metres;
22
+ for (const player of GetActivePlayers() as number[]) {
23
+ if (player === cache.playerId) continue;
24
+ const ped = GetPlayerPed(player);
25
+ const [px = 0, py = 0, pz = 0] = GetEntityCoords(ped, false);
26
+ const d = Math.hypot(px - x, py - y, pz - z);
27
+ if (d > bestDistance) continue;
28
+ const serverId = GetPlayerServerId(player);
29
+ if (options.filter && !options.filter(serverId, ped)) continue;
30
+ best = serverId;
31
+ bestDistance = d;
32
+ }
33
+ return best;
34
+ }
35
+
36
+ /**
37
+ * The ped of a player by server id: `cache.ped` for the local player, 0 when that player is not in scope (never the
38
+ * local ped through `GetPlayerPed(-1)`).
39
+ */
40
+ export function playerPed(serverId: number): number {
41
+ if (serverId === cache.serverId) return cache.ped;
42
+ const player = GetPlayerFromServerId(serverId);
43
+ return player === -1 ? 0 : GetPlayerPed(player);
44
+ }