-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathacc_shared_memory.py
More file actions
644 lines (600 loc) · 22.3 KB
/
Copy pathacc_shared_memory.py
File metadata and controls
644 lines (600 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
"""
ACC Shared Memory reader (Windows only) — v2 ctypes edition.
Uses ctypes.Structure so that field offsets are computed automatically by the
C-ABI layout rules, exactly matching the official ACC SDK headers.
Named pages:
Local\\acpmf_physics → SPageFilePhysics
Local\\acpmf_graphics → SPageFileGraphics
Local\\acpmf_static → SPageFileStatic
Only the fields needed by acc_bridge.py are extracted.
"""
from __future__ import annotations
import ctypes
import mmap
import struct
from dataclasses import dataclass
from typing import Optional, Tuple
# ── ctypes helpers ────────────────────────────────────────────────────────
def _f4(): return ctypes.c_float * 4
def _f3(): return ctypes.c_float * 3
def _f5(): return ctypes.c_float * 5
def _f60(): return (ctypes.c_float * 3) * 60
def _i60(): return ctypes.c_int32 * 60
def _w(n): return ctypes.c_wchar * n # wchar_t — 2 bytes each on Windows
# Concrete array types used in struct fields
_Float3 = ctypes.c_float * 3
_Float4 = ctypes.c_float * 4
_Float5 = ctypes.c_float * 5
_Float12 = ctypes.c_float * 12 # 4 wheels × Vector3f
# ─── SPageFilePhysics ─────────────────────────────────────────────────────
# Follows the official ACC SDK header (shared_memory_v1.x).
# Unused-in-ACC fields are still declared so offsets stay correct.
class _Physics(ctypes.Structure):
_pack_ = 4
_fields_ = [
# offset 0
("packetId", ctypes.c_int32),
# 4
("gas", ctypes.c_float),
# 8
("brake", ctypes.c_float),
# 12
("fuel", ctypes.c_float),
# 16
("gear", ctypes.c_int32),
# 20
("rpms", ctypes.c_int32),
# 24
("steerAngle", ctypes.c_float),
# 28
("speedKmh", ctypes.c_float),
# 32
("velocity", _Float3),
# 44
("accG", _Float3),
# 56
("wheelSlip", _Float4),
# 72 (unused)
("wheelLoad", _Float4),
# 88
("wheelsPressure", _Float4),
# 104
("wheelAngularSpeed", _Float4),
# 120 (unused)
("tyreWear", _Float4),
# 136 (unused)
("tyreDirtyLevel", _Float4),
# 152
("tyreCoreTemperature", _Float4),
# 168 (unused)
("camberRAD", _Float4),
# 184
("suspensionTravel", _Float4),
# 200 (unused)
("drs", ctypes.c_float),
# 204 ← TC as float (0/1 activation, NOT the setup-level integer)
("tc", ctypes.c_float),
# 208
("heading", ctypes.c_float),
# 212
("pitch", ctypes.c_float),
# 216
("roll", ctypes.c_float),
# 220 (unused)
("cgHeight", ctypes.c_float),
# 224
("carDamage", _Float5),
# 244 (unused)
("numberOfTyresOut", ctypes.c_int32),
# 248
("pitLimiterOn", ctypes.c_int32),
# 252 ← ABS as float (0/1 activation, NOT setup-level)
("abs", ctypes.c_float),
# 256 (unused)
("kersCharge", ctypes.c_float),
# 260 (unused)
("kersInput", ctypes.c_float),
# 264
("autoShifterOn", ctypes.c_int32),
# 268 (unused)
("rideHeight", ctypes.c_float * 2),
# 276
("turboBoost", ctypes.c_float),
# 280 (unused)
("ballast", ctypes.c_float),
# 284 (unused)
("airDensity", ctypes.c_float),
# 288
("airTemp", ctypes.c_float),
# 292
("roadTemp", ctypes.c_float),
# 296
("localAngularVel", _Float3),
# 308
("finalFF", ctypes.c_float),
# 312 (unused)
("performanceMeter", ctypes.c_float),
# 316 (unused)
("engineBrake", ctypes.c_int32),
# 320 (unused)
("ersRecoveryLevel", ctypes.c_int32),
# 324 (unused)
("ersPowerLevel", ctypes.c_int32),
# 328 (unused)
("ersHeatCharging", ctypes.c_int32),
# 332 (unused)
("ersIsCharging", ctypes.c_int32),
# 336 (unused)
("kersCurrentKJ", ctypes.c_float),
# 340 (unused)
("drsAvailable", ctypes.c_int32),
# 344 (unused)
("drsEnabled", ctypes.c_int32),
# 348
("brakeTemp", _Float4),
# 364
("clutch", ctypes.c_float),
# 368 (unused)
("tyreTempI", _Float4),
# 384 (unused)
("tyreTempM", _Float4),
# 400 (unused)
("tyreTempO", _Float4),
# 416 (unused)
("isAIControlled", ctypes.c_int32),
# 420 (unused — contact point arrays: 4 wheels × Vector3f = 12 floats each)
("tyreContactPoint", _Float12),
# 468 (unused)
("tyreContactNormal", _Float12),
# 516 (unused)
("tyreContactHeading", _Float12),
# 564
("brakeBias", ctypes.c_float),
# 568
("localVelocity", _Float3),
# 580 (unused)
("P2PActivation", ctypes.c_int32),
# 584 (unused)
("P2PStatus", ctypes.c_int32),
# 588 (unused)
("currentMaxRpm", ctypes.c_float),
# 592 (unused)
("mz", _Float4),
# 608 (unused)
("fx", _Float4),
# 624 (unused)
("fy", _Float4),
# 640
("slipRatio", _Float4),
# 656
("slipAngle", _Float4),
# 672 (unused)
("tcInAction", ctypes.c_int32),
# 676 (unused)
("tcCutAction", ctypes.c_int32),
# 680 (unused)
("absInAction", ctypes.c_int32),
# 684 (unused)
("suspensionDamage", _Float4),
# 700 (unused)
("tyreTemp", _Float4),
# 716
("waterTemp", ctypes.c_float),
# 720
("brakePressure", _Float4),
# 736
("frontBrakeCompound", ctypes.c_int32),
# 740
("rearBrakeCompound", ctypes.c_int32),
# 744
("padLife", _Float4),
# 760
("discLife", _Float4),
# 776
("ignitionOn", ctypes.c_int32),
# 780
("starterEngineOn", ctypes.c_int32),
# 784
("isEngineRunning", ctypes.c_int32),
# 788
("kerbVibrations", ctypes.c_float),
# 792
("slipVibrations", ctypes.c_float),
# 796
("gVibrations", ctypes.c_float),
# 800
("absVibrations", ctypes.c_float),
]
# Helper alias so we can write _f3 * 4 in the field definition above
_f3 = _f3 # already defined as function — use () in _fields_
# ─── SPageFileGraphics ────────────────────────────────────────────────────
# Graphics contains the *setup* ABS/TC/EngineMap integers (what the player
# selected in the garage menu), surface grip, flags, lap times, etc.
class _Graphics(ctypes.Structure):
_pack_ = 4
_fields_ = [
# 0
("packetId", ctypes.c_int32),
# 4
("status", ctypes.c_int32),
# 8
("session", ctypes.c_int32),
# 12 — wchar_t[15] = 30 bytes each
("currentTime", _w(15)),
# 42
("lastTime", _w(15)),
# 72
("bestTime", _w(15)),
# 102
("split", _w(15)),
# 132
("completedLaps", ctypes.c_int32),
# 136
("position", ctypes.c_int32),
# 140
("iCurrentTime", ctypes.c_int32),
# 144
("iLastTime", ctypes.c_int32),
# 148
("iBestTime", ctypes.c_int32),
# 152
("sessionTimeLeft", ctypes.c_float),
# 156
("distanceTraveled", ctypes.c_float),
# 160
("isInPit", ctypes.c_int32),
# 164
("currentSectorIndex", ctypes.c_int32),
# 168
("lastSectorTime", ctypes.c_int32),
# 172
("numberOfLaps", ctypes.c_int32),
# 176 — wchar_t[33] = 66 bytes
("tyreCompound", _w(33)),
# 242 — pad to align next int to 4
("_pad0", ctypes.c_int16),
# 244
("replayTimeMultiplier",ctypes.c_float),
# 248
("normalizedCarPosition",ctypes.c_float),
# 252
("activeCars", ctypes.c_int32),
# 256 — (float[3])[60] = 720 bytes
("carCoordinates", (ctypes.c_float * 3) * 60),
# 976
("carID", ctypes.c_int32 * 60),
# 1216
("playerCarID", ctypes.c_int32),
# 1220
("penaltyTime", ctypes.c_float),
# 1224
("flag", ctypes.c_int32),
# 1228
("penalty", ctypes.c_int32),
# 1232
("idealLineOn", ctypes.c_int32),
# 1236
("isInPitLane", ctypes.c_int32),
# 1240
("surfaceGrip", ctypes.c_float),
# 1244
("mandatoryPitDone", ctypes.c_int32),
# 1248
("windSpeed", ctypes.c_float),
# 1252
("windDirection", ctypes.c_float),
# 1256
("isSetupMenuVisible", ctypes.c_int32),
# 1260
("mainDisplayIndex", ctypes.c_int32),
# 1264
("secondaryDisplayIndex",ctypes.c_int32),
# 1268
("tc", ctypes.c_int32), # ← setup-level TC (1-12)
# 1272
("tcCut", ctypes.c_int32),
# 1276
("engineMap", ctypes.c_int32), # ← engine map (1-N)
# 1280
("abs", ctypes.c_int32), # ← setup-level ABS (1-12)
# 1284
("fuelXLap", ctypes.c_float),
# 1288
("rainLights", ctypes.c_int32),
# 1292
("flashingLights", ctypes.c_int32),
# 1296
("lightsStage", ctypes.c_int32),
# 1300
("exhaustTemperature", ctypes.c_float),
# 1304
("wiperLV", ctypes.c_int32),
# 1308
("driverStintTotalTimeLeft", ctypes.c_int32),
# 1312
("driverStintTimeLeft", ctypes.c_int32),
# 1316
("rainTyres", ctypes.c_int32),
# 1320
("sessionIndex", ctypes.c_int32),
# 1324
("usedFuel", ctypes.c_float),
# 1328 — wchar_t[15] = 30 bytes
("deltaLapTime", _w(15)),
# 1358
("iDeltaLapTime", ctypes.c_int32),
# 1362 — pad 2 bytes
("_pad1", ctypes.c_int16),
# 1364 — wchar_t[15] = 30 bytes
("estimatedLapTime", _w(15)),
# 1394
("iEstimatedLapTime", ctypes.c_int32),
# 1398
("isDeltaPositive", ctypes.c_int32),
# 1402
("iSplit", ctypes.c_int32),
# 1406
("isValidLap", ctypes.c_int32),
# 1410
("fuelEstimatedLaps", ctypes.c_float),
# 1414 — wchar_t[33] = 66 bytes
("trackStatus", _w(33)),
# 1480 — pad 2 bytes
("_pad2", ctypes.c_int16),
# 1482 — unused mfd fields
("mfdTyreSet", ctypes.c_int32),
# 1486
("mfdFuelToAdd", ctypes.c_float),
# 1490
("mfdTyrePressureLF", ctypes.c_float),
# 1494
("mfdTyrePressureRF", ctypes.c_float),
# 1498
("mfdTyrePressureLR", ctypes.c_float),
# 1502
("mfdTyrePressureRR", ctypes.c_float),
# 1506
("trackGripStatus", ctypes.c_int32),
# 1510
("rainIntensity", ctypes.c_int32),
# 1514
("rainIntensityIn10min",ctypes.c_int32),
# 1518
("rainIntensityIn30min",ctypes.c_int32),
# 1522
("currentTyreSet", ctypes.c_int32),
# 1526
("strategyTyreSet", ctypes.c_int32),
# 1530
("gapAhead", ctypes.c_int32),
# 1534
("gapBehind", ctypes.c_int32),
]
# ─── SPageFileStatic ──────────────────────────────────────────────────────
class _Static(ctypes.Structure):
_pack_ = 4
_fields_ = [
("smVersion", _w(15)),
("acVersion", _w(15)),
("numberOfSessions", ctypes.c_int32),
("numCars", ctypes.c_int32),
("carModel", _w(33)),
("_pad0", ctypes.c_int16),
("track", _w(33)),
("_pad1", ctypes.c_int16),
("playerName", _w(33)),
("_pad2", ctypes.c_int16),
("playerSurname", _w(33)),
("_pad3", ctypes.c_int16),
("playerNick", _w(33)),
("_pad4", ctypes.c_int16),
("sectorCount", ctypes.c_int32),
("maxTorque", ctypes.c_float),
("maxPower", ctypes.c_float),
("maxRpm", ctypes.c_int32),
("maxFuel", ctypes.c_float),
("suspensionMaxTravel", ctypes.c_float * 4),
("tyreRadius", ctypes.c_float * 4),
("maxTurboBoost", ctypes.c_float),
("deprecated1", ctypes.c_float),
("deprecated2", ctypes.c_float),
("penaltiesEnabled", ctypes.c_int32),
("aidFuelRate", ctypes.c_float),
("aidTireRate", ctypes.c_float),
("aidMechanicalDamage", ctypes.c_float),
("aidAllowTyreBlankets",ctypes.c_int32),
("aidStability", ctypes.c_float),
("aidAutoClutch", ctypes.c_int32),
("aidAutoBlip", ctypes.c_int32),
("hasDRS", ctypes.c_int32),
("hasERS", ctypes.c_int32),
("hasKERS", ctypes.c_int32),
("kersMaxJ", ctypes.c_float),
("engineBrakeSettingsCount", ctypes.c_int32),
("ersPowerControllerCount", ctypes.c_int32),
("trackSplineLength", ctypes.c_float),
("trackConfiguration", _w(33)),
("_pad5", ctypes.c_int16),
("ersMaxJ", ctypes.c_float),
("isTimedRace", ctypes.c_int32),
("hasExtraLap", ctypes.c_int32),
("carSkin", _w(33)),
("_pad6", ctypes.c_int16),
("reversedGridPositions", ctypes.c_int32),
("pitWindowStart", ctypes.c_int32),
("pitWindowEnd", ctypes.c_int32),
("isOnline", ctypes.c_int32),
("dryTyresName", _w(33)),
("_pad7", ctypes.c_int16),
("wetTyresName", _w(33)),
("_pad8", ctypes.c_int16),
]
# ─── Public dataclasses ───────────────────────────────────────────────────
@dataclass
class Physics:
packet_id: int
gas: float
brake: float
clutch: float
fuel: float
gear: int
rpms: int
speed_kmh: float
tyre_pressure: Tuple[float, ...]
tyre_core_temp: Tuple[float, ...]
brake_temp: Tuple[float, ...]
air_temp: float
road_temp: float
brake_bias: float # raw float ~0.54 = 54%
@dataclass
class Graphics:
packet_id: int
status: int
completed_laps: int
position: int
current_time_ms: int
last_time_ms: int
best_time_ms: int
flag: int
surface_grip: float # 0..1
tc: int # setup level (Graphics page)
abs: int # setup level (Graphics page)
engine_map: int # setup level (Graphics page)
stint_left_ms: int
delta_ms: int # signed ms
is_valid_lap: bool
fuel_estimated_laps: float
@dataclass
class StaticInfo:
max_rpm: int
max_fuel: float
# ─── Shared memory wrapper ────────────────────────────────────────────────
def _open_page(name: str, size: int) -> Optional[mmap.mmap]:
try:
return mmap.mmap(-1, size, name)
except OSError:
return None
def _read_struct(mm: mmap.mmap, cls):
"""Copy mmap bytes into a ctypes struct and return it."""
mm.seek(0)
buf = mm.read(ctypes.sizeof(cls))
obj = cls()
ctypes.memmove(ctypes.addressof(obj), buf, len(buf))
return obj
class ACCSharedMemory:
def __init__(self) -> None:
self._phy_mm: Optional[mmap.mmap] = None
self._gfx_mm: Optional[mmap.mmap] = None
self._sta_mm: Optional[mmap.mmap] = None
self.physics = None # kept for compatibility (None → not open)
self.graphics = None
def open(self) -> bool:
PHY_SZ = ctypes.sizeof(_Physics) + 256
GFX_SZ = ctypes.sizeof(_Graphics) + 256
STA_SZ = ctypes.sizeof(_Static) + 256
self._phy_mm = _open_page(r"Local\acpmf_physics", max(PHY_SZ, 4096))
self._gfx_mm = _open_page(r"Local\acpmf_graphics", max(GFX_SZ, 4096))
self._sta_mm = _open_page(r"Local\acpmf_static", max(STA_SZ, 4096))
self.physics = self._phy_mm # non-None → open indicator
self.graphics = self._gfx_mm
return self._phy_mm is not None and self._gfx_mm is not None
def close(self) -> None:
for m in (self._phy_mm, self._gfx_mm, self._sta_mm):
if m is not None:
try:
m.close()
except Exception:
pass
self._phy_mm = self._gfx_mm = self._sta_mm = None
self.physics = self.graphics = None
def is_live(self) -> bool:
if self._gfx_mm is None:
return False
g = _read_struct(self._gfx_mm, _Graphics)
return g.status == 2
def read_physics(self) -> Physics:
if self._phy_mm is None:
raise RuntimeError("physics page not opened")
p = _read_struct(self._phy_mm, _Physics)
return Physics(
packet_id = p.packetId,
gas = p.gas,
brake = p.brake,
clutch = p.clutch,
fuel = p.fuel,
gear = p.gear,
rpms = p.rpms,
speed_kmh = p.speedKmh,
tyre_pressure = tuple(p.wheelsPressure),
tyre_core_temp = tuple(p.tyreCoreTemperature),
brake_temp = tuple(p.brakeTemp),
air_temp = p.airTemp,
road_temp = p.roadTemp,
brake_bias = p.brakeBias,
)
def read_graphics(self) -> Graphics:
if self._gfx_mm is None:
raise RuntimeError("graphics page not opened")
g = _read_struct(self._gfx_mm, _Graphics)
# delta: iDeltaLapTime is always positive; isDeltaPositive tells sign
delta = g.iDeltaLapTime if g.isDeltaPositive else -g.iDeltaLapTime
return Graphics(
packet_id = g.packetId,
status = g.status,
completed_laps = g.completedLaps,
position = g.position,
current_time_ms = g.iCurrentTime,
last_time_ms = g.iLastTime,
best_time_ms = g.iBestTime,
flag = g.flag,
surface_grip = g.surfaceGrip,
tc = g.tc, # setup integer
abs = g.abs, # setup integer
engine_map = g.engineMap, # setup integer
stint_left_ms = g.driverStintTimeLeft,
delta_ms = delta,
is_valid_lap = bool(g.isValidLap),
fuel_estimated_laps = g.fuelEstimatedLaps,
)
def read_static(self) -> StaticInfo:
if self._sta_mm is None:
return StaticInfo(max_rpm=8500, max_fuel=110.0)
s = _read_struct(self._sta_mm, _Static)
return StaticInfo(
max_rpm = s.maxRpm,
max_fuel = s.maxFuel,
)
# ─── manual debug ─────────────────────────────────────────────────────────
if __name__ == "__main__":
import time
# Print key offsets for verification
print("=== Field offsets (for debug) ===")
for name, *_ in _Physics._fields_:
print(f" Physics.{name:30s} @ {getattr(_Physics, name).offset}")
print()
for name, *_ in _Graphics._fields_:
print(f" Graphics.{name:30s} @ {getattr(_Graphics, name).offset}")
print("\n=== Connecting to ACC ===")
sm = ACCSharedMemory()
if not sm.open():
print("ACC shared memory not found — is the game running?")
raise SystemExit(1)
print("Connected. Press Ctrl+C to exit.\n")
try:
while True:
p = sm.read_physics()
g = sm.read_graphics()
print(
f"RPM={p.rpms:5d} G={p.gear} V={p.speed_kmh:5.1f} "
f"T={p.gas*100:3.0f}% B={p.brake*100:3.0f}% "
f"TC={g.tc} ABS={g.abs} MAP={g.engine_map} "
f"BB={p.brake_bias*100:.1f}% "
f"GRIP={g.surface_grip*100:.0f}% "
f"LAP={g.current_time_ms/1000:6.3f}s",
end="\r",
)
time.sleep(0.05)
except KeyboardInterrupt:
print("\nbye")
finally:
sm.close()