@aifivem/lib 0.7.0 → 0.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aifivem/lib",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Helpers every ai-core resource uses: logging, exports, rate limits, database tables.",
5
5
  "license": "GPL-3.0-only",
6
6
  "repository": {
@@ -22,7 +22,7 @@
22
22
  "access": "public"
23
23
  },
24
24
  "dependencies": {
25
- "@aifivem/shared": "^0.6.0",
25
+ "@aifivem/shared": "^0.8.0",
26
26
  "@aifivem/mysql": "^0.2.0"
27
27
  },
28
28
  "devDependencies": {
@@ -0,0 +1,51 @@
1
+ import { createColshape, deleteColshape, onColshape } from "../fivem/colshape";
2
+ import { sleep } from "../shared";
3
+
4
+ /** How long a test shape waits for the local player's enter (FiveM samples every 50 ms). */
5
+ const WAIT_MS = 2000;
6
+ const TRIES = 6;
7
+
8
+ /** One test: a 50 m sphere around the player must report the player's own ped entering it. */
9
+ async function testOnce(ped: number): Promise<"yes" | "no" | "missing"> {
10
+ const [x = 0, y = 0, z = 0] = GetEntityCoords(ped, false);
11
+ const id = createColshape({
12
+ type: "sphere",
13
+ center: { x, y, z },
14
+ radius: 50,
15
+ });
16
+ if (id === null) return "missing";
17
+ const entered = await new Promise<boolean>((resolve) => {
18
+ const timer = setTimeout(() => {
19
+ stop();
20
+ resolve(false);
21
+ }, WAIT_MS);
22
+ const stop = onColshape(id, (entity, inside) => {
23
+ if (!inside || entity !== PlayerPedId()) return;
24
+ clearTimeout(timer);
25
+ stop();
26
+ resolve(true);
27
+ });
28
+ });
29
+ deleteColshape(id);
30
+ return entered ? "yes" : "no";
31
+ }
32
+
33
+ /**
34
+ * Whether colshapes work for the local player on this client: the natives exist and FiveM samples the player's ped
35
+ * as a player (type 11). A try counts only once the ped has its network object (before that FiveM samples it as a
36
+ * plain ped, which the zones' shapes ignore); false means zones keep the script-side check.
37
+ */
38
+ export async function colshapesWork(): Promise<boolean> {
39
+ for (let tries = 0; tries < TRIES;) {
40
+ const ped = PlayerPedId();
41
+ if (!ped || !DoesEntityExist(ped) || !NetworkGetEntityIsNetworked(ped)) {
42
+ await sleep(1000);
43
+ continue;
44
+ }
45
+ const result = await testOnce(ped);
46
+ if (result !== "no") return result === "yes";
47
+ tries++;
48
+ await sleep(5000);
49
+ }
50
+ return false;
51
+ }
@@ -6,6 +6,7 @@ export { ScriptCamera } from "./scriptCamera";
6
6
  export { medical } from "./medical";
7
7
  export { fuel } from "./fuel";
8
8
  export { mdt } from "./mdt";
9
+ export { phone } from "./phone";
9
10
  export {
10
11
  NuiScreen,
11
12
  type NuiPageMessage,
@@ -48,11 +49,7 @@ export {
48
49
  type ProgressOptions,
49
50
  } from "./progress";
50
51
  export { input, itemPicker, menu } from "./menu/dialogs";
51
- export {
52
- lockpick,
53
- skillCheck,
54
- type LockpickOptions,
55
- } from "./menu/minigames";
52
+ export { lockpick, skillCheck, type LockpickOptions } from "./menu/minigames";
56
53
  export type { MenuListeners } from "./menu/requests";
57
54
  export { inventory } from "./inventory";
58
55
  export { vehicleKeys } from "./vehicleKeys";
@@ -98,6 +95,12 @@ export {
98
95
  resourceExport,
99
96
  } from "../fivem/exports";
100
97
  export { createLocale, loadLocaleTexts, LOCALE_CONVAR } from "../fivem/locale";
98
+ export {
99
+ createColshape,
100
+ deleteColshape,
101
+ hasColshapes,
102
+ onColshape,
103
+ } from "../fivem/colshape";
101
104
  export { EntityState } from "../fivem/state/entityState";
102
105
  export { GlobalGroup, GlobalKey } from "../fivem/state/globalState";
103
106
  export { PlayerState } from "../fivem/state/playerState";
@@ -0,0 +1,14 @@
1
+ import { CORE } from "@aifivem/shared";
2
+
3
+ /** The local player's phone through ai-core's client phone layer, whatever phone runs (`docs/compat/phone.md`). */
4
+ export const phone = {
5
+ /**
6
+ * `fn(phone)` when the local player opens the phone (`phone`: the phone's resource name): once per opening, at most
7
+ * once per 10 s; nothing for a phone without an open signal.
8
+ */
9
+ onUsed(fn: (phone: string) => void): void {
10
+ on(CORE.clientPhoneUsedEvent, (phone: unknown) => {
11
+ if (typeof phone === "string") fn(phone);
12
+ });
13
+ },
14
+ };
@@ -0,0 +1,98 @@
1
+ import { createColshape, deleteColshape, onColshape } from "../fivem/colshape";
2
+ import { createLogger, sleep } from "../shared";
3
+ import { zoneContains } from "../shared/zone";
4
+ import { onCache } from "./cache";
5
+ import { colshapesWork } from "./colshapeCheck";
6
+ import type { Zone } from "./zoneGrid";
7
+
8
+ const log = createLogger(GetCurrentResourceName());
9
+
10
+ /** Delay of the one position check after a zone gets its colshape or the ped changes. */
11
+ const SETTLE_MS = 250;
12
+ /** Zones moved onto colshapes per tick at the hand-over (about 15 natives each). */
13
+ const CHUNK = 500;
14
+
15
+ /**
16
+ * The colshape side of a `ZoneEngine`: zones as FiveM colshapes once a live test passed. FiveM reports only the
17
+ * changes it saw itself, so a zone is checked once against the player's position after its colshape is made (a
18
+ * seeded or handed-over state, an event still queued for the id's previous shape) and after a ped change. A zone's
19
+ * `interval` stays the shortest gap between two of its enter / exit calls.
20
+ */
21
+ export class ColshapeZones {
22
+ /** Colshapes passed the live test. */
23
+ active = false;
24
+ private readonly attached = new Set<Zone>();
25
+ private lastPed = 0;
26
+
27
+ constructor(
28
+ private readonly setInside: (zone: Zone, inside: boolean) => void,
29
+ ) {}
30
+
31
+ /** Runs the live test; on a pass moves the script-checked zones (`filed()` then) over, calling `moved` for each. */
32
+ async start(filed: () => Zone[], moved: (zone: Zone) => void): Promise<void> {
33
+ if (!(await colshapesWork())) {
34
+ log.warn("zones: colshapes unavailable, script check kept");
35
+ return;
36
+ }
37
+ this.active = true;
38
+ this.lastPed = PlayerPedId();
39
+ // The new ped's handle is noticed at the next colshape event too (the old ped exits every shape as it goes).
40
+ onCache("ped", () => this.pedChanged());
41
+ const zones = filed();
42
+ for (let i = 0; i < zones.length; i += CHUNK) {
43
+ if (i > 0) await sleep(0);
44
+ for (const zone of zones.slice(i, i + CHUNK))
45
+ if (zone.filed && this.attach(zone)) moved(zone);
46
+ }
47
+ }
48
+
49
+ /** The zone as a colshape; false when it stays on the script check. */
50
+ attach(zone: Zone): boolean {
51
+ if (!this.active) return false;
52
+ const id = createColshape(zone.options.shape);
53
+ if (id === null) return false;
54
+ zone.colshape = id;
55
+ zone.unsubscribe = onColshape(id, (entity, inside) =>
56
+ this.event(zone, entity, inside),
57
+ );
58
+ this.attached.add(zone);
59
+ this.recheck(zone, SETTLE_MS);
60
+ return true;
61
+ }
62
+
63
+ detach(zone: Zone): void {
64
+ if (zone.colshape === null) return;
65
+ zone.unsubscribe?.();
66
+ deleteColshape(zone.colshape);
67
+ if (zone.recheck !== null) clearTimeout(zone.recheck);
68
+ zone.colshape = null;
69
+ zone.unsubscribe = null;
70
+ zone.recheck = null;
71
+ this.attached.delete(zone);
72
+ }
73
+
74
+ private event(zone: Zone, entity: number, inside: boolean): void {
75
+ const ped = PlayerPedId();
76
+ if (ped !== this.lastPed) this.pedChanged();
77
+ if (entity !== ped || inside === zone.inside) return;
78
+ const wait = zone.lastFire + zone.interval - GetGameTimer();
79
+ if (wait > 0) this.recheck(zone, wait);
80
+ else this.setInside(zone, inside);
81
+ }
82
+
83
+ private pedChanged(): void {
84
+ this.lastPed = PlayerPedId();
85
+ for (const zone of this.attached) this.recheck(zone, SETTLE_MS);
86
+ }
87
+
88
+ /** One position check of the zone after `ms` (an earlier pending one stands). */
89
+ private recheck(zone: Zone, ms: number): void {
90
+ if (zone.recheck !== null) return;
91
+ zone.recheck = setTimeout(() => {
92
+ zone.recheck = null;
93
+ if (zone.colshape === null) return;
94
+ const [x = 0, y = 0, z = 0] = GetEntityCoords(PlayerPedId(), false);
95
+ this.setInside(zone, zoneContains(zone.options.shape, x, y, z));
96
+ }, ms);
97
+ }
98
+ }
@@ -1,60 +1,52 @@
1
1
  import { every, type Job } from "../fivem/scheduler/every";
2
2
  import { createLogger } from "../shared";
3
- import { zoneBounds, zoneContains, type ZoneShape } from "../shared/zone";
3
+ import { zoneContains } from "../shared/zone";
4
4
  import { cache } from "./cache";
5
+ import { ColshapeZones } from "./zoneColshapes";
6
+ import { Zone, ZoneGrid, type ZoneOptions } from "./zoneGrid";
7
+
8
+ export type { ZoneOptions };
5
9
 
6
10
  /**
7
- * The zone checker: inside / outside checks at each zone's own interval, never per frame. Built for any count
8
- * (measured with 1,000,000 zones): zones sit in a grid of 64 m cells and a check looks only at the player's cell and
9
- * the zones the player is in. ai-lib runs one for every resource's zones (`zones.ts`); a resource runs its own only
10
- * while ai-lib does not.
11
+ * The zone checker. With `colshapes` (ai-lib's checker only) each zone becomes a FiveM colshape once a live test
12
+ * passed (`zoneColshapes.ts`): FiveM tests every shape at 20 Hz on a worker thread and JS sees only enter / exit
13
+ * events (every player's ped, filtered here to the local one). Otherwise, and for
14
+ * a zone FiveM refuses, the script check: each zone at its own interval, never per frame, in a grid of 64 m cells
15
+ * (measured with 1,000,000 zones). ai-lib runs one for every resource's zones (`zones.ts`); a resource runs its own
16
+ * only while ai-lib does not.
11
17
  */
12
18
 
13
19
  const log = createLogger(GetCurrentResourceName());
14
20
 
15
- export interface ZoneOptions {
16
- shape: ZoneShape;
17
- /** How often to check, in ms (default 500, at least 50). A shop needs ~500, a fast trigger ~100; per-frame work belongs elsewhere. */
18
- interval?: number;
19
- onEnter?: () => void;
20
- onExit?: () => void;
21
- }
22
-
23
- const CELL = 64;
24
- /** A zone wider than this many cells is kept in one list checked every time instead of in the grid. */
25
- const MAX_CELLS = 64;
26
- const cellKey = (cx: number, cy: number): number =>
27
- ((cx + 32768) << 16) | (cy + 32768);
28
-
29
- class Zone {
30
- inside = false;
31
- nextCheck = 0;
32
- readonly interval: number;
33
- /** Grid cells the zone is filed under; empty when it is in the large list. */
34
- readonly cells: number[] = [];
35
-
36
- constructor(
37
- readonly options: ZoneOptions,
38
- inside: boolean,
39
- ) {
40
- this.interval = Math.max(50, options.interval ?? 500);
41
- this.inside = inside;
42
- }
21
+ export interface ZoneEngineOptions {
22
+ /** Zones as FiveM colshapes after a live test. Every resource listening for colshape events gets all of them: one engine per client. */
23
+ colshapes?: boolean;
43
24
  }
44
25
 
45
26
  /**
46
- * A set of zones. One scheduler job serves them all at the shortest interval any zone asks for; each zone is checked
47
- * only when its own interval has passed. With no zones the job stops.
27
+ * A set of zones. One scheduler job serves the script-checked ones at the shortest interval any of them asks for;
28
+ * each zone is checked only when its own interval has passed. With none of them the job stops.
48
29
  */
49
30
  export class ZoneEngine {
50
31
  private readonly zones = new Map<string, Zone>();
51
- private readonly grid = new Map<number, Set<Zone>>();
52
- private readonly large = new Set<Zone>();
32
+ private readonly grid = new ZoneGrid();
53
33
  private readonly insideNow = new Set<Zone>();
54
- /** How many zones use each interval, so the shortest one is found without walking every zone. */
55
- private readonly intervals = new Map<number, number>();
56
34
  private job: Job | null = null;
57
35
  private period = 0;
36
+ private readonly colshapes = new ColshapeZones((zone, inside) =>
37
+ this.setInside(zone, inside),
38
+ );
39
+
40
+ constructor(options: ZoneEngineOptions = {}) {
41
+ if (!options.colshapes) return;
42
+ void this.colshapes.start(
43
+ () => [...this.zones.values()].filter((zone) => zone.filed),
44
+ (zone) => {
45
+ this.grid.unfile(zone);
46
+ this.schedule();
47
+ },
48
+ );
49
+ }
58
50
 
59
51
  /**
60
52
  * Adds (or replaces) a zone. A replaced zone the player was in fires its onExit first. `inside` seeds the state of a
@@ -65,27 +57,8 @@ export class ZoneEngine {
65
57
  const zone = new Zone(options, inside);
66
58
  this.zones.set(id, zone);
67
59
  if (inside) this.insideNow.add(zone);
68
- const [minX, minY, maxX, maxY] = zoneBounds(options.shape);
69
- const x0 = Math.floor(minX / CELL);
70
- const y0 = Math.floor(minY / CELL);
71
- const x1 = Math.floor(maxX / CELL);
72
- const y1 = Math.floor(maxY / CELL);
73
- if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS) this.large.add(zone);
74
- else {
75
- for (let cx = x0; cx <= x1; cx++) {
76
- for (let cy = y0; cy <= y1; cy++) {
77
- const key = cellKey(cx, cy);
78
- let cell = this.grid.get(key);
79
- if (!cell) this.grid.set(key, (cell = new Set()));
80
- cell.add(zone);
81
- zone.cells.push(key);
82
- }
83
- }
84
- }
85
- this.intervals.set(
86
- zone.interval,
87
- (this.intervals.get(zone.interval) ?? 0) + 1,
88
- );
60
+ if (this.colshapes.attach(zone)) return;
61
+ this.grid.file(zone);
89
62
  this.schedule();
90
63
  }
91
64
 
@@ -94,27 +67,18 @@ export class ZoneEngine {
94
67
  const zone = this.zones.get(id);
95
68
  if (!zone) return;
96
69
  this.zones.delete(id);
97
- this.large.delete(zone);
98
- for (const key of zone.cells) {
99
- const cell = this.grid.get(key);
100
- cell?.delete(zone);
101
- if (cell?.size === 0) this.grid.delete(key);
102
- }
103
- const left = (this.intervals.get(zone.interval) ?? 1) - 1;
104
- if (left > 0) this.intervals.set(zone.interval, left);
105
- else this.intervals.delete(zone.interval);
70
+ this.colshapes.detach(zone);
71
+ if (this.grid.unfile(zone)) this.schedule();
106
72
  if (this.insideNow.delete(zone) && !quiet) this.fire(zone, false);
107
- this.schedule();
108
73
  }
109
74
 
110
75
  /** Removes every zone (exits fire for the ones the player is in). */
111
76
  clear(): void {
112
77
  const inside = [...this.insideNow];
78
+ for (const zone of this.zones.values()) this.colshapes.detach(zone);
113
79
  this.zones.clear();
114
80
  this.grid.clear();
115
- this.large.clear();
116
81
  this.insideNow.clear();
117
- this.intervals.clear();
118
82
  for (const zone of inside) this.fire(zone, false);
119
83
  this.schedule();
120
84
  }
@@ -128,9 +92,7 @@ export class ZoneEngine {
128
92
  }
129
93
 
130
94
  private schedule(): void {
131
- let period = 0;
132
- for (const interval of this.intervals.keys())
133
- period = period === 0 ? interval : Math.min(period, interval);
95
+ const period = this.grid.shortestInterval();
134
96
  if (period === this.period) return;
135
97
  this.job?.stop();
136
98
  this.job = period
@@ -143,18 +105,18 @@ export class ZoneEngine {
143
105
  const now = GetGameTimer();
144
106
  const [x = 0, y = 0, z = 0] = GetEntityCoords(cache.ped, false);
145
107
  // The zones the player is in go first, so leaving one is noticed wherever the player went.
146
- for (const zone of this.insideNow) this.test(zone, now, x, y, z);
147
- for (const zone of this.large) this.test(zone, now, x, y, z);
148
- const cell = this.grid.get(
149
- cellKey(Math.floor(x / CELL), Math.floor(y / CELL)),
150
- );
151
- if (cell) for (const zone of cell) this.test(zone, now, x, y, z);
108
+ for (const zone of this.insideNow)
109
+ if (zone.filed) this.test(zone, now, x, y, z);
110
+ this.grid.forNear(x, y, (zone) => this.test(zone, now, x, y, z));
152
111
  }
153
112
 
154
113
  private test(zone: Zone, now: number, x: number, y: number, z: number): void {
155
114
  if (now < zone.nextCheck) return;
156
115
  zone.nextCheck = now + zone.interval;
157
- const inside = zoneContains(zone.options.shape, x, y, z);
116
+ this.setInside(zone, zoneContains(zone.options.shape, x, y, z));
117
+ }
118
+
119
+ private setInside(zone: Zone, inside: boolean): void {
158
120
  if (inside === zone.inside) return;
159
121
  if (inside) this.insideNow.add(zone);
160
122
  else this.insideNow.delete(zone);
@@ -163,6 +125,7 @@ export class ZoneEngine {
163
125
 
164
126
  private fire(zone: Zone, inside: boolean): void {
165
127
  zone.inside = inside;
128
+ zone.lastFire = GetGameTimer();
166
129
  // A failing enter / exit handler must not stop the other zones.
167
130
  try {
168
131
  if (inside) zone.options.onEnter?.();
@@ -0,0 +1,115 @@
1
+ import { zoneBounds, type ZoneShape } from "../shared/zone";
2
+
3
+ export interface ZoneOptions {
4
+ shape: ZoneShape;
5
+ /**
6
+ * How often the script check runs, in ms (default 500, at least 50). A colshape zone is tested every 50 ms by
7
+ * FiveM, and this stays the shortest gap between two of its enter / exit calls.
8
+ */
9
+ interval?: number;
10
+ onEnter?: () => void;
11
+ onExit?: () => void;
12
+ }
13
+
14
+ export class Zone {
15
+ inside = false;
16
+ nextCheck = 0;
17
+ readonly interval: number;
18
+ /** Grid cells the zone is filed under (`ZoneGrid`). */
19
+ readonly cells: number[] = [];
20
+ /** Filed for the script check. */
21
+ filed = false;
22
+ colshape: number | null = null;
23
+ unsubscribe: (() => void) | null = null;
24
+ /** Pending position check of a colshape zone (`zoneColshapes.ts`). */
25
+ recheck: ReturnType<typeof setTimeout> | null = null;
26
+ /** Game time of the last enter / exit call. */
27
+ lastFire = 0;
28
+
29
+ constructor(
30
+ readonly options: ZoneOptions,
31
+ inside: boolean,
32
+ ) {
33
+ this.interval = Math.max(50, options.interval ?? 500);
34
+ this.inside = inside;
35
+ }
36
+ }
37
+
38
+ const CELL = 64;
39
+ /** A zone wider than this many cells is kept in one list checked every time instead of in the grid. */
40
+ const MAX_CELLS = 64;
41
+ const cellKey = (cx: number, cy: number): number =>
42
+ ((cx + 32768) << 16) | (cy + 32768);
43
+
44
+ /** The script-checked zones of a `ZoneEngine`: a grid of 64 m cells, a list of very large zones, and their intervals. */
45
+ export class ZoneGrid {
46
+ private readonly cells = new Map<number, Set<Zone>>();
47
+ private readonly large = new Set<Zone>();
48
+ /** How many zones use each interval, so the shortest one is found without walking every zone. */
49
+ private readonly intervals = new Map<number, number>();
50
+
51
+ file(zone: Zone): void {
52
+ zone.filed = true;
53
+ const [minX, minY, maxX, maxY] = zoneBounds(zone.options.shape);
54
+ const x0 = Math.floor(minX / CELL);
55
+ const y0 = Math.floor(minY / CELL);
56
+ const x1 = Math.floor(maxX / CELL);
57
+ const y1 = Math.floor(maxY / CELL);
58
+ if ((x1 - x0 + 1) * (y1 - y0 + 1) > MAX_CELLS) this.large.add(zone);
59
+ else {
60
+ for (let cx = x0; cx <= x1; cx++) {
61
+ for (let cy = y0; cy <= y1; cy++) {
62
+ const key = cellKey(cx, cy);
63
+ let cell = this.cells.get(key);
64
+ if (!cell) this.cells.set(key, (cell = new Set()));
65
+ cell.add(zone);
66
+ zone.cells.push(key);
67
+ }
68
+ }
69
+ }
70
+ this.intervals.set(
71
+ zone.interval,
72
+ (this.intervals.get(zone.interval) ?? 0) + 1,
73
+ );
74
+ }
75
+
76
+ /** Takes a zone out; false when it was not filed. */
77
+ unfile(zone: Zone): boolean {
78
+ if (!zone.filed) return false;
79
+ zone.filed = false;
80
+ this.large.delete(zone);
81
+ for (const key of zone.cells) {
82
+ const cell = this.cells.get(key);
83
+ cell?.delete(zone);
84
+ if (cell?.size === 0) this.cells.delete(key);
85
+ }
86
+ zone.cells.length = 0;
87
+ const left = (this.intervals.get(zone.interval) ?? 1) - 1;
88
+ if (left > 0) this.intervals.set(zone.interval, left);
89
+ else this.intervals.delete(zone.interval);
90
+ return true;
91
+ }
92
+
93
+ clear(): void {
94
+ this.cells.clear();
95
+ this.large.clear();
96
+ this.intervals.clear();
97
+ }
98
+
99
+ /** The shortest interval of the filed zones, 0 with none. */
100
+ shortestInterval(): number {
101
+ let period = 0;
102
+ for (const interval of this.intervals.keys())
103
+ period = period === 0 ? interval : Math.min(period, interval);
104
+ return period;
105
+ }
106
+
107
+ /** Runs `fn` for the zones that may contain a point: the large ones and the point's cell. */
108
+ forNear(x: number, y: number, fn: (zone: Zone) => void): void {
109
+ for (const zone of this.large) fn(zone);
110
+ const cell = this.cells.get(
111
+ cellKey(Math.floor(x / CELL), Math.floor(y / CELL)),
112
+ );
113
+ if (cell) for (const zone of cell) fn(zone);
114
+ }
115
+ }
@@ -0,0 +1,128 @@
1
+ import { createLogger } from "../shared";
2
+ import type { ZoneShape } from "../shared/zone";
3
+
4
+ /**
5
+ * FiveM colshapes on both sides: shapes kept by FiveM itself (one BVH for every resource, entities sampled at 20 Hz,
6
+ * the test on a worker thread) that raise `onColshapeEnter` / `onColshapeExit(entity, id)` in every resource listening
7
+ * for them. Documented for Enhanced,
8
+ * backported to Legacy and RedM (citizenfx/fivem "feat(natives): backport colshape natives to legacy + rdr3",
9
+ * 2026-07-23). A resource's shapes are deleted when it stops.
10
+ */
11
+
12
+ const log = createLogger(GetCurrentResourceName());
13
+
14
+ /** GTA V `NetObjEntityType` (citizenfx/fivem `code/shared/net/NetObjEntityType.h`): 0 automobile ... 13 train. */
15
+ const ENTITY_TYPES = 14;
16
+ /** A player's ped (`CNetObjPlayer`). */
17
+ const PLAYER_TYPE = 11;
18
+
19
+ let available: boolean | undefined;
20
+
21
+ /** Whether this build has colshapes: a test shape must exist after it is created (probed once). */
22
+ export function hasColshapes(): boolean {
23
+ if (available === undefined) {
24
+ try {
25
+ const id = CreateColshapeSphere(0, 0, -5000, 0.1);
26
+ const valid = typeof id === "number" && id >= 0;
27
+ // BOOL natives answer 1 / 0 in JS.
28
+ available = valid && Boolean(DoesColshapeExist(id));
29
+ if (valid) DeleteColshape(id);
30
+ } catch {
31
+ available = false;
32
+ }
33
+ }
34
+ return available;
35
+ }
36
+
37
+ /**
38
+ * A lib `ZoneShape` as a colshape that only players' peds trigger; null without colshapes or when FiveM refuses
39
+ * it (its ids are shared by every resource): the caller keeps its own check then.
40
+ */
41
+ export function createColshape(shape: ZoneShape): number | null {
42
+ if (!hasColshapes()) return null;
43
+ let id: unknown;
44
+ try {
45
+ switch (shape.type) {
46
+ case "sphere":
47
+ id = CreateColshapeSphere(
48
+ shape.center.x,
49
+ shape.center.y,
50
+ shape.center.z,
51
+ shape.radius,
52
+ );
53
+ break;
54
+ case "cylinder":
55
+ // Ours reaches `height` up and down from the centre; FiveM's height is the whole cylinder.
56
+ id = CreateColshapeCylinder(
57
+ shape.center.x,
58
+ shape.center.y,
59
+ shape.center.z,
60
+ shape.radius,
61
+ shape.height * 2,
62
+ );
63
+ break;
64
+ case "poly":
65
+ if (shape.points.length < 3) return null;
66
+ id = CreateColshapePolygon(
67
+ shape.minZ,
68
+ shape.maxZ,
69
+ shape.points.flatMap((p) => [p.x, p.y]),
70
+ );
71
+ break;
72
+ }
73
+ if (typeof id !== "number" || id < 0 || !DoesColshapeExist(id)) return null;
74
+ for (let type = 0; type < ENTITY_TYPES; type++)
75
+ if (type !== PLAYER_TYPE) SetColshapeEntityType(id, type, false);
76
+ return id;
77
+ } catch (error) {
78
+ log.error("colshape could not be created", error);
79
+ // A shape made before the throw would react to every entity type.
80
+ if (typeof id === "number" && id >= 0)
81
+ try {
82
+ DeleteColshape(id);
83
+ } catch {
84
+ // gone already
85
+ }
86
+ return null;
87
+ }
88
+ }
89
+
90
+ /** Deletes a colshape (nothing when it is gone). No exit event follows: the owner handles its own state. */
91
+ export function deleteColshape(id: number): void {
92
+ if (hasColshapes() && DoesColshapeExist(id)) DeleteColshape(id);
93
+ }
94
+
95
+ type ColshapeHandler = (entity: number, inside: boolean) => void;
96
+ const handlers = new Map<number, ColshapeHandler>();
97
+ let listening = false;
98
+
99
+ function dispatch(entity: number, id: number, inside: boolean): void {
100
+ const handler = handlers.get(id);
101
+ if (!handler) return;
102
+ try {
103
+ handler(entity, inside);
104
+ } catch (error) {
105
+ log.error("colshape handler failed", error);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Enter (`inside` true) and exit of one colshape, through one listener per resource. Every resource that listens
111
+ * receives every colshape event of every resource (and, on the client, every player's ped crossing them), so only one
112
+ * place per side should listen for many shapes. Returns the unsubscribe.
113
+ */
114
+ export function onColshape(id: number, handler: ColshapeHandler): () => void {
115
+ if (!listening) {
116
+ listening = true;
117
+ on("onColshapeEnter", (entity: number, shape: number) =>
118
+ dispatch(entity, shape, true),
119
+ );
120
+ on("onColshapeExit", (entity: number, shape: number) =>
121
+ dispatch(entity, shape, false),
122
+ );
123
+ }
124
+ handlers.set(id, handler);
125
+ return () => {
126
+ if (handlers.get(id) === handler) handlers.delete(id);
127
+ };
128
+ }