Repository navigation
Expand file tree
/
Copy pathbsx.lua
More file actions
3890 lines (3279 loc) · 174 KB
/
Copy pathbsx.lua
File metadata and controls
3890 lines (3279 loc) · 174 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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- SPDX-License-Identifier: LicenseRef-CDAL-BSX-Source-Available-1.0
-- Editor metadata only: never require this file at runtime. Include ../ids.lua too.
-- These definitions show all tiers; they do not grant permissions or enable features.
-- LuaJIT standard-library completion comes from LuaLS. The host exposes only its
-- documented whitelist: safe/changes scripts have no require, ffi, io, package,
-- debug, jit or print. Native require accepts only ffi and bit; the console has print.
-- The string, table, os and coroutine libraries are restricted; see the Lua README.
-- Scripts may define on_unload() for ordinary hot reload; it is skipped after errors.
---@meta
---@alias BsxAddress integer|lightuserdata # Exact numeric address, or native CDAL lightuserdata.
---@alias BsxRuleValue number|string|lightuserdata # Decimal text preserves 64-bit integers; other text names an operand to read ("xmm1.f32", "$0", "tick").
---@alias BsxRuleCompare '=='|'~='|'!='|'<'|'<='|'>'|'>='|'contains'|'excludes'|'absent'|'present'
---@alias BsxRuleOperation 'set'|'add'|'sub'|'mul'|'div'|'min'|'max'|'and'|'or'|'xor'|'sqrt'|'cas'|'copy16'|BsxRuleCompare # A comparison is a check step: the later operations run only while it holds.
---@alias BsxRuleCondition [string, BsxRuleCompare, BsxRuleValue]|[string, 'absent'|'present'] # absent/present: whether a keyed table row exists
---@alias BsxRuleSet [string, BsxRuleOperation, BsxRuleValue]|[string, 'cas', BsxRuleValue, BsxRuleValue]|[string, 'absent'|'present'|'remove'] # cas: {memory, "cas", new, expected}; remove: {"#0[rcx].0", "remove"} deletes a table row; copy16: {"[rax+0x10]", "copy16", "buf[0x20]"}
---@alias BsxRuleReturn [string, BsxRuleValue]
---@class BsxEmptyEvent # plugins_loaded or title_screen: no copied fields.
---@class BsxFrameEvent
---@field frame integer # Lua number.
---@class BsxSaveLoadEvent
---@field key string # Exact decimal save key.
---@field argument integer
---@field replayed boolean # True for the one replay of an earlier load.
---@class BsxSaveLoadedEvent
---@field key string # Exact decimal save key.
---@field generation string # Exact decimal generation.
---@field argument integer
---@class BsxEquipmentRequestEvent # equip/unequip before the native call.
---@field bucket integer
---@field index integer
---@field tag integer
---@class BsxEquipmentAppliedEvent
---@field generation string
---@field item_word0 string # Exact decimal item word; persistence is unproven.
---@field count string # Exact signed decimal count.
---@field tag integer
---@field row integer
---@field cause integer
---@field controlled? boolean # Omitted when the controlled character is unknown.
---@class BsxWorldReadyEvent
---@field generation string
---@field requested_stage integer
---@field follows_save boolean
---@class BsxLoadRequestEvent
---@field requested_stage integer
---@field previous_stage integer
---@class BsxWeaponSwapEvent
---@field slot integer
---@field slot2 integer
---@class BsxQuickSlotUseEvent
---@field storage integer
---@field index integer
---@field use_parameter integer
---@field amount string # Exact unsigned decimal amount.
---@class BsxQuickSlotUseAfterEvent: BsxQuickSlotUseEvent
---@field result integer # Normal wrapper return, including failure; not proof of consumption.
---@class BsxMovieEvent
---@field path string # At most 259 bytes.
---@field path_truncated boolean
---@class BsxStatChangeEvent
---@field stat_id integer
---@field delta string # Exact signed decimal delta the game was asked to apply, not the amount applied.
---@field source_kind integer # 0 none, 1 an actor, 2 unknown.
---@class BsxSaveLoadAfterEvent
---@field key string # Exact decimal save key.
---@field argument integer
---@field result integer # The game's raw return code; not proof the load finished.
---@class BsxEquipmentAfterEvent: BsxEquipmentRequestEvent
---@field result integer # Zero is the game's success code, not proof the slot changed.
---@class BsxLoadRequestAfterEvent: BsxLoadRequestEvent
---@field current_stage integer # The manager's selector after the call, not loading progress.
---@class BsxWeaponSwapAfterEvent: BsxWeaponSwapEvent
---@field result integer
---@class BsxMovieAfterEvent: BsxMovieEvent
---@field opened boolean # The game's open call returned true; not playback.
---@class BsxBattleStateEvent
---@field in_battle boolean
---@class BsxKeyEvent
---@field virtual_key integer # Windows virtual key; zero marks a reset.
---@field scan_code integer
---@field modifiers integer # Ctrl=1, Alt=2, Shift=4, Win=8.
---@field repeat_count integer
---@field down boolean
---@field ['repeat'] boolean # Use e['repeat']; repeat is a Lua keyword.
---@field extended boolean
---@field reset boolean
---@field gamepad boolean # a controller button ([BSX] Gamepad=1); virtual_key is VK_GAMEPAD_*, scan_code the controller index
---@class BsxHitEvent
---@field target_key integer
---@field attacker_key? integer # Omitted when unknown; not a proven killer.
---@field skill_key integer
---@field sequence string # Exact decimal sequence.
---@field generation string # Exact decimal generation.
---@field producer_thread integer
---@class BsxDeathEvent
---@field actor_key integer
---@field source_key? integer # Omitted when unknown; not a proven killer.
---@field sequence string
---@field generation string
---@field producer_thread integer
---@class BsxReviveEvent
---@field actor_key integer
---@field sequence string
---@field generation string
---@field producer_thread integer
---@class BsxZoneChangedEvent
---@field in_safe_zone boolean
---@field in_town boolean
---@field prev_in_safe_zone boolean
---@field prev_in_town boolean
---@class BsxWeatherChangedEvent
---@field weather_mask integer
---@field prev_weather_mask integer
---@field precipitation number
---@class BsxGamepadEvent
---@field button string
---@field name string
---@field virtual_key integer
---@field pad_index integer
---@field down boolean
---@field ['repeat'] boolean # Use e['repeat']; repeat is a Lua keyword.
---@field reset boolean
---@class BsxFishingResultEvent
---@field matched boolean
---@field actor_key integer
---@field category_key integer
---@class BsxLootPickupEvent
---@field kind string
---@field actor_key integer
---@field interaction_key integer
---@field target_key integer
---@field result integer
---@class BsxSkillLearnedEvent
---@field skill_key integer
---@field level integer
---@field reason integer
---@field result integer
---@class BsxSkillResetEvent
---@field category integer
---@field result integer
---@class BsxPetSummonedEvent
---@field action string
---@field mercenary_no string # Exact decimal unsigned 64-bit mercenary ID.
---@field actor_key integer
---@field result integer
---@class BsxQuestDialogueEvent
---@field actor_key integer
---@field dialog_id integer
---@field dialog_sub integer
---@field speaking boolean
---@class BsxJournalUnlockedEvent
---@field count integer
---@field key integer
---@field mode integer
---@field category integer
---@field clear boolean
---@class BsxMiniGameRecordEvent
---@field key integer
---@field value number
---@field updated boolean
---@class BsxBossRushEvent
---@field phase string
---@field event_name string
---@field round integer
---@field round_limit integer
---@class BsxCombatDamageEvent # Observed HP change delivered on FRAME (Lua API 7+; Safe tier).
---@field amount integer # Rounded display HP change magnitude (>= 1; scaled 1/1000 of raw stat units).
---@field raw_delta string # Exact signed decimal HP delta passed to StatusComponent::ApplyStatDelta (negative = damage, positive = heal).
---@field is_heal boolean # True when raw_delta > 0 (healing/restoration); false when damage.
---@field target_key integer # Target actor key (0 if unavailable).
---@field attacker_key integer # Attacker/source actor key when known (0 when unknown or environmental).
---@field is_player_target boolean # True when the controlled player took this damage/heal.
---@field is_player_attacker boolean # True when the controlled player is the attributed attacker.
---@field realm 'server'|'client'|'unknown' # Simulation actor realm where ApplyStatDelta executed.
---@field flag integer # Opaque native flag byte from ApplyStatDelta.
---@class BsxWeaponDrawEvent # Player weapon draw/sheathe transition delivered on FRAME (Lua API 7+; Safe tier; SnapshotProvider=1).
---@field drawn boolean # True when the player drew a weapon; false when sheathed.
---@class BsxAttackHitEvent # Server-realm HP damage hit delivered on FRAME (Lua API 8+; Safe tier).
---@field amount integer # Rounded display HP damage magnitude (>= 1).
---@field raw_delta string # Exact signed decimal HP delta applied by StatusComponent::ApplyStatDelta.
---@field target_key integer # Target actor key (0 if unavailable).
---@field attacker_key integer # Attacker actor key when known (0 when unknown).
---@field is_player_target boolean # True when the controlled player took the hit.
---@field is_player_attacker boolean # True when the controlled player dealt the hit.
---@field realm 'server'|'client'|'unknown' # Simulation actor realm.
---@field flag integer # Opaque native flag byte.
---@class BsxKillEvent # Actor lethal HP transition delivered on FRAME (Lua API 8+; Safe tier).
---@field target_key integer # Killed actor key.
---@field killer_key integer # Killer actor key when known (0 when unknown).
---@field is_player_target boolean # True when the controlled player died.
---@field is_player_killer boolean # True when the controlled player scored the kill.
---@field overkill string # Non-negative exact decimal overkill HP amount.
---@field realm 'server'|'client'|'unknown' # Simulation actor realm.
---@class BsxJustActionEvent # Perfect guard / evade window pass delivered on FRAME (Lua API 8+; Safe tier).
---@field is_guard boolean # True for guard window evaluation, false for evade window.
---@field kind 'guard'|'evade' # Action kind string.
---@field is_late boolean # True when the native late-window output boolean was set.
---@field radius number # Extra radius parameter passed to EvaluateJustWindow.
---@class BsxGroggyChangedEvent # Groggy stack counter update delivered on FRAME (Lua API 8+; Safe tier).
---@field actor_key integer # Affected actor key.
---@field groggy boolean # True when resulting groggy stack counter is > 0.
---@field added boolean # True on groggy stack increment, false on decrement/clear.
---@field selector integer # Groggy contributor selector (0xFFFF when untagged).
---@field amount integer # Groggy delta magnitude applied.
---@field stack_count integer # Current signed groggy stack counter (+0x340).
---@class BsxBuffEvent # Client buff apply/remove acknowledgement delivered on FRAME (Lua API 8+; Safe tier).
---@field actor_key integer # Target actor key.
---@field buff_key integer # Buff definition key from TrocBuffAckInfo (+0x04).
---@field skill_key integer # Skill key from TrocBuffAckInfo (+0x00), or 0 when standalone.
---@field skill_level integer # Skill level (+0x08).
---@field buff_index integer # Sub-index within the skill/buff (+0x0C).
---@field uid integer # Unique server buff instance ID (+0x10).
---@field caster_key integer # Caster actor key (+0x14).
---@field is_player boolean # True when actor_key matches the controlled player.
---@class BsxDefinitionEntry
---@field row integer # Cache ordinal.
---@field key integer # Serialized key, distinct from row.
---@field name string # Cached internal name, not localized.
---@field display_name? string # Localized display name when ItemInfo::DisplayName and Localization::sTextPoolManager are declared and loaded.
---@class BsxItemInfo
---@field row integer # Cache ordinal.
---@field key integer # Serialized key, distinct from row.
---@field name string # Cached internal name, not localized.
---@field display_name? string # Localized display name when ItemInfo::DisplayName and Localization::sTextPoolManager are declared and loaded.
---@field max_stack string # Exact signed decimal value.
---@field max_durability integer
---@field category_row integer
---@field item_type integer
---@field cooldown_ms? integer # Active difficulty cooldown duration in ms (`0` if item uses shared fallback storage); Lua API 6+.
---@class BsxTime
---@field day integer # Client day counter; epoch unknown.
---@field hour integer
---@field minute integer
---@field second integer
---@field millisecond integer
---@field day_mod_7 integer # Stored day counter modulo seven, not a named weekday.
---@field progress_multiplier integer # Raw u16 that GetTime uses for progress extrapolation.
---@class BsxWeatherSnapshot
---@field rain_base number # Raw value before native attenuation.
---@field snow_base number
---@field override_count? integer # Active WeatherController override count when SnapshotProvider=1.
---@field precipitation? number
---@field humidity? number
---@field cloudiness? number
---@field wind_direction? number # Degrees.
---@field wind_speed? number
---@class BsxPosition
---@field x number # Game units; scale and compass directions are unverified.
---@field y number
---@field z number
---@field yaw_deg? number
---@class BsxActorSnapshot # Populated when [Lua] SnapshotProvider=1 and WORLD_READY.
---@field actor integer
---@field key integer
---@field controlled boolean
---@field kind 'normal'|'child'|'other'
---@field dead? boolean
---@field x? number
---@field y? number
---@field z? number
---@field distance? number
---@field yaw_deg? number
---@field character_row? integer
---@field character_name? string
---@field display_name? string
---@field faction? integer
---@class BsxActorList
---@field total integer
---@field truncated boolean
---@field sequence integer
---@field [integer] BsxActorSnapshot
---@class BsxStatSnapshot
---@field stat_id integer
---@field current integer
---@field stored integer
---@field max integer
---@field base_max integer
---@field override_max integer
---@field remainder integer
---@class BsxActorScreenBounds # 2D projected screen bounds returned by game.actors.screen_bounds().
---@field x number
---@field y number
---@field w number
---@field h number
---@field cx number
---@field cy number
---@field feet_x number
---@field feet_y number
---@field head_y number
---@field depth number
---@field on_screen boolean
---@class BsxPlayerState
---@field world_ready boolean
---@field in_movie boolean
---@field dead? boolean
---@field in_cutscene? boolean
---@field in_battle? boolean
---@field character_row? integer
---@field character_name? string
---@field display_name? string
---@field faction? integer
---@field in_safe_zone? boolean
---@field in_town? boolean
---@field weather_mask? integer
---@field active_slot_key? integer
---@field active_slot_occurrence? integer
---@field weapon_out? boolean
---@field in_cc_state? boolean
---@field weight_level? integer
---@field wanted_level? integer
---@field world_map_open? boolean # Lua API 8+, World Map screen state from UiControlManager observer.
---@field main_menu_open? boolean # Lua API 8+, Main Menu screen state from UiControlManager observer.
---@field menu_open? boolean # Lua API 8+, any menu/pause screen requesting reduced time scale or map/main menu.
---@field menu_time_scale? number # Lua API 8+, requested menu time scale (`< 1.0` when paused/menu active).
---@class BsxInventoryItem
---@field bucket integer # External bucket tag.
---@field index integer # Zero-based index within the bucket.
---@field row integer # Definition ordinal, not an external item key.
---@field count string # Exact signed decimal count.
---@field instance_id? string # Decimal ItemNo; omitted when unassigned.
---@class BsxEquipmentItem
---@field slot_tag integer # Actor-relative tag.
---@field index integer # Equipment index, not an inventory index.
---@field row integer
---@field count string
---@field instance_id? string
---@class BsxInventorySnapshot
---@field actor_key integer
---@field generation string # Script-local observation generation.
---@field truncated boolean
---@field [integer] BsxInventoryItem
---@class BsxEquipmentSnapshot
---@field actor_key integer
---@field generation string
---@field truncated boolean
---@field [integer] BsxEquipmentItem
---Rules run compiled register operations on the game thread; no Lua runs there.
---Operands: registers (edx, xmm0.f32, packed lanes xmm0.f32[2]), memory ([rcx+0x40].u32, chains like [[rcx+0x68]+0x40].f32),
---the script's cells $0..$15 (optionally typed, $3.f32), per-thread cells ^0..^7, keyed tables (#0[rcx].1.f32), per-call temporaries %0..%7 and read-only tick (milliseconds) and tick_us (microseconds).
---rsp, tick and rip cannot be written. Conditions all hold; integer arithmetic saturates.
---See bsx/lua/HOOK_RULES.md.
---@class CdalRuleSpec # Native Lua API 3.
---@field expect? string # Original bytes at the ID as hex pairs, ?? for any byte, up to 32; checked before hooking.
---@field enabled? boolean # false installs the rule paused until rule:enable(true); default true.
---@field after? boolean # func IDs: run when the function returns; rax/xmm0 are the result, other registers the entry arguments.
---@field context? boolean # With after = true: each call is followed from entry to return (or an exception); rules inside a marked call reach its temporaries as %%0..%%7 and `depth` counts marked calls. Inside an unmarked call (when false, before failed, paused) %%N, buf and depth fail. when is checked at entry.
---@field unwind? boolean # With after = true and before, context or an entry walk: the return phase also runs when an exception leaves a matched call (no result: rax/xmm0 refused there).
---@field buffer? boolean # With context = true: each call gets a zeroed 2048-byte buffer, buf[OFF].type (OFF a constant, a slot, or slot+constant), and `buf` is its address for each.
---@field before? BsxRuleSet[] # With after = true: run at function entry (conditions checked then); may change rcx/rdx/r8/r9/xmm0-3, memory, cells, temporaries; `set` then runs at return of the same call, sharing %0..%7.
---@field stop_on_failure? boolean # A change that cannot be made (unreadable/unwritable address, division by zero) skips the later changes and the rule's jump/ret.
---@field when? BsxRuleCondition[] # Up to 32 {operand, comparison, value} conditions (absent/present take no value); all must hold.
---@field each? CdalRuleEach # Walk a bounded list before `set`: its own `set` runs once per element, with @ the element's address.
---@field set? BsxRuleSet[] # One to 32 {operand, operation, value} operations, in order; {operand, "cas", new, expected} swaps 4- or 8-byte memory only if it still holds expected.
---@field ret? BsxRuleReturn # {return operand, value} at a function entry; cannot be combined with set.
---@field jump? integer # Continue at the ID's address plus this many bytes after the operations; must land on an instruction; not with ret.
---@class CdalRuleEach # A bounded list walk in a rule. Give count or end, not both.
---@field list string # Whole-number operand holding the first element's address, such as "[rcx+0x48].u64".
---@field count? string # Whole-number operand holding the number of elements.
---@field ["end"]? string # Whole-number operand holding the address after the last element.
---@field stride integer # Bytes from one element to the next, 1 to 65536.
---@field max integer # At most this many elements are walked, 1 to 1024.
---@field entry? boolean # With after = true: walk when the function is entered, after before; set runs at return.
---@field set BsxRuleSet[] # Operations per element; @ is the element's address ([@+0x10].u32). A false check step skips to the next element; a failed change with stop_on_failure stops the walk, the rest of set and jump/ret. Shares the 32 operations with before and set.
---@alias BsxEventName 'plugins_loaded'|'frame'|'save_load'|'equip'|'unequip'|'save_loaded'|'equip_applied'|'unequip_applied'|'world_ready'|'title_screen'|'load_request'|'weapon_swap'|'quick_slot_use'|'quick_slot_use_after'|'stat_change'|'save_load_after'|'equip_after'|'unequip_after'|'load_request_after'|'weapon_swap_after'|'movie_after'|'battle_state_after'|'movie'|'battle_state'|'key'|'gamepad'|'hit'|'death'|'revive'|'zone_changed'|'weather_changed'|'fishing_result'|'loot_pickup'|'skill_learned'|'skill_reset'|'pet_summoned'|'quest_dialogue'|'journal_unlocked'|'minigame_record'|'boss_rush_event'|'combat_damage'|'weapon_draw'|'attack_hit'|'kill'|'just_action'|'groggy_changed'|'buff_applied'|'buff_removed'
---@class CdalRule # Native Lua API 3; removed on stop, error or reload. Methods return true or nil and a reason.
local rule = {}
---Replace an operation's value (or a ret rule's return value). Native API 3.
---@param index integer # One-based.
---@param value BsxRuleValue
function rule:set(index, value) end
---Replace a condition's comparison value. Native API 3.
---@param index integer # One-based.
---@param value BsxRuleValue
function rule:when(index, value) end
---Pause or resume this rule without removing its hook. Native API 3.
---@param enabled boolean
function rule:enable(enabled) end
---Count executions where all conditions held. Native API 3.
---@return number hits
function rule:hits() end
---Whether the rule is installed and enabled. Native API 3.
---@return boolean active
function rule:active() end
---Remove this rule's hook now. Native API 3.
function rule:remove() end
---@class CdalPack # Safe Lua API 1+; native scripts receive lightuserdata addresses.
local pack = {}
---Read a declared pack site's address, or nil and a reason. Safe, Lua API 1+.
---@param site string
---@return BsxAddress? address
---@return string? reason
function pack:address(site) end
---Read a declared pack site's status, or nil and a reason for an unknown site. Safe, Lua API 1+.
---@param site string
---@return string? status
---@return string? reason
function pack:status(site) end
---@class BsxConfig
config = {}
---Read a integer from the settings snapshot; missing or malformed values use the default. Safe, Lua API 1+.
---@param section string
---@param key string
---@param default? integer # Defaults to 0.
---@return integer value
function config.int(section, key, default) end
---Read a finite number from the settings snapshot; missing or malformed values use the default. Safe, Lua API 1+.
---@param section string
---@param key string
---@param default? number # Defaults to 0.
---@return number value
function config.float(section, key, default) end
---Read a boolean from the settings snapshot; missing or malformed values use the default. Safe, Lua API 1+.
---@param section string
---@param key string
---@param default? boolean # Defaults to false.
---@return boolean value
function config.bool(section, key, default) end
---Read a string from the settings snapshot; missing or malformed values use the default. Safe, Lua API 1+.
---@param section string
---@param key string
---@param default? string # Defaults to an empty string.
---@return string value
function config.string(section, key, default) end
---Update an INI entry in the in-memory settings snapshot and persist buffer (`settings.ini` is written only when `config.save()` runs). Safe, Lua API 4+.
---@param section string # Nonempty section name or empty string for top-level keys; must not contain newlines, `[`, `]`, `=`, or control characters.
---@param key string # Nonempty key name without newlines, `[`, `]`, `=`, or control characters.
---@param value string|number|boolean # Stored as UTF-8 INI value without newlines or NULs.
function config.set(section, key, value) end
---Write buffered `config.set` changes losslessly to this script's `settings.ini` (preserving comments and unrelated keys, without triggering hot-reload). Safe, Lua API 4+; unavailable in the console.
---@return boolean? ok
---@return string? reason
function config.save() end
---@class BsxMemory
mem = {}
---Read a guarded unsigned 8-bit value, or nil and a reason. Safe, Lua API 1+.
---@param address BsxAddress
---@return integer? value
---@return string? reason
function mem.read_u8(address) end
---Read a guarded unsigned 32-bit value, or nil and a reason. Safe, Lua API 1+.
---@param address BsxAddress
---@return integer? value
---@return string? reason
function mem.read_u32(address) end
---Read a guarded unsigned 64-bit value as exact decimal text, or nil and a reason. Safe, Lua API 1+.
---@param address BsxAddress
---@return string? value
---@return string? reason
function mem.read_u64(address) end
---Read a guarded float, or nil and a reason. Safe, Lua API 1+.
---@param address BsxAddress
---@return number? value
---@return string? reason
function mem.read_f32(address) end
---Read a guarded pointer as an exact number (zero for null), or nil and a reason. Safe, Lua API 1+.
---@param address BsxAddress
---@return integer? value
---@return string? reason
function mem.read_ptr(address) end
---Write a unsigned 8-bit value to guarded writable non-executable memory. Native Lua API 3 only.
---@param address BsxAddress
---@param value integer
---@return boolean? ok # True, or nil and a reason.
---@return string? reason
function mem.write_u8(address, value) end
---Write a unsigned 16-bit value to guarded writable non-executable memory. Native Lua API 3 only.
---@param address BsxAddress
---@param value integer
---@return boolean? ok # True, or nil and a reason.
---@return string? reason
function mem.write_u16(address, value) end
---Write a unsigned 32-bit value to guarded writable non-executable memory. Native Lua API 3 only.
---@param address BsxAddress
---@param value integer
---@return boolean? ok # True, or nil and a reason.
---@return string? reason
function mem.write_u32(address, value) end
---Write a unsigned 64-bit value (decimal text preserves all bits) to guarded writable non-executable memory. Native Lua API 3 only.
---@param address BsxAddress
---@param value integer|string
---@return boolean? ok # True, or nil and a reason.
---@return string? reason
function mem.write_u64(address, value) end
---Compare-and-exchange on aligned writable non-executable memory: writes new only if the u32 still holds expected. Native Lua API 3 only.
---@param address BsxAddress
---@param expected integer
---@param new integer
---@return boolean? swapped # True; false and the value found; or nil and a reason.
---@return number|string? found_or_reason
function mem.cas_u32(address, expected, new) end
---Compare-and-exchange on aligned writable non-executable memory: writes new only if the u64 still holds expected (decimal text keeps all bits). Native Lua API 3 only.
---@param address BsxAddress
---@param expected integer|string
---@param new integer|string
---@return boolean? swapped # True; false and the value found as decimal text; or nil and a reason.
---@return string? found_or_reason
function mem.cas_u64(address, expected, new) end
---Write a finite float to guarded writable non-executable memory. Native Lua API 3 only.
---@param address BsxAddress
---@param value number
---@return boolean? ok # True, or nil and a reason.
---@return string? reason
function mem.write_f32(address, value) end
---Write a pointer as an exact number, decimal text or lightuserdata to guarded writable non-executable memory. Native Lua API 3 only.
---@param address BsxAddress
---@param value integer|string|lightuserdata
---@return boolean? ok # True, or nil and a reason.
---@return string? reason
function mem.write_ptr(address, value) end
---@class BsxFs
local fs = {}
---Read a file inside this script's data folder; denied operations raise an error. Safe, Lua API 1+.
---@param path string
---@return string contents
function fs.read(path) end
---Write a file inside this script's data folder; denied operations raise an error. Safe, Lua API 1+.
---@param path string
---@param contents string
---@return boolean ok # True on success.
function fs.write(path, contents) end
---Return whether a path exists inside this script's data folder (`data/...`). Safe, Lua API 4+.
---@param path string
---@return boolean exists
function fs.exists(path) end
---List filenames or child directories under a path in this script's data folder (`''` or `'subdir'`). Safe, Lua API 4+.
---@param path? string
---@return string[] entries
function fs.list(path) end
---Delete a file or empty directory inside this script's data folder. Safe, Lua API 4+.
---@param path string
---@return boolean deleted
function fs.delete(path) end
---Create a directory inside this script's data folder. Safe, Lua API 4+.
---@param path string
---@return boolean created
function fs.mkdir(path) end
---@class BsxJson
local json = {}
---Encode a plain-data Lua value (`nil`, boolean, finite number, string, array, or string-keyed table) to JSON; returns nil and a reason on cycles or unsupported types. Safe, Lua API 4+.
---@param value any
---@param opts? { pretty?: boolean }
---@return string? json_text
---@return string? reason
function json.encode(value, opts) end
---Decode a bounded JSON string (<= 256 KiB, depth <= 16) into Lua values; returns nil and a reason on malformed input. Safe, Lua API 4+.
---@param text string
---@return any value
---@return string? reason
function json.decode(text) end
---@class BsxSave
local save = {}
---Read per-save data; nil alone means absent, nil and a reason means unavailable. Safe, Lua API 3; CoSave and WorldReady must be enabled.
---@param key string
---@return string|number|nil value
---@return string? reason
function save.get(key) end
---Update per-save data in memory; this does not start or guarantee a game save. Safe, Lua API 3.
---@param key string
---@param value string|number # Bounded string or finite number.
---@return boolean? ok # True, or nil and a reason.
---@return string? reason
function save.set(key, value) end
---@class BsxHandle # Returned by subscription and bus helpers on Lua API 4+.
local handle = {}
---Cancel this callback, hotkey, timer, bus, audio voice, or tween handle (idempotent). Lua API 4+.
---@return boolean cancelled # True if cancelled by this call; false if already inactive.
function handle:off() end
---Alias for `handle:off()` (useful for `bsx.audio` voice and `bsx.tween` handles). Safe, Lua API 4+.
---@return boolean cancelled
function handle:stop() end
---Alias for `handle:off()` (useful for `bsx.audio` voice and `bsx.tween` handles). Safe, Lua API 4+.
---@return boolean cancelled
function handle:cancel() end
---Return whether this registration is still active. Lua API 4+.
---@return boolean active
function handle:active() end
---@class BsxBus # Cross-script plain-data bus on FRAME (Lua API 4+; absent from console).
local bus = {}
---Subscribe to plain-data messages emitted on topic; runs on FRAME. Lua API 4+.
---@param topic string # 1..64 ASCII characters in A-Z, a-z, 0-9, ., _, :, -.
---@param callback fun(payload: any, topic: string)
---@return BsxHandle handle
function bus.on(topic, callback) end
---Queue a plain-data message for FRAME delivery to all active subscribers of topic. Lua API 4+.
---@param topic string
---@param payload? any # nil, boolean, finite number, string (<=4096B), or plain acyclic tables.
---@return integer? subscribers # Current subscriber count when queued; nil and reason if queue full.
---@return string? reason
function bus.emit(topic, payload) end
---Register a named request provider callable by other scripts on FRAME (an uncaught error in `handler` disables the provider script until reload; use `pcall` inside `handler` for recoverable errors). Lua API 4+.
---@param name string # 1..64 ASCII characters in A-Z, a-z, 0-9, ., _, :, -.
---@param handler fun(payload: any): any
---@return BsxHandle? handle # Handle on success; nil and reason on duplicate.
---@return string? reason
function bus.provide(name, handler) end
---Invoke a named provider synchronously on FRAME within both scripts' budgets and fault boundaries (`false, reason` if the provider throws, disabling that provider script until reload). Lua API 4+.
---@param name string
---@param payload? any
---@return boolean ok
---@return any result_or_reason
function bus.call(name, payload) end
---@class BsxModInfo
---@field folder string
---@field name string
---@field version string
---@field state string
---@field exports string[]
---@class BsxMods # Lua API 4+ active-mod discovery & exported function proxies.
local mods = {}
---List all currently running (`state == 'on'`) BSX Lua mods and their exported function names. Safe, Lua API 4+.
---@return BsxModInfo[] mods
function mods.list() end
---Return a read-only proxy table wrapping a running mod's `bsx.export` functions, or nil and a reason. Safe, Lua API 4+.
---@param folder string # Script folder name (e.g. a dependency in `script.json` `"requires"`).
---@return table<string, fun(...): any>? proxy
---@return string? reason
function mods.get(folder) end
---@class BsxAudioOptions
---@field volume? number # Playback gain in `0.0..4.0` (default `1.0`).
---@field pitch? number # Playback pitch ratio in `0.25..4.0` (default `1.0`).
---@field loop? boolean # Loop playback until stopped or unloaded (default `false`).
---@class BsxAudio # Script-local WAV audio playback helpers (Lua API 4+; absent from console).
local audio = {}
---Play a PCM WAV file relative to this script's `data/` folder. Returns a stoppable handle on success, or nil and reason. Safe, Lua API 4+.
---@param rel_path string # Relative `.wav` path under this script's `data/` folder.
---@param opts? BsxAudioOptions
---@return BsxHandle? handle
---@return string? reason
function audio.play(rel_path, opts) end
---Stop all active audio voices owned by this script. Safe, Lua API 4+.
---@return boolean stopped
function audio.stop_all() end
---Read the BSX Lua audio master volume (`0.0..1.0`). Safe, Lua API 4+.
---@return number volume
function audio.master_volume() end
---Set the BSX Lua audio master volume clamped to `0.0..1.0`. Safe, Lua API 4+.
---@param volume number
---@return number clamped
function audio.set_master_volume(volume) end
---@alias BsxTweenEase 'linear'|'in_quad'|'out_quad'|'in_out_quad'|'in_cubic'|'out_cubic'|'in_out_cubic'|'smoothstep'
---@class BsxTweenOptions
---@field ease? BsxTweenEase # Easing curve name (default `'linear'`).
---@field on_update fun(value: number|table, progress: number)
---@field on_done? fun()
---@class BsxTween # Bounded frame-stepped scalar and table interpolators (Lua API 4+; absent from console).
local tween = {}
---Animate a number or numeric-field table (`<= 32` keys) over `duration_sec` (`0..3600`). Returns a cancellable handle or nil and reason. Safe, Lua API 4+.
---@param from number|table
---@param to number|table
---@param duration_sec number # Finite duration in `0..3600` seconds.
---@param on_update_or_opts fun(value: number|table, progress: number)|BsxTweenOptions
---@param on_done? fun()
---@return BsxHandle? handle
---@return string? reason
function tween.to(from, to, duration_sec, on_update_or_opts, on_done) end
---Cancel all active tweens created by this script. Safe, Lua API 4+.
---@return boolean cleared
function tween.cancel_all() end
---@class BsxMemoryInfo
---@field working_set_mb number # Current process working set in MiB.
---@field peak_working_set_mb number # Peak process working set in MiB.
---@field private_mb number # Committed private bytes in MiB.
---@field system_total_mb number # Total physical system RAM in MiB.
---@field system_avail_mb number # Available physical system RAM in MiB.
---@field system_load_pct integer # Windows physical memory load percentage (`0..100`).
---@field window_focused boolean # True when a window owned by this process is currently in the foreground.
---@field cooldown_remaining_sec number # Seconds remaining on the global 30 s trim cooldown (`0` when ready).
---@field trim_in_progress boolean # True while the background working-set trim worker is running.
---@field last_trim_seq integer # Monotonic counter incremented each time an asynchronous trim completes.
---@field last_trim_before_mb number # Working set in MiB captured when the most recent completed trim started.
---@field last_trim_after_mb number # Working set in MiB captured immediately after the most recent completed trim finished.
---@field last_trim_freed_mb number # Working set reduction in MiB from the most recent completed trim.
---@class BsxMemoryTrimResult
---@field before_mb number # Process working set before trimming in MiB.
---@field after_mb number # Working set snapshot at queue time (`pending = true`) or final working set after completion.
---@field freed_mb number # Working set reduction in MiB (`0` while `pending = true`; read `info().last_trim_freed_mb` once done).
---@field cooldown_sec integer # Host-enforced global cooldown in seconds (`30`).
---@field pending boolean # True because trimming runs asynchronously off `FRAME`; poll `bsx.memory.info()` for `last_trim_seq` / `trim_in_progress`.
---@class BsxProcessMemory # Safe-tier process working-set inspection and cooldown-guarded trim (Lua API 7+; absent from console).
local memory = {}
---Query current process working set, private bytes, physical RAM availability, foreground focus, and trim cooldown/worker status. Safe, Lua API 7+.
---@return BsxMemoryInfo? info
---@return string? reason
function memory.info() end
---Queue an asynchronous working-set trim (`SetProcessWorkingSetSize(-1, -1)`) on a host worker thread so `FRAME` never blocks or exceeds the callback time budget, enforcing a process-wide 30 s cooldown across all scripts. Poll `bsx.memory.info().last_trim_seq` / `trim_in_progress` for final after/freed MB. Safe, Lua API 7+.
---@return BsxMemoryTrimResult? result
---@return string? reason
function memory.trim() end
---@class BsxSystemInfo
---@field viewport_w integer # Game window client width in pixels (or primary screen width if headless).
---@field viewport_h integer # Game window client height in pixels (or primary screen height if headless).
---@field fps number # Smoothed frames per second measured across up to the last 120 `FRAME` boundaries.
---@field frame_ms number # Average frame interval in milliseconds across up to the last 120 frames.
---@field fps_1pct_low number # 1% low FPS estimate (1000 / 99th-percentile frame time) over recent frames.
---@field uptime_sec number # Elapsed runtime seconds since BSX Lua started.
---@field frame_count integer # Total `FRAME` callbacks seen since startup.
---@field window_focused boolean # True when a window owned by this process is currently in the foreground.
---@field monitor_hz integer # Current display refresh rate in Hz (0 if unavailable).
---@class BsxSystem # Safe-tier viewport, frame-pacing telemetry, and clipboard helpers (Lua API 7+; absent from console).
local system = {}
---Query game viewport dimensions, FPS / 1% low / frame-time telemetry, uptime, focus, and display refresh rate. Safe, Lua API 7+.
---@return BsxSystemInfo info
function system.info() end
---Copy UTF-8 text (up to 64 KiB, NUL-free) to the Windows clipboard via CF_UNICODETEXT; returns true or nil and a reason. Safe, Lua API 7+.
---@param text string
---@return boolean? ok
---@return string? reason
function system.copy_text(text) end
---Read UTF-8 text (up to 64 KiB) from the Windows clipboard via CF_UNICODETEXT; returns the string or nil and a reason. Safe, Lua API 7+.
---@return string? text
---@return string? reason
function system.paste_text() end
---@class Bsx
---@field api_version integer # Running native BSX interface version.
---@field lua_api integer # This script's selected Lua API.
---@field dev_mode boolean # True when [Lua] DevMode=1 (Lua API 4+).
---@field fs BsxFs
---@field json BsxJson # Deterministic JSON encoder/decoder (Lua API 4+).
---@field save BsxSave # Lua API 3; calls can refuse until the service is ready.
---@field bus BsxBus # Lua API 4+; absent from console.
---@field mods BsxMods # Lua API 4+; absent from console.
---@field ui BsxUi # Lua API 4+; absent from console.
---@field draw BsxDraw # Lua API 4+; absent from console.
---@field audio BsxAudio # Lua API 4+; absent from console.
---@field tween BsxTween # Lua API 4+; absent from console.
---@field memory BsxProcessMemory # Lua API 7+; absent from console.
---@field system BsxSystem # Lua API 7+; absent from console.
---@field config BsxConfig # Same table as global config.
---@field mem BsxMemory # Same table as global mem.
bsx = {}
---@type BsxBus
bsx.bus = {}
---@type BsxAudio
bsx.audio = {}
---@type BsxTween
bsx.tween = {}
---@type BsxProcessMemory
bsx.memory = {}
---@type BsxSystem
bsx.system = {}
---@class BsxUiPanel # Retained overlay panel handle (Lua API 4+; up to 4 per script, 32 widgets).
local ui_panel = {}
---Append a text line to the panel and return its widget ID.
---@param text string # At most 127 UTF-8 bytes, NUL-free.
---@return integer widget_id
function ui_panel:text(text) end
---Append a horizontal separator and return its widget ID.
---@return integer widget_id
function ui_panel:separator() end
---Append a button and return its widget ID; callback runs on FRAME.
---@param label string # Nonempty UTF-8 label, at most 127 bytes.
---@param callback fun()
---@return integer widget_id
function ui_panel:button(label, callback) end
---Append a checkbox and return its widget ID; callback receives the new boolean on FRAME.
---@param label string # Nonempty UTF-8 label, at most 127 bytes.
---@param initial boolean
---@param callback fun(checked: boolean)
---@return integer widget_id
function ui_panel:checkbox(label, initial, callback) end
---Append a float slider and return its widget ID; callback receives the new value on FRAME.
---@param label string # Nonempty UTF-8 label, at most 127 bytes.
---@param min number
---@param max number # Finite, strictly greater than min.
---@param initial number
---@param callback fun(value: number)
---@return integer widget_id
function ui_panel:slider(label, min, max, initial, callback) end
---Update the label/text of an existing widget on this panel (or overlay text for progress).
---@param widget_id integer
---@param text string # At most 127 UTF-8 bytes, NUL-free.
---@return boolean updated
function ui_panel:set_text(widget_id, text) end
---Update the value of a checkbox (boolean), slider/progress/combo (number), or input_text (string) widget on this panel.
---@param widget_id integer
---@param value boolean|number|string
---@return boolean updated
function ui_panel:set_value(widget_id, value) end
---Replace the item list of an existing combo or listbox widget on this panel and optionally set its 1-based selected index (or 0 to clear listbox selection).
---@param widget_id integer
---@param items (string|BsxListboxItem)[] # Combo: 1..64 labels (<= 254 bytes). Listbox: 0..2048 labels or `{ label, category }` tables (<= 128 KiB).
---@param selected_index? integer # Optional 1-based selected index (or 0 for listbox).
---@return boolean updated
function ui_panel:set_items(widget_id, items, selected_index) end
---Keep the next widget on the same horizontal line as the previous widget.
---@return integer widget_id
function ui_panel:same_line() end
---Append a progress bar (fraction in 0..1, optional overlay text) and return its widget ID.
---@param fraction number # Finite number clamped to 0..1.
---@param overlay_text? string # At most 127 UTF-8 bytes, NUL-free.
---@return integer widget_id
function ui_panel:progress(fraction, overlay_text) end
---Append a combo dropdown and return its widget ID; callback receives (index, item) on FRAME.
---@param label string # Nonempty UTF-8 label, at most 127 bytes.
---@param items string[] # Nonempty item labels (1..64), total serialized size <= 254 bytes.
---@param initial_index integer # 1-based selected index.
---@param callback fun(index: integer, item: string)
---@return integer widget_id
function ui_panel:combo(label, items, initial_index, callback) end
---Append a single-line text input submitted on Enter (or on every edit when `opts.live` is true on `BSX.Lua.UI/5+`); callback runs on FRAME.
---@param label string # Nonempty UTF-8 label, at most 127 bytes.
---@param initial_text string # Initial buffer text, at most 127 UTF-8 bytes, NUL-free.
---@param callback fun(text: string)
---@param opts? boolean|{ live?: boolean } # When true / `{ live = true }`, invoke callback on live text changes.
---@return integer widget_id
function ui_panel:input_text(label, initial_text, callback, opts) end
---Append a click-to-capture hotkey picker (`Esc` cancels, `Backspace` clears to `""`) and return its widget ID; optional callback runs on FRAME when changed.
---@param label string # Nonempty UTF-8 label, at most 127 bytes.
---@param current_key string # Current chord string (e.g. `"f7"`, `"ctrl+shift+h"`, `"numpad9"`, `"mouse4"`, `"pad_a"` with `Gamepad=1`), at most 63 bytes.
---@param callback? fun(key: string)
---@return integer widget_id
function ui_panel:hotkey(label, current_key, callback) end
---Start a collapsible section (paired with end_section) and return its widget ID.
---@param label string # Nonempty UTF-8 header label, at most 127 bytes.
---@param default_open? boolean # Default true.
---@return integer widget_id
function ui_panel:section(label, default_open) end
---End the most recent collapsible section on this panel.
---@return integer widget_id
function ui_panel:end_section() end
---@class BsxColorRgba
---@field r number # Red channel in 0..1.
---@field g number # Green channel in 0..1.
---@field b number # Blue channel in 0..1.
---@field a number # Alpha channel in 0..1.
---@field hex string # Uppercase #RRGGBBAA string.
---Add an ImGui RGBA color picker widget (`ColorEdit4`) to this panel (BSX.Lua.UI/3+).
---@param label string
---@param default_color? BsxColor
---@param callback? fun(color: BsxColorRgba, hex: string)
---@return integer widget_id
function ui_panel:color(label, default_color, callback) end
---Begin a tab bar container on this panel (pair with `end_tab_bar`).
---@param id_label string
---@return integer widget_id
function ui_panel:begin_tab_bar(id_label) end
---Begin a tab item inside the active tab bar (pair with `end_tab`).
---@param label string
---@return integer widget_id
function ui_panel:tab(label) end