@aifivem/lib 0.8.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.8.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.7.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
+ }
@@ -95,6 +95,12 @@ export {
95
95
  resourceExport,
96
96
  } from "../fivem/exports";
97
97
  export { createLocale, loadLocaleTexts, LOCALE_CONVAR } from "../fivem/locale";
98
+ export {
99
+ createColshape,
100
+ deleteColshape,
101
+ hasColshapes,
102
+ onColshape,
103
+ } from "../fivem/colshape";
98
104
  export { EntityState } from "../fivem/state/entityState";
99
105
  export { GlobalGroup, GlobalKey } from "../fivem/state/globalState";
100
106
  export { PlayerState } from "../fivem/state/playerState";
@@ -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
+ }
@@ -0,0 +1,21 @@
1
+ import {
2
+ applyVehicleDamage,
3
+ readVehicleDamage,
4
+ repairVehicle,
5
+ restoreVehicleDamage,
6
+ setVehicleEngineHealth,
7
+ } from "./vehicle";
8
+
9
+ /**
10
+ * Server features only FiveM for GTAV Enhanced has (patch notes and native docs, `aicore-fivem` skill
11
+ * `references/enhanced.md`). Each feature is probed; without it every helper answers null / false and the caller
12
+ * keeps its own path. Scripts never call these natives by hash themselves. (Colshapes are on Legacy too:
13
+ * `createColshape` in the fivem layer.)
14
+ */
15
+ export const enhanced = {
16
+ readVehicleDamage,
17
+ applyVehicleDamage,
18
+ restoreVehicleDamage,
19
+ repairVehicle,
20
+ setVehicleEngineHealth,
21
+ };
@@ -0,0 +1,80 @@
1
+ import { createLogger, VEHICLE_DAMAGE_MAX } from "../../shared";
2
+
3
+ export const log = createLogger(GetCurrentResourceName());
4
+
5
+ /**
6
+ * Hashes of the FiveM for GTAV Enhanced server natives that are in neither @citizenfx/server nor Legacy's wrappers
7
+ * (joaat of the upper-case name, from the native docs; `aicore-fivem` skill `references/enhanced.md`).
8
+ */
9
+ export const HASH = {
10
+ isWrecked: "0xA067F5AD", // IS_VEHICLE_WRECKED(Vehicle) -> BOOL
11
+ wheels: "0xEDF4B0FC", // GET_VEHICLE_NUMBER_OF_WHEELS(Vehicle) -> int (owner reported)
12
+ wheelOff: "0xCF1BC668", // IS_VEHICLE_WHEEL_BROKEN_OFF(Vehicle, int wheel) -> BOOL
13
+ breakWheel: "0xA274CADB", // BREAK_OFF_VEHICLE_WHEEL(Vehicle, int wheel, BOOL, BOOL, BOOL, BOOL)
14
+ allWindows: "0xBB619744", // ARE_ALL_VEHICLE_WINDOWS_INTACT(Vehicle) -> BOOL
15
+ smashWindow: "0xDDD9A8C2", // SMASH_VEHICLE_WINDOW(Vehicle, int window)
16
+ lightBroken: "0x7AFC9DF5", // IS_VEHICLE_LIGHT_BROKEN(Vehicle, int light) -> BOOL
17
+ breakLight: "0x611A3234", // SET_VEHICLE_LIGHT_BROKEN(Vehicle, int light, BOOL broken)
18
+ bumper: "0x67C9FAA3", // GET_VEHICLE_BUMPER_STATE(Vehicle, BOOL front) -> int
19
+ setBumper: "0x4716182C", // SET_VEHICLE_BUMPER_STATE(Vehicle, BOOL front, int state)
20
+ burstTyre: "0x89D28068", // SET_VEHICLE_TYRE_BURST(Vehicle, int wheel, BOOL onRim, float damage)
21
+ fixTyre: "0xA42EFA6B", // SET_VEHICLE_TYRE_FIXED(Vehicle, int wheel)
22
+ tank: "0x660A3692", // SET_VEHICLE_PETROL_TANK_HEALTH(Vehicle, float)
23
+ engine: "0x1B760FB5", // SET_VEHICLE_ENGINE_HEALTH(Vehicle, float)
24
+ fixed: "0x17469AA1", // SET_VEHICLE_FIXED(Vehicle): RPC to the owner client
25
+ deformationFixed: "0xDD2920C8", // SET_VEHICLE_DEFORMATION_FIXED(Vehicle): RPC to the owner client
26
+ } as const;
27
+
28
+ type Arg = number | boolean;
29
+
30
+ /** FiveM's own wrappers pass floats like this: an integral number would arrive as an int. */
31
+ export const float = (v: number): number => (v === 0 ? v : v + 0.0000001);
32
+ /** A native answering BOOL, read as truthy: JS gets `1` / `0`, never `true` (`aicore-fivem` `engine.md`). */
33
+ export const bool = (hash: string, ...args: Arg[]): boolean =>
34
+ Boolean(Citizen.invokeNative(hash, ...args, Citizen.returnResultAnyway()));
35
+ /** A native answering int. */
36
+ export const int = (hash: string, ...args: Arg[]): unknown =>
37
+ Citizen.invokeNative(
38
+ hash,
39
+ ...args,
40
+ Citizen.returnResultAnyway(),
41
+ Citizen.resultAsInteger(),
42
+ );
43
+ /** A native answering nothing. */
44
+ export const call = (hash: string, ...args: Arg[]): void =>
45
+ Citizen.invokeNative(hash, ...args);
46
+
47
+ /** Runs one setter; a failure is logged and the next setter still runs. */
48
+ export function attempt(name: string, fn: () => void): void {
49
+ try {
50
+ fn();
51
+ } catch (error) {
52
+ log.error(`enhanced native ${name} failed`, error);
53
+ }
54
+ }
55
+
56
+ let vehicleNatives: boolean | undefined;
57
+ /**
58
+ * The b177 server vehicle natives: a server without them throws on the unknown hash (ai-voice's probe works the same
59
+ * way). A "no" is kept only when probed on a vehicle a client owns, so a fresh entity without data cannot switch the
60
+ * feature off for good.
61
+ */
62
+ export function hasVehicleNatives(vehicle: number): boolean {
63
+ if (vehicleNatives === undefined && DoesEntityExist(vehicle)) {
64
+ try {
65
+ bool(HASH.isWrecked, vehicle);
66
+ vehicleNatives = true;
67
+ } catch {
68
+ if (NetworkGetEntityOwner(vehicle) > 0) vehicleNatives = false;
69
+ }
70
+ }
71
+ return vehicleNatives === true;
72
+ }
73
+
74
+ /** Synced wheel count, 0 while unknown (no owner client has sent the vehicle's data yet). */
75
+ export function wheelCount(vehicle: number): number {
76
+ const n = int(HASH.wheels, vehicle);
77
+ return typeof n === "number" && Number.isInteger(n)
78
+ ? Math.min(VEHICLE_DAMAGE_MAX.wheel + 1, Math.max(0, n))
79
+ : 0;
80
+ }
@@ -0,0 +1,177 @@
1
+ import {
2
+ readBumperState,
3
+ VEHICLE_DAMAGE_MAX,
4
+ waitFor,
5
+ type VehicleDamage,
6
+ } from "../../shared";
7
+ import {
8
+ attempt,
9
+ bool,
10
+ call,
11
+ float,
12
+ HASH,
13
+ hasVehicleNatives,
14
+ int,
15
+ log,
16
+ wheelCount,
17
+ } from "./natives";
18
+
19
+ /** Lowest petrol tank health restored: a tank at or below 0 can burn the car at a garage spot. */
20
+ const TANK_FLOOR = 100;
21
+
22
+ let readFailed = false;
23
+
24
+ /**
25
+ * A per-wheel native that may refuse an index. Tyre and wheel indexes are GTA's (0 LF, 1 RF, 2 LM, 3 RM, 4 LR, 5 RR,
26
+ * ...: a car's rear tyres are 4 and 5) or the synced wheel order; the docs do not say which, so every index up to
27
+ * `VEHICLE_DAMAGE_MAX.wheel` is walked and a refused one counts as intact.
28
+ */
29
+ function wheelSafe(fn: () => unknown): boolean {
30
+ try {
31
+ return Boolean(fn());
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The damage of a vehicle a client owns and has synced (windows, tyres, wheels, lights, bumpers, petrol tank), read on
39
+ * the server. Null on Legacy, before the owner's first sync (the server's vehicle data is empty then) or when a native
40
+ * fails (logged once): the caller keeps what it had.
41
+ */
42
+ export function readVehicleDamage(vehicle: number): VehicleDamage | null {
43
+ if (
44
+ !DoesEntityExist(vehicle) ||
45
+ NetworkGetEntityOwner(vehicle) <= 0 ||
46
+ !hasVehicleNatives(vehicle)
47
+ )
48
+ return null;
49
+ try {
50
+ // 0 until the owner's first sync: nothing to read yet.
51
+ if (wheelCount(vehicle) === 0) return null;
52
+ const windows: number[] = [];
53
+ if (!bool(HASH.allWindows, vehicle))
54
+ for (let i = 0; i <= VEHICLE_DAMAGE_MAX.window; i++)
55
+ if (!IsVehicleWindowIntact(vehicle, i)) windows.push(i);
56
+ const tyres: Array<[number, boolean]> = [];
57
+ const wheelsOff: number[] = [];
58
+ for (let i = 0; i <= VEHICLE_DAMAGE_MAX.wheel; i++) {
59
+ if (wheelSafe(() => bool(HASH.wheelOff, vehicle, i))) wheelsOff.push(i);
60
+ else if (wheelSafe(() => IsVehicleTyreBurst(vehicle, i, false)))
61
+ tyres.push([i, wheelSafe(() => IsVehicleTyreBurst(vehicle, i, true))]);
62
+ }
63
+ const lights: number[] = [];
64
+ for (let i = 0; i <= VEHICLE_DAMAGE_MAX.light; i++)
65
+ if (bool(HASH.lightBroken, vehicle, i)) lights.push(i);
66
+ const tank = GetVehiclePetrolTankHealth(vehicle);
67
+ return {
68
+ v: 1,
69
+ windows,
70
+ tyres,
71
+ wheelsOff,
72
+ lights,
73
+ bumpers: [
74
+ readBumperState(int(HASH.bumper, vehicle, true)) ?? 0,
75
+ readBumperState(int(HASH.bumper, vehicle, false)) ?? 0,
76
+ ],
77
+ tank: Number.isFinite(tank) ? tank : 1000,
78
+ };
79
+ } catch (error) {
80
+ if (!readFailed) log.error("enhanced vehicle damage read failed", error);
81
+ readFailed = true;
82
+ return null;
83
+ }
84
+ }
85
+
86
+ /** Writes stored damage to the synced vehicle data; false on Legacy. */
87
+ export function applyVehicleDamage(
88
+ vehicle: number,
89
+ damage: VehicleDamage,
90
+ ): boolean {
91
+ if (!DoesEntityExist(vehicle) || !hasVehicleNatives(vehicle)) return false;
92
+ for (const i of damage.windows)
93
+ attempt("SMASH_VEHICLE_WINDOW", () => call(HASH.smashWindow, vehicle, i));
94
+ for (const i of damage.wheelsOff)
95
+ attempt("BREAK_OFF_VEHICLE_WHEEL", () =>
96
+ call(HASH.breakWheel, vehicle, i, false, true, false, false),
97
+ );
98
+ for (const [i, onRim] of damage.tyres)
99
+ attempt("SET_VEHICLE_TYRE_BURST", () =>
100
+ call(HASH.burstTyre, vehicle, i, onRim, float(1000)),
101
+ );
102
+ for (const i of damage.lights)
103
+ attempt("SET_VEHICLE_LIGHT_BROKEN", () =>
104
+ call(HASH.breakLight, vehicle, i, true),
105
+ );
106
+ damage.bumpers.forEach((state, i) => {
107
+ if (state > 0)
108
+ attempt("SET_VEHICLE_BUMPER_STATE", () =>
109
+ call(HASH.setBumper, vehicle, i === 0, state),
110
+ );
111
+ });
112
+ if (damage.tank < 1000)
113
+ attempt("SET_VEHICLE_PETROL_TANK_HEALTH", () =>
114
+ call(HASH.tank, vehicle, float(Math.max(TANK_FLOOR, damage.tank))),
115
+ );
116
+ return true;
117
+ }
118
+
119
+ /**
120
+ * Restores stored damage on a new entity once its owner client has synced it (a write before that is overwritten
121
+ * by the client's first sync); gives up after 10 s, when the entity is gone or when `same()` says the handle is no
122
+ * longer that vehicle. Resolves whether it was applied (false on Legacy).
123
+ */
124
+ export async function restoreVehicleDamage(
125
+ vehicle: number,
126
+ damage: VehicleDamage,
127
+ same: () => boolean = () => true,
128
+ ): Promise<boolean> {
129
+ const until = (ready: () => boolean): Promise<boolean> =>
130
+ waitFor(
131
+ () =>
132
+ !DoesEntityExist(vehicle) || !same() ? false : ready() || undefined,
133
+ 10_000,
134
+ 250,
135
+ ).catch(() => false);
136
+ // The probe runs on an owned vehicle, like every read.
137
+ if (!(await until(() => NetworkGetEntityOwner(vehicle) > 0))) return false;
138
+ if (!hasVehicleNatives(vehicle)) return false;
139
+ if (!(await until(() => wheelCount(vehicle) > 0))) return false;
140
+ return applyVehicleDamage(vehicle, damage);
141
+ }
142
+
143
+ /**
144
+ * A full repair from the server: deformation, windows, lights, bumpers, tyres, engine, body and petrol tank. The
145
+ * health values are written to the synced data (no owner client needed); `SET_VEHICLE_FIXED` and the deformation go
146
+ * to the owner client. False on Legacy.
147
+ */
148
+ export function repairVehicle(vehicle: number): boolean {
149
+ if (!DoesEntityExist(vehicle) || !hasVehicleNatives(vehicle)) return false;
150
+ attempt("SET_VEHICLE_FIXED", () => call(HASH.fixed, vehicle));
151
+ attempt("SET_VEHICLE_DEFORMATION_FIXED", () =>
152
+ call(HASH.deformationFixed, vehicle),
153
+ );
154
+ attempt("SET_VEHICLE_ENGINE_HEALTH", () =>
155
+ call(HASH.engine, vehicle, float(1000)),
156
+ );
157
+ attempt("SET_VEHICLE_PETROL_TANK_HEALTH", () =>
158
+ call(HASH.tank, vehicle, float(1000)),
159
+ );
160
+ attempt("SET_VEHICLE_BODY_HEALTH", () => SetVehicleBodyHealth(vehicle, 1000));
161
+ // Every index (see `wheelSafe`); SET_VEHICLE_FIXED repairs them on the owner client too.
162
+ for (let i = 0; i <= VEHICLE_DAMAGE_MAX.wheel; i++)
163
+ wheelSafe(() => call(HASH.fixTyre, vehicle, i));
164
+ return true;
165
+ }
166
+
167
+ /** Engine health written to the synced data from the server (no owner client needed); false on Legacy. */
168
+ export function setVehicleEngineHealth(
169
+ vehicle: number,
170
+ health: number,
171
+ ): boolean {
172
+ if (!DoesEntityExist(vehicle) || !hasVehicleNatives(vehicle)) return false;
173
+ attempt("SET_VEHICLE_ENGINE_HEALTH", () =>
174
+ call(HASH.engine, vehicle, float(health)),
175
+ );
176
+ return true;
177
+ }
@@ -165,3 +165,11 @@ export { characters } from "./characters";
165
165
  export { illegal } from "./illegal";
166
166
  export { bans } from "./bans";
167
167
  export { isPrimeTime } from "./primeTime";
168
+ export { enhanced } from "./enhanced/enhanced";
169
+ export {
170
+ createColshape,
171
+ deleteColshape,
172
+ hasColshapes,
173
+ onColshape,
174
+ } from "../fivem/colshape";
175
+ export { vehicleCondition, type VehicleCondition } from "./vehicle/condition";
@@ -0,0 +1,25 @@
1
+ import type { VehicleDamage } from "../../shared";
2
+ import { readVehicleDamage } from "../enhanced/vehicle";
3
+ import { fuel } from "../fuel";
4
+
5
+ /** A vehicle's condition read on the server, in ai-vehicles' `SaveVehicle` shape. */
6
+ export interface VehicleCondition {
7
+ engine: number;
8
+ body: number;
9
+ /** Through ai-core's fuel layer (any fuel script); left out when unknown. */
10
+ fuel?: number;
11
+ /** Windows, tyres, lights, bumpers, tank: FiveM for GTAV Enhanced only, and only while a client owns the vehicle. */
12
+ damage?: VehicleDamage;
13
+ }
14
+
15
+ /** The condition to store with an owned vehicle that leaves the world (parked, impounded, listed, cleaned up). */
16
+ export function vehicleCondition(vehicle: number): VehicleCondition {
17
+ const level = fuel.get(vehicle);
18
+ const damage = readVehicleDamage(vehicle);
19
+ return {
20
+ engine: GetVehicleEngineHealth(vehicle),
21
+ body: GetVehicleBodyHealth(vehicle),
22
+ ...(level !== null ? { fuel: level } : {}),
23
+ ...(damage ? { damage } : {}),
24
+ };
25
+ }
@@ -1,5 +1,11 @@
1
1
  import { VEHICLE_BAGS, type KeyPurpose } from "@aifivem/shared";
2
- import { waitFor, type VehicleProps, type VehicleSetup } from "../../shared";
2
+ import {
3
+ waitFor,
4
+ type VehicleDamage,
5
+ type VehicleProps,
6
+ type VehicleSetup,
7
+ } from "../../shared";
8
+ import { restoreVehicleDamage } from "../enhanced/vehicle";
3
9
  import { fuel } from "../fuel";
4
10
  import { vehicleKeys } from "../vehicleKeys";
5
11
  import { randomPlate } from "./plate";
@@ -28,6 +34,8 @@ export interface SpawnVehicleOptions {
28
34
  props?: VehicleProps;
29
35
  /** Fresh-vehicle extras: full tuning, colours, livery, tint, dirt, engine running. */
30
36
  setup?: VehicleSetup;
37
+ /** Stored damage (windows, tyres, lights...), restored once a client owns the vehicle; FiveM for GTAV Enhanced only. */
38
+ damage?: VehicleDamage;
31
39
  /** Doors locked for everyone (keys unlock them). */
32
40
  locked?: boolean;
33
41
  /** Routing bucket the vehicle lives in (players put in it should be in the same one). */
@@ -60,7 +68,7 @@ async function seatPlayer(
60
68
 
61
69
  /**
62
70
  * Creates a networked vehicle on the server (strict entity lockdown) and sets it up in one step: plate, fuel, state
63
- * bags, look (props / setup), lock, bucket, keys for its purpose, a driver and passengers. Resolves the entity, or null when the model does not exist or creation failed.
71
+ * bags, look (props / setup), damage (Enhanced), lock, bucket, keys for its purpose, a driver and passengers. Resolves the entity, or null when the model does not exist or creation failed.
64
72
  */
65
73
  export async function spawnVehicle(
66
74
  options: SpawnVehicleOptions,
@@ -100,6 +108,16 @@ export async function spawnVehicle(
100
108
  if (options.setup) state.set(VEHICLE_BAGS.setup, options.setup, true);
101
109
  for (const [key, value] of Object.entries(options.bags ?? {}))
102
110
  state.set(key, value, true);
111
+ // Not awaited: it waits for the first owner client (nothing happens on Legacy).
112
+ if (options.damage) {
113
+ const model = GetEntityModel(vehicle);
114
+ // A handle freed and reused within the wait must not get this damage.
115
+ void restoreVehicleDamage(
116
+ vehicle,
117
+ options.damage,
118
+ () => GetEntityModel(vehicle) === model,
119
+ );
120
+ }
103
121
  if (options.keysTo !== undefined) {
104
122
  const synced = await waitFor(
105
123
  () =>
@@ -1,5 +1,7 @@
1
1
  /** Helpers usable on client and server. No FiveM natives here. */
2
2
 
3
+ import { isRecord } from "./record";
4
+
3
5
  export { sleep, waitFor } from "./wait";
4
6
  export { bool, int, num, record, str, vec4, type Vec4 } from "./read";
5
7
  export {
@@ -12,13 +14,7 @@ export {
12
14
  readVec4,
13
15
  } from "./strict";
14
16
  export { fail, isActionOk, replyError, type ActionResult } from "./action";
15
- export {
16
- distance,
17
- flatDistance,
18
- headingTo,
19
- nearestOf,
20
- type Vec3,
21
- } from "./vec";
17
+ export { distance, flatDistance, headingTo, nearestOf, type Vec3 } from "./vec";
22
18
  export { pickRandom, randomInt, rollChance } from "./random";
23
19
  export { ServerClock } from "./clock";
24
20
  export {
@@ -36,11 +32,7 @@ export {
36
32
  readAccess,
37
33
  type AccessRule,
38
34
  } from "./access";
39
- export {
40
- BLIP_STYLE_FIELDS,
41
- readBlipStyle,
42
- type BlipStyle,
43
- } from "./blipStyle";
35
+ export { BLIP_STYLE_FIELDS, readBlipStyle, type BlipStyle } from "./blipStyle";
44
36
  export {
45
37
  polyFromCorners,
46
38
  readZoneShape,
@@ -63,10 +55,14 @@ export {
63
55
  type VehicleProps,
64
56
  type VehicleSetup,
65
57
  } from "./vehicleProps";
58
+ export {
59
+ readBumperState,
60
+ toVehicleDamage,
61
+ VEHICLE_DAMAGE_MAX,
62
+ type VehicleDamage,
63
+ } from "./vehicleDamage";
66
64
 
67
- export function isRecord(value: unknown): value is Record<string, unknown> {
68
- return typeof value === "object" && value !== null && !Array.isArray(value);
69
- }
65
+ export { isRecord };
70
66
 
71
67
  /** Client text made safe for the server console: one line, no control characters, no `^n` colour codes. */
72
68
  export function logSafe(text: string, max: number): string {
@@ -1,7 +1,6 @@
1
1
  import type { DataSpec, WidgetSpec } from "@aifivem/shared";
2
2
 
3
- const isRecord = (v: unknown): v is Record<string, unknown> =>
4
- typeof v === "object" && v !== null && !Array.isArray(v);
3
+ import { isRecord } from "./record";
5
4
 
6
5
  /** An NPC standing at a place (a shopkeeper, a clerk): its model, an optional idle scenario and where it stands. */
7
6
  export interface PlacePed {
@@ -0,0 +1,4 @@
1
+ /** A plain object (not null, not an array). */
2
+ export function isRecord(value: unknown): value is Record<string, unknown> {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
@@ -0,0 +1,84 @@
1
+ import { isRecord } from "./record";
2
+
3
+ /**
4
+ * A vehicle's damage beyond engine and body health, as plain data: read and restored by the server on FiveM for GTAV
5
+ * Enhanced (lib server `enhanced`). Stored JSON carries `v: 1`.
6
+ */
7
+ export interface VehicleDamage {
8
+ v: 1;
9
+ /** Smashed windows: 0 front left, 1 front right, 2 rear left, 3 rear right, 4 middle left, 5 middle right, 6 windscreen, 7 rear windscreen. */
10
+ windows: number[];
11
+ /** Burst tyres by synced wheel index, `true` when it runs on the rim. */
12
+ tyres: Array<[wheel: number, onRim: boolean]>;
13
+ /** Broken off wheels by synced wheel index. */
14
+ wheelsOff: number[];
15
+ /** Broken lights, 0-21 (`SET_VEHICLE_LIGHT_BROKEN`: headlights 0-1, taillights 2-3, indicators 4-7, ...). */
16
+ lights: number[];
17
+ /** Front and rear bumper: 0 intact, 1 hanging loose, 2 broken off. */
18
+ bumpers: [front: number, rear: number];
19
+ /** Petrol tank health, 1000 undamaged. */
20
+ tank: number;
21
+ }
22
+
23
+ /** Highest index kept of each part: the server reader walks the same ranges. */
24
+ export const VEHICLE_DAMAGE_MAX = {
25
+ window: 7,
26
+ light: 21,
27
+ /** Synced wheel index (a vehicle has at most 10 wheels). */
28
+ wheel: 15,
29
+ } as const;
30
+ const MAX_WHEEL = VEHICLE_DAMAGE_MAX.wheel;
31
+
32
+ const indexes = (v: unknown, max: number): number[] | null =>
33
+ Array.isArray(v) &&
34
+ v.length <= max + 1 &&
35
+ v.every((x) => Number.isInteger(x) && x >= 0 && x <= max)
36
+ ? [...new Set(v as number[])]
37
+ : null;
38
+
39
+ /** A bumper state (0 intact, 1 loose, 2 off), null when it is not one. */
40
+ export const readBumperState = (v: unknown): number | null =>
41
+ v === 0 || v === 1 || v === 2 ? v : null;
42
+
43
+ /** Stored damage, checked; null when the shape is not ours. */
44
+ export function toVehicleDamage(v: unknown): VehicleDamage | null {
45
+ if (!isRecord(v) || v.v !== 1) return null;
46
+ const windows = indexes(v.windows, VEHICLE_DAMAGE_MAX.window);
47
+ const wheelsOff = indexes(v.wheelsOff, MAX_WHEEL);
48
+ const lights = indexes(v.lights, VEHICLE_DAMAGE_MAX.light);
49
+ const front = Array.isArray(v.bumpers) ? readBumperState(v.bumpers[0]) : null;
50
+ const rear = Array.isArray(v.bumpers) ? readBumperState(v.bumpers[1]) : null;
51
+ if (
52
+ !windows ||
53
+ !wheelsOff ||
54
+ !lights ||
55
+ front === null ||
56
+ rear === null ||
57
+ typeof v.tank !== "number" ||
58
+ !Number.isFinite(v.tank) ||
59
+ !Array.isArray(v.tyres) ||
60
+ v.tyres.length > MAX_WHEEL + 1
61
+ )
62
+ return null;
63
+ const tyres: Array<[number, boolean]> = [];
64
+ for (const t of v.tyres) {
65
+ if (
66
+ !Array.isArray(t) ||
67
+ !Number.isInteger(t[0]) ||
68
+ t[0] < 0 ||
69
+ t[0] > MAX_WHEEL ||
70
+ typeof t[1] !== "boolean"
71
+ )
72
+ return null;
73
+ tyres.push([t[0] as number, t[1]]);
74
+ }
75
+ return {
76
+ v: 1,
77
+ windows,
78
+ tyres,
79
+ wheelsOff,
80
+ lights,
81
+ bumpers: [front, rear],
82
+ tank: Math.min(1000, Math.max(-1000, v.tank)),
83
+ };
84
+ }
@@ -1,3 +1,4 @@
1
+ import { isRecord } from "./record";
1
2
  /**
2
3
  * A vehicle's look and tuning as plain data (colours, mods, extras, livery, wheels, neon, tint, plate), read from and
3
4
  * written to an entity. Stored JSON carries `v: 1`.
@@ -26,8 +27,6 @@ export interface VehicleProps {
26
27
  bodyHealth: number;
27
28
  }
28
29
 
29
- const isObj = (v: unknown): v is Record<string, unknown> =>
30
- typeof v === "object" && v !== null && !Array.isArray(v);
31
30
  const nums = (v: unknown, n: number): number[] | null =>
32
31
  Array.isArray(v) && v.length === n && v.every((x) => typeof x === "number")
33
32
  ? v
@@ -36,7 +35,7 @@ const nums = (v: unknown, n: number): number[] | null =>
36
35
  /** Stored or received props, checked; null when the shape is not ours. */
37
36
  export function toVehicleProps(v: unknown): VehicleProps | null {
38
37
  if (
39
- !isObj(v) ||
38
+ !isRecord(v) ||
40
39
  v.v !== 1 ||
41
40
  typeof v.model !== "number" ||
42
41
  typeof v.plate !== "string"
@@ -51,8 +50,8 @@ export function toVehicleProps(v: unknown): VehicleProps | null {
51
50
  !extraColors ||
52
51
  !neonColor ||
53
52
  !tyreSmoke ||
54
- !isObj(v.mods) ||
55
- !isObj(v.extras) ||
53
+ !isRecord(v.mods) ||
54
+ !isRecord(v.extras) ||
56
55
  !Array.isArray(v.neon)
57
56
  )
58
57
  return null;
@@ -124,7 +123,7 @@ const colorsOf = (v: unknown): [number, number] | undefined => {
124
123
 
125
124
  /** A received setup, checked field by field (wrong fields drop); null when it is not an object. */
126
125
  export function toVehicleSetup(v: unknown): VehicleSetup | null {
127
- if (!isObj(v)) return null;
126
+ if (!isRecord(v)) return null;
128
127
  return {
129
128
  maxed: v.maxed === true || undefined,
130
129
  colors: colorsOf(v.colors),