Repository navigation
Expand file tree
/
Copy pathruntime_triggers.cpp
More file actions
4092 lines (3829 loc) · 183 KB
/
Copy pathruntime_triggers.cpp
File metadata and controls
4092 lines (3829 loc) · 183 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
// SacredSDK — runtime trigger hooks (HANDOFF task 20).
//
// Lets modders write `sacred.on_trigger("HQ_3_2_1_sera_DLG_OFFEN",
// function(ctx) … end)` and have the function fire when Sacred dispatches
// that trigger at game-time. First-cut implementation hooks:
//
// FUN_004915a0 "SelfTriggerQuest" (NPC dialog → quest trigger)
// FUN_00491170 "Dialog-Check" (Dialog %s nicht möglich)
//
// Both share the same MSVC SEH prologue and the same calling convention
// (__fastcall: ECX = ctx, EDX = record, plus stack args we don't touch).
// On entry, `[ECX + 0xa460]` is the interpreter's current name-buffer — it
// holds the trigger name as an inline ASCII cstring. We snapshot ECX in a
// naked thunk, call our C++ helper which reads the name and dispatches to
// the registered Lua handlers, then jump through to the saved prologue +
// jmp back to FUN_xxx + 7 so Sacred sees its own stack frame untouched.
//
// Why two hooks and not one
// -------------------------
// The agent's recon (see HANDOFF task 20) showed tag-0x1a is NOT the fire
// site (it's just metadata-setup). Triggers fire from two distinct
// subsystems: SelfTriggerQuest for `<NPC>_DLG_*` style names, Dialog-Check
// for `Dialog %s` style names. Hooking both gives full coverage. A handler
// that doesn't match the fired name is a cheap dictionary miss.
//
// Lifecycle
// ---------
// bake worker thread → take_state(L) → if handlers exist, install_hooks()
// main thread → Sacred plays → trampoline → fire(name) → pcall
//
// Threading
// ---------
// Sacred's interpreter runs on the main thread. Bake worker exits before
// the first hook fire, so there is no concurrent Lua access. We do the
// .text install on the bake worker thread; that's a race against Sacred's
// main thread potentially executing the prologue we're overwriting — see
// HANDOFF gotcha #12 for the SuspendThread mitigation if it bites. For now
// we follow text_logger's pattern (which works) and skip the suspend.
#include "sdk.h"
#include "hooks/detour.h" // Goal A2: unified trampoline-detour installer
#include <cstring>
#include <cstdio>
extern "C" {
#include "lua/lua.h"
#include "lua/lauxlib.h"
#include "lua/lualib.h"
}
namespace sdk { namespace runtime_triggers {
volatile bool g_ready = false;
volatile long g_handlers = 0;
volatile long g_fires = 0;
volatile long g_handler_errs = 0;
volatile long g_thunk_self_trigger = 0;
volatile long g_thunk_dialog_check = 0;
volatile long g_thunk_funnel = 0;
volatile long g_thunk_hash = 0;
volatile long g_seen_self_trigger = 0;
volatile long g_seen_dialog_check = 0;
volatile long g_seen_funnel = 0;
volatile long g_seen_hash = 0;
// ── DIALOG-TEXT SOURCE PROBE (read-only) ────────────────────────────────────
// dialog_arm sets g_dlgres_armed_c10 = the armed NPC's creature+0x10 value (the
// id the renderer is suspected to resolve → "murderer"). read_name_hash (the
// FUN_0080e780 hook) then logs every resolve of THAT id together with its CALLER
// return address, pinning the render call-site. Capped to avoid flooding. Setting
// it to 0 disarms. This reuses the existing FUN_0080e780 hook (no new detour).
volatile uint32_t g_dlgres_armed_c10 = 0;
volatile long g_dlgres_logged = 0;
constexpr long DLGRES_LOG_MAX = 60;
// Active dialog-text redirect hash. Set by sacred.dialog_redirect(hash) from
// Lua on the npc_in_dialog RISING edge (o:on_talk) and cleared (0) on the
// FALLING edge (o:on_talk_end) — so it stays armed for the WHOLE talk window
// regardless of which frame the body string is fetched. text_logger's
// FUN_0080f5e0 hook reads it via sdk_current_dialog_text_hash() and swaps the
// vanilla dialog sentence for our text. (Replaces the fetch-time bit read, which
// missed: the closing "Good luck" line is fetched as the talk bit is clearing.)
volatile uint32_t g_redir_active_hash = 0;
static lua_State* g_L = nullptr;
static char g_status[256] = "(idle)";
// Diagnostic: small ring of recently-seen trigger names, populated by the
// trampolines whether or not a handler matched. Lets the user discover the
// REAL names Sacred dispatches and register handlers for them.
//
// Anti-spam: time-window dedup. If the same name was pushed within
// RING_DEDUP_MS ms, skip — that way per-frame UI lookups (queried 30×/s)
// don't fill the ring and crowd out rare event-only queries.
//
// Guarded by g_ring_cs because both thunks plus the overlay reader touch
// it.
static const int RING_CAP = 64;
static const uint64_t RING_DEDUP_MS = 1000;
struct RingEntry {
char text[128];
uint64_t pushed_at;
};
static RingEntry g_ring[RING_CAP];
static int g_ring_head = 0; // next slot to overwrite
static int g_ring_count = 0;
static CRITICAL_SECTION g_ring_cs;
static bool g_ring_cs_init = false;
static void set_status(const char* fmt, ...) {
va_list ap; va_start(ap, fmt);
vsnprintf(g_status, sizeof(g_status), fmt, ap);
va_end(ap);
sdk_log("[runtime_triggers] %s", g_status);
}
const char* status() { return g_status; }
// =========================================================================
// Game-state bindings — direct hero-struct writes.
// =========================================================================
//
// Task-21 recon concluded that Sacred has NO standalone C primitives for
// these operations — gold-set / has-item / qbit-flip are all bytecode
// interpreter cases. The cleanest runtime path is direct struct writes
// via the CT pointer chain that player_state.cpp already resolves.
//
// Offsets (verified by recon; medium confidence):
// hero + 0x3EE u32 gold
// hero + 0x1A4..0x1EC (step 4) 19 equip slots of item handles (sdk_items.inc)
//
// Hero quest bits (ctx:set_qbit / get_qbit, sacred.hero_qbit) live in
// cStatsManager, 160 per difficulty: sdk_vars.inc.
constexpr uintptr_t HERO_OFF_GOLD = 0x3EE;
constexpr uintptr_t HERO_OFF_EQUIP_BASE = 0x1A4;
// Verified via CT table + char.cpp source (community refs):
constexpr uintptr_t HERO_OFF_SKILL_ID_BASE = 0x3CC; // 8 × u8
constexpr uintptr_t HERO_OFF_SKILL_LVL_BASE = 0x3D4; // 8 × u8
constexpr uintptr_t HERO_OFF_MAX_HEALTH = 0x4D4; // u32
constexpr uintptr_t HERO_OFF_CUR_HEALTH = 0x4D8; // u32
constexpr uintptr_t HERO_OFF_CLASS_ID = 0x010; // u16
static int32_t sacred_get_hero_gold() {
uintptr_t base = sdk::player::hero_base();
if (!base) return -1;
void* addr = (void*)(base + HERO_OFF_GOLD);
if (IsBadReadPtr(addr, sizeof(uint32_t))) return -1;
return (int32_t)*(uint32_t*)addr;
}
// SILENT path — direct write to [hero+0x3EE], no UI/sound side effects.
// Use as a fallback or when modder explicitly wants quiet adjustment.
static bool sacred_give_hero_gold_silent(int32_t amount) {
uintptr_t base = sdk::player::hero_base();
if (!base) return false;
void* addr = (void*)(base + HERO_OFF_GOLD);
if (IsBadWritePtr(addr, sizeof(uint32_t))) return false;
int64_t cur = (int64_t)*(uint32_t*)addr;
int64_t neu = cur + amount;
if (neu < 0) neu = 0;
if (neu > 0x7FFFFFFFLL) neu = 0x7FFFFFFFLL;
*(uint32_t*)addr = (uint32_t)neu;
sdk_log("[runtime_triggers] give_gold(silent) %+d (%lld -> %lld)",
amount, cur, neu);
return true;
}
// COSMETIC EVENT — emits a GOLD_CHANGE event to Sacred's kernel event
// bus. Live test (2026-05-14) showed the event handler does NOT itself
// touch [hero+0x3EE] — it just routes side-effects to registered UI
// listeners (coin sound, floating "+N" text, HUD invalidate). So we
// pair the event with the direct write below to get both the money
// AND the polish. Three vanilla callsites use this same blob pattern.
//
// Event blob layout (36 bytes):
// +0x00 vtable = 0x00890B38
// +0x04 kind = 6
// +0x08 color = 0xFFFFFFFF (yellow, +) or 0xFFFF0040 (red, -)
// +0x0C x = [hero+0x1C] (world position)
// +0x10 y = [hero+0x20]
// +0x14 subkind = 0x3EC (GOLD_CHANGE discriminator)
// +0x18 amount = signed delta
// +0x1C reserved = 0
// +0x20 cleanup_ptr = NULL (MUST be null — kernel frees if non-null)
//
// Calling convention:
// kernel = get_kernel(&blob, 0, 0) // cdecl, 3 ignored args, EAX = singleton
// recv_event(kernel, &blob, 0, 0) // __thiscall, ECX=kernel, ret 0x0c
struct GoldChangeEvent {
void* vtable;
uint32_t kind;
uint32_t color;
uint32_t x;
uint32_t y;
uint32_t subkind;
int32_t amount;
uint32_t reserved;
void* cleanup_ptr;
};
typedef void* (__cdecl *kernel_get_fn_t)(void* a0, int a1, int a2);
typedef void (__thiscall *kernel_recv_fn_t)(void* this_, void* ev, int a1, int a2);
constexpr uintptr_t SACRED_KERNEL_GET_VA = 0x00808E50;
constexpr uintptr_t SACRED_KERNEL_RECV_VA = 0x008092F0;
constexpr uintptr_t SACRED_EVENT_VTABLE_VA = 0x00890B38;
constexpr uint32_t GOLD_CHANGE_SUBKIND = 0x000003EC;
// Emit the cosmetic event (sound/text/HUD-invalidate). Returns true on
// success. Caller must have already updated [hero+0x3EE] via silent path.
static bool emit_gold_change_event(uintptr_t hero_base, int32_t amount) {
HMODULE exe = g_attach.exe_module;
if (!exe || (uintptr_t)exe != 0x00400000) return false;
GoldChangeEvent ev;
__try {
ev.vtable = (void*)SACRED_EVENT_VTABLE_VA;
ev.kind = 6;
ev.color = (amount >= 0) ? 0xFFFFFFFFu : 0xFFFF0040u;
ev.x = *(uint32_t*)(hero_base + 0x1C);
ev.y = *(uint32_t*)(hero_base + 0x20);
ev.subkind = GOLD_CHANGE_SUBKIND;
ev.amount = amount;
ev.reserved = 0;
ev.cleanup_ptr = nullptr;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
auto get_kernel = (kernel_get_fn_t) SACRED_KERNEL_GET_VA;
auto recv_evt = (kernel_recv_fn_t)SACRED_KERNEL_RECV_VA;
void* kernel = nullptr;
__try {
kernel = get_kernel(&ev, 0, 0);
} __except (EXCEPTION_EXECUTE_HANDLER) { return false; }
if (!kernel) return false;
__try {
recv_evt(kernel, &ev, 0, 0);
} __except (EXCEPTION_EXECUTE_HANDLER) { return false; }
return true;
}
// PUBLIC give_gold — does both the money math AND the cosmetic event.
// Live testing showed the event is purely a notifier — it doesn't write
// to [hero+0x3EE], so we direct-write FIRST then emit the event to
// trigger the sound/text/HUD invalidate. The event sees the freshly
// updated gold value when the HUD listener queries it.
static bool sacred_give_hero_gold(int32_t amount) {
uintptr_t base = sdk::player::hero_base();
if (!base) return false;
// 1) Actual money change (silent direct write, clamped 0..INT32_MAX).
if (!sacred_give_hero_gold_silent(amount)) return false;
// 2) Cosmetic event — coin sound + "+N" floating text + HUD refresh.
bool ev_ok = emit_gold_change_event(base, amount);
if (!ev_ok) {
sdk_log("[runtime_triggers] give_gold %+d: event emit failed "
"(money still credited)", amount);
}
return true;
}
// ctx:has_item(type): does the hero carry an item of this TYPE (backpack,
// equipment, or the quest-item list)? The scan lives in sdk_items.inc. Until
// 2026-09-11 this compared equipment item HANDLES with a res id, over 18 of the
// 19 slots and no backpack, so it never matched (SDK_GAPS gap 6).
static int hero_item_count_type(uint32_t type, bool* listed); // sdk_items.inc
static int sacred_hero_has_item(int item_type) {
bool listed = false;
int n = hero_item_count_type((uint32_t)item_type, &listed);
if (n < 0) return -1;
return (n > 0 || listed) ? 1 : 0;
}
// ctx:set_qbit(bit[, on]) / ctx:get_qbit(bit): the hero's own quest bits, the
// "HeroQBit" of vanilla's SetVarBit and IsQBitSet: (sdk_vars.inc). Until
// 2026-09-11 these were no-ops waiting for an "interp-ctx+0xA860 bitarray";
// that slot is the operand reader's INT staging, not a bitfield (SDK_GAPS gap 12).
static int hero_qbit_now(int bit, int set); // sdk_vars.inc
static bool sacred_set_hero_qbit(int bit, bool value) {
return hero_qbit_now(bit, value ? 1 : 0) == (value ? 1 : 0);
}
static int sacred_get_hero_qbit(int bit) {
return hero_qbit_now(bit, -1);
}
// Notification: forward to the overlay's toast list (rendered in
// overlay.cpp). Sacred's own in-engine banner system would need a
// reverse-engineering pass we haven't done — but for the modder's UX,
// an ImGui toast over the game window achieves the same effect and
// works during the menu/loading too.
//
// Caller has already applied length cap + dedup + throttle (see
// l_sacred_notify), so we just forward.
static bool sacred_show_banner(const char* text) {
if (!text) return false;
::sdk::overlay::push_toast(text);
return true;
}
// =========================================================================
// Lua-side: sacred.on_trigger(name, fn) + sacred.clear_triggers()
// =========================================================================
//
// Handlers live in LUA_REGISTRYINDEX[SDK_HANDLERS_KEY], which is itself a
// table mapping trigger name → list of fns. Multiple handlers per name
// stack; fire() runs each in registration order, each in pcall.
static const char SDK_HANDLERS_KEY[] = "sacred_sdk__trigger_handlers";
static const char SDK_CTX_KEY[] = "sacred_sdk__ctx";
static const char SDK_TICK_KEY[] = "sacred_sdk__tick_handlers";
// on_world_load handler list — fired once when the walker captures
// cQuestManager (definition of the fire path is near the walker hook).
static const char SDK_WORLD_LOAD_KEY[] = "sacred_sdk__world_load_handlers";
// =========================================================================
// Notification throttle — anti-overflow for Sacred's UI message queue
// =========================================================================
//
// Sacred's in-game banner ("Quest completed", "Group eliminated", …) goes
// through a finite-size message queue inside the engine. If our mod
// floods sacred.notify() from a hot handler (e.g. fired every frame), we
// risk overflowing the queue or stacking dozens of banners.
//
// Defense in depth:
// 1. Hard cap on message length (256 chars). Anything longer is truncated.
// 2. Minimum gap between successive notifications (default 750 ms).
// Excess calls return false (caller can detect throttling).
// 3. Back-to-back duplicates are silently dropped regardless of gap.
//
// These caps apply REGARDLESS of how many handlers stack on a trigger;
// every notify() call across all of them goes through one funnel.
constexpr DWORD NOTIFY_MIN_GAP_MS = 750;
constexpr size_t NOTIFY_MAX_LEN = 256;
static DWORD g_last_notify_tick = 0;
static char g_last_notify_text[NOTIFY_MAX_LEN] = "";
static CRITICAL_SECTION g_notify_cs;
static bool g_notify_cs_init = false;
volatile long g_notify_calls = 0;
volatile long g_notify_passed = 0;
volatile long g_notify_dropped = 0;
static void ensure_handlers_table(lua_State* L) {
lua_getfield(L, LUA_REGISTRYINDEX, SDK_HANDLERS_KEY);
if (lua_istable(L, -1)) { lua_pop(L, 1); return; }
lua_pop(L, 1);
lua_newtable(L);
lua_setfield(L, LUA_REGISTRYINDEX, SDK_HANDLERS_KEY);
}
static int l_on_trigger(lua_State* L) {
const char* name = luaL_checkstring(L, 1);
luaL_checktype(L, 2, LUA_TFUNCTION);
ensure_handlers_table(L);
lua_getfield(L, LUA_REGISTRYINDEX, SDK_HANDLERS_KEY); // [+1] handlers
lua_getfield(L, -1, name); // [+1] list-or-nil
bool is_new_key = !lua_istable(L, -1);
if (is_new_key) {
lua_pop(L, 1);
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setfield(L, -3, name); // handlers[name]=list
}
int len = (int)lua_rawlen(L, -1);
lua_pushvalue(L, 2);
lua_rawseti(L, -2, len + 1);
lua_pop(L, 2);
if (is_new_key) InterlockedIncrement(&g_handlers);
return 0;
}
static int l_clear_triggers(lua_State* L) {
lua_pushnil(L);
lua_setfield(L, LUA_REGISTRYINDEX, SDK_HANDLERS_KEY);
g_handlers = 0;
return 0;
}
// sacred.on_tick(fn) — fn() is pcalled ~every 250 ms while in-world
// (driven off the sacred_hash heartbeat). Ideal for polling hero
// position, e.g. "has the player reached the quest marker?".
static int l_on_tick(lua_State* L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_getfield(L, LUA_REGISTRYINDEX, SDK_TICK_KEY);
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, SDK_TICK_KEY);
}
int len = (int)lua_rawlen(L, -1);
lua_pushvalue(L, 1);
lua_rawseti(L, -2, len + 1);
lua_pop(L, 1);
return 0;
}
// sacred.on_world_load(fn) — registers a handler that fires ONCE per
// Sacred process, the moment the FunkCode walker first captures the
// cQuestManager pointer (= a save is loaded, world is alive, walker's
// per-record loop hasn't yet started). The right place to call
// `sacred.questbook_register(...)` so new quest_ids are present before
// tag-0x35 (log_entry) records dispatch.
//
// LIMITATION: switching to a different save within the same Sacred
// session won't re-fire — cQuestManager is a singleton and we keep the
// pointer cached. Workaround: restart Sacred between saves while
// testing. (A multi-fire variant would need a hook on cObjectManager
// load instead of the walker entry; tracked as a future SDK issue.)
static int l_on_world_load(lua_State* L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_getfield(L, LUA_REGISTRYINDEX, SDK_WORLD_LOAD_KEY);
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, SDK_WORLD_LOAD_KEY);
}
int len = (int)lua_rawlen(L, -1);
lua_pushvalue(L, 1);
lua_rawseti(L, -2, len + 1);
lua_pop(L, 1);
return 0;
}
// -------------------------------------------------------------------------
// sacred.notify(text) -> bool
// shows a top-of-screen banner ("Quest completed" style). Returns true
// if the message was forwarded to Sacred's queue, false if throttled /
// deduped / truncated-to-empty.
// -------------------------------------------------------------------------
static int l_sacred_notify(lua_State* L) {
size_t len = 0;
const char* msg = luaL_checklstring(L, 1, &len);
InterlockedIncrement(&g_notify_calls);
if (!g_notify_cs_init) {
InitializeCriticalSection(&g_notify_cs);
g_notify_cs_init = true;
}
EnterCriticalSection(&g_notify_cs);
char clipped[NOTIFY_MAX_LEN];
size_t clip_len = (len < NOTIFY_MAX_LEN - 1) ? len : NOTIFY_MAX_LEN - 1;
memcpy(clipped, msg, clip_len);
clipped[clip_len] = 0;
if (clip_len == 0) {
LeaveCriticalSection(&g_notify_cs);
InterlockedIncrement(&g_notify_dropped);
lua_pushboolean(L, 0);
return 1;
}
DWORD now = GetTickCount();
bool throttled = (now - g_last_notify_tick) < NOTIFY_MIN_GAP_MS;
bool duplicate = (strcmp(clipped, g_last_notify_text) == 0);
if (throttled || duplicate) {
LeaveCriticalSection(&g_notify_cs);
InterlockedIncrement(&g_notify_dropped);
lua_pushboolean(L, 0);
return 1;
}
g_last_notify_tick = now;
strncpy_s(g_last_notify_text, sizeof(g_last_notify_text),
clipped, _TRUNCATE);
LeaveCriticalSection(&g_notify_cs);
bool ok = sacred_show_banner(clipped);
if (ok) InterlockedIncrement(&g_notify_passed);
else InterlockedIncrement(&g_notify_dropped);
sdk_log("[notify] %s", clipped);
lua_pushboolean(L, ok ? 1 : 0);
return 1;
}
// -------------------------------------------------------------------------
// ctx:gold() / ctx:give_gold(N) / ctx:has_item(N) / ctx:set_qbit(N,V) etc.
// Each method receives `self` (ctx table) as arg 1.
// -------------------------------------------------------------------------
static int l_ctx_gold(lua_State* L) {
int g = sacred_get_hero_gold();
if (g < 0) { lua_pushnil(L); return 1; }
lua_pushinteger(L, g);
return 1;
}
static int l_ctx_give_gold(lua_State* L) {
int amount = (int)luaL_checkinteger(L, 2);
lua_pushboolean(L, sacred_give_hero_gold(amount));
return 1;
}
static int l_ctx_give_gold_silent(lua_State* L) {
int amount = (int)luaL_checkinteger(L, 2);
lua_pushboolean(L, sacred_give_hero_gold_silent(amount));
return 1;
}
static int l_ctx_charge_gold(lua_State* L) {
int amount = (int)luaL_checkinteger(L, 2);
lua_pushboolean(L, sacred_give_hero_gold(-amount));
return 1;
}
static int l_ctx_has_item(lua_State* L) {
int item_res = (int)luaL_checkinteger(L, 2);
int r = sacred_hero_has_item(item_res);
if (r < 0) { lua_pushnil(L); return 1; }
lua_pushboolean(L, r);
return 1;
}
static int l_ctx_set_qbit(lua_State* L) {
int bit = (int)luaL_checkinteger(L, 2);
bool val = lua_isnone(L, 3) ? true : (lua_toboolean(L, 3) != 0);
lua_pushboolean(L, sacred_set_hero_qbit(bit, val));
return 1;
}
static int l_ctx_get_qbit(lua_State* L) {
int bit = (int)luaL_checkinteger(L, 2);
int r = sacred_get_hero_qbit(bit);
if (r < 0) { lua_pushnil(L); return 1; }
lua_pushboolean(L, r);
return 1;
}
static int l_ctx_notify(lua_State* L) {
// ctx:notify("…") forwards to sacred.notify("…"). We just shuffle
// the args (drop `self`, keep the message) and call l_sacred_notify.
lua_remove(L, 1); // drop self
return l_sacred_notify(L);
}
// -------------------------------------------------------------------------
// Named-POSITION bindings — [cQuestManager+0x334..+0x338], stride 0x64.
// This is the table tag 0x17 DefPos fills (pos_*, LOC_RG*), with X, Y, radius
// and Z at +0x44..+0x50 (.claude/knowledge/quests/RE_conditions_vars.md §2.7).
// It is NOT the script-variable table: variables are sacred.var_* and
// ctx:get_var / ctx:set_var (sdk_vars.inc).
//
// sacred.state_dump() -> count (also logs to file)
// sacred.state_get(name) -> {x, y, r, z} or nil (exact name, else any case)
// sacred.state_set(name, v0[, v1, v2, v3]) -> bool (in-place only)
// -------------------------------------------------------------------------
// Caller owns the buffer; we cap at 256 rows to keep stack pressure in check.
constexpr int STATE_DUMP_MAX = 256;
// Forward decl needed by both the questbook block (which gates on
// "world loaded?") and the named-state Lua bindings further down.
// Definition lives near the bottom alongside the walker hook.
extern volatile uintptr_t g_quest_mgr;
// =========================================================================
// Quest-display registry — read + register from Lua.
// =========================================================================
//
// Recon: see sdk/.claude/knowledge/re/questbook_inserter.md. The display-registry
// vector lives at ABSOLUTE GLOBALS (not behind a cQuestManager pointer):
//
// DAT_00aad3a4 uint8_t* begin (= [cQuestManager + 0x424] alias)
// DAT_00aad3a8 uint8_t* end
// stride 0x174 (372 bytes)
// key (uint32_t) at entry+0x08
//
// Engine path for inserting an entry is `FUN_00806d20` — but it only ever
// fires from `case 0x9a` of the master record dispatcher (savegame /
// network 0x9a records). FunkCode tags 0x35/0x57/0x40/0x3f/0x75/0x4d
// only MUTATE existing entries. That's why brand-new quest_ids silently
// no-op end-to-end without the SDK's help.
//
// Our SDK uses Option A from the recon: call the underlying vector::resize
// directly to grow the array, then stamp `entry+8 = quest_id`. Active-hero
// bookkeeping (quest_id == 100/0x65) is skipped — caller takes that risk
// (the only known users of that path are vanilla, not custom mods).
//
// Lifecycle: the registry is REBUILT from the savegame each load, so the
// mod must re-register its quest_ids on every world-load. Cheap pattern:
// register from a `sacred.on_trigger(...)` handler that fires once early
// in the session.
constexpr uintptr_t QB_REGISTRY_BEGIN_VA = 0x00aad3a4; // uint8_t** begin
constexpr uintptr_t QB_REGISTRY_END_VA = 0x00aad3a8; // uint8_t** end
constexpr uintptr_t QB_REGISTRY_RESIZE_VA = 0x004b5370; // vector::resize
constexpr uintptr_t QB_ENTRY_STRIDE = 0x174;
constexpr uintptr_t QB_ENTRY_OFF_QID = 0x08;
// --- SDK-owned quest-id allow-list ---------------------------------------
// Every quest_id the SDK itself registers is recorded here. The "hide other
// quests" suppressor (Variant A — keep vanilla scripts 100% intact, just
// stop the *vanilla* quests from showing in the journal/map) zeroes the
// render gate on any registry entry whose quest_id is NOT in this list.
// Fixed array, no STL dependency.
static uint32_t g_sdk_qids[128];
static int g_sdk_qids_n = 0;
static void sdk_qid_add(uint32_t id) {
for (int i = 0; i < g_sdk_qids_n; i++) if (g_sdk_qids[i] == id) return;
if (g_sdk_qids_n < (int)(sizeof(g_sdk_qids) / sizeof(g_sdk_qids[0])))
g_sdk_qids[g_sdk_qids_n++] = id;
}
static bool sdk_qid_has(uint32_t id) {
for (int i = 0; i < g_sdk_qids_n; i++) if (g_sdk_qids[i] == id) return true;
return false;
}
// __thiscall: `this` = pointer to vector struct (begin / end / cap triple
// at 0x00aad3a4..0x00aad3ac), arg1 = new element count. Callee-pops the
// stack arg per MSVC convention. Verified against FUN_004b5370 decompile
// at decompiled/004b5370_FUN_004b5370.c.
typedef void (__thiscall *qb_resize_t)(void* this_, uint32_t new_count);
static unsigned g_track_log_n = 0;
static int questbook_count_safe() {
__try {
uintptr_t begin = *(uintptr_t*)QB_REGISTRY_BEGIN_VA;
uintptr_t end = *(uintptr_t*)QB_REGISTRY_END_VA;
if (!begin || end < begin) return 0;
return (int)((end - begin) / QB_ENTRY_STRIDE);
} __except (EXCEPTION_EXECUTE_HANDLER) {
return -1;
}
}
// Read quest_id at the given slot. Returns -1 on out-of-range / fault.
static int64_t questbook_quest_id_at(int idx) {
int n = questbook_count_safe();
if (idx < 0 || idx >= n) return -1;
__try {
uintptr_t begin = *(uintptr_t*)QB_REGISTRY_BEGIN_VA;
uintptr_t entry = begin + (uintptr_t)idx * QB_ENTRY_STRIDE;
return (int64_t)(uint32_t)*(uint32_t*)(entry + QB_ENTRY_OFF_QID);
} __except (EXCEPTION_EXECUTE_HANDLER) {
return -1;
}
}
// Append a new entry, stamp its quest_id field. Returns the new slot's
// index on success, -1 on failure. Gating: refuse if the cQuestManager
// walker hasn't fired yet (= save not loaded), because vector::resize on
// an uninitialized vector struct would crash.
static int questbook_register_impl(uint32_t quest_id) {
if (!g_quest_mgr) {
sdk_log("[questbook] register refused: world not loaded yet "
"(cQuestManager not captured)");
return -1;
}
int before = questbook_count_safe();
if (before < 0) {
sdk_log("[questbook] register refused: count read faulted");
return -1;
}
uint32_t new_count = (uint32_t)(before + 1);
// Sanity: refuse if this quest_id already exists, to avoid duplicate
// entries that would confuse the mutator scan.
for (int i = 0; i < before; i++) {
if (questbook_quest_id_at(i) == (int64_t)quest_id) {
sdk_qid_add(quest_id);
sdk_log("[questbook] register skipped: quest_id=%u already at idx=%d",
quest_id, i);
return i;
}
}
qb_resize_t resize = (qb_resize_t)QB_REGISTRY_RESIZE_VA;
__try {
resize((void*)QB_REGISTRY_BEGIN_VA, new_count);
} __except (EXCEPTION_EXECUTE_HANDLER) {
sdk_log("[questbook] register: resize(%u) raised — abort",
new_count);
return -1;
}
int after = questbook_count_safe();
if (after != (int)new_count) {
sdk_log("[questbook] register: post-resize count=%d, expected %u",
after, new_count);
return -1;
}
// Stamp quest_id into entry+8. The rest of the entry is whatever the
// resize default-constructed via the copy ctor — typically zeros + the
// installed vtable pointer. Mutator handlers read quest_id at +8 to
// match, so this single write makes the entry "discoverable".
__try {
uintptr_t begin = *(uintptr_t*)QB_REGISTRY_BEGIN_VA;
uintptr_t entry = begin + (uintptr_t)before * QB_ENTRY_STRIDE;
*(uint32_t*)(entry + QB_ENTRY_OFF_QID) = quest_id;
sdk_qid_add(quest_id);
sdk_log("[questbook] registered quest_id=%u at idx=%d entry=%p",
quest_id, before, (void*)entry);
return before;
} __except (EXCEPTION_EXECUTE_HANDLER) {
sdk_log("[questbook] register: quest_id stamp faulted");
return -1;
}
}
// Variant A suppressor: keep all vanilla FunkCode 100% intact (so the
// new-game intro / Shaddar cinematic / fade-in — which are quest-trigger
// chains wrapped in IF/BlockReader blocks — are NOT corrupted by record
// deletion), and instead stop *vanilla* quests from appearing. For every
// registry entry whose quest_id is NOT SDK-owned, zero the journal render
// gate (+0x24) and the map-marker coords (+0x10/+0x14). The vector entry
// itself is left in place (no resize → no engine desync); the quest logic
// still runs, it just never shows in the journal or on the map. Idempotent
// — safe to call every tick (re-hides quests the script re-activates).
// Returns the number of entries hidden, or -1 on fault.
static int questbook_hide_others_impl() {
int n = questbook_count_safe();
if (n <= 0) return n;
int hidden = 0;
__try {
uintptr_t begin = *(uintptr_t*)QB_REGISTRY_BEGIN_VA;
for (int i = 0; i < n; i++) {
uintptr_t e = begin + (uintptr_t)i * QB_ENTRY_STRIDE;
uint32_t qid = *(uint32_t*)(e + QB_ENTRY_OFF_QID);
if (qid == 0 || sdk_qid_has(qid)) continue; // keep SDK quests
bool any = false;
if (*(uint32_t*)(e + 0x24) != 0) { // journal gate
*(uint32_t*)(e + 0x24) = 0; any = true;
}
if (*(uint32_t*)(e + 0x10) != 0 ||
*(uint32_t*)(e + 0x14) != 0) { // kompass marker
*(uint32_t*)(e + 0x10) = 0;
*(uint32_t*)(e + 0x14) = 0; any = true;
}
if (any) hidden++;
}
} __except (EXCEPTION_EXECUTE_HANDLER) {
return -1;
}
return hidden;
}
// sacred.hide_other_quests() -> n (hidden count, nil on fault)
// Call from on_tick in a class mod to keep the journal free of that
// class's built-in quests while leaving the scripts (and intro) vanilla.
static int l_sacred_hide_other_quests(lua_State* L) {
int h = questbook_hide_others_impl();
if (h < 0) { lua_pushnil(L); return 1; }
lua_pushinteger(L, h);
return 1;
}
// sacred.hide_vanilla_quests(on) -> on
// Toggle the race-free journal-builder suppressor (hook on FUN_006b07e0).
// While on, every NON-SDK quest's render gate (+0x24) and map marker are
// zeroed right before the journal is built, so vanilla quests never show
// — script logic and the new-game intro stay 100% vanilla. Call ONCE
// (e.g. at mod top); persists for the process.
extern volatile bool g_hide_vanilla;
static int l_sacred_hide_vanilla_quests(lua_State* L) {
bool on = true;
if (lua_gettop(L) >= 1) on = lua_toboolean(L, 1) != 0;
g_hide_vanilla = on;
sdk_log("[questbook] hide_vanilla_quests = %s", on ? "ON" : "OFF");
lua_pushboolean(L, on);
return 1;
}
// -------------------------------------------------------------------------
// Lua bindings: sacred.questbook_count / dump / register / get_id.
// -------------------------------------------------------------------------
static int l_sacred_questbook_count(lua_State* L) {
int n = questbook_count_safe();
if (n < 0) { lua_pushnil(L); return 1; }
lua_pushinteger(L, n);
return 1;
}
// Shared dump impl — used by both the Lua binding and the overlay F8 key.
// Returns the entry count (or -1 if the registry isn't readable).
static int questbook_dump_impl() {
int n = questbook_count_safe();
if (n < 0) {
sdk_log("[questbook] dump: registry not readable "
"(world not loaded / globals not mapped)");
return -1;
}
sdk_log("[questbook] === dump: %d entries (cQuestManager=%p) ===",
n, (void*)g_quest_mgr);
uintptr_t begin = 0;
__try { begin = *(uintptr_t*)QB_REGISTRY_BEGIN_VA; }
__except (EXCEPTION_EXECUTE_HANDLER) { begin = 0; }
for (int i = 0; i < n; i++) {
int64_t qid = questbook_quest_id_at(i);
sdk_log("[questbook] %3d. quest_id=%lld (0x%llx)", i, qid, qid);
if (!begin) continue;
uintptr_t e = begin + (uintptr_t)i * QB_ENTRY_STRIDE;
__try {
// Header region (+0x00..+0x23): type/flags/quest_id/state.
const uint8_t* b = (const uint8_t*)e;
sdk_log("[questbook] hdr +00: %02x %02x %02x %02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x %02x %02x %02x",
b[0],b[1],b[2],b[3], b[4],b[5],b[6],b[7],
b[8],b[9],b[10],b[11], b[12],b[13],b[14],b[15]);
sdk_log("[questbook] hdr +10: %02x %02x %02x %02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x %02x %02x %02x",
b[16],b[17],b[18],b[19], b[20],b[21],b[22],b[23],
b[24],b[25],b[26],b[27], b[28],b[29],b[30],b[31]);
// Log slots: +0x24 (slot 0) then +0x28.. (slots 1..10), as u32.
const uint32_t* L = (const uint32_t*)(e + 0x24);
sdk_log("[questbook] log s0=%08x s1=%08x s2=%08x s3=%08x "
"s4=%08x s5=%08x", L[0], L[1], L[2], L[3], L[4], L[5]);
sdk_log("[questbook] log s6=%08x s7=%08x s8=%08x s9=%08x "
"s10=%08x", L[6], L[7], L[8], L[9], L[10]);
} __except (EXCEPTION_EXECUTE_HANDLER) {
sdk_log("[questbook] (entry body read faulted)");
}
}
sdk_log("[questbook] === end dump ===");
return n;
}
// Public entry point (declared in sdk.h) — bound to the overlay F8 key.
void questbook_dump_to_log() {
questbook_dump_impl();
}
static int l_sacred_questbook_dump(lua_State* L) {
lua_pushinteger(L, questbook_dump_impl());
return 1;
}
static int l_sacred_questbook_register(lua_State* L) {
lua_Integer qid = luaL_checkinteger(L, 1);
if (qid < 0 || qid > 0xFFFFFFFFLL) {
return luaL_error(L, "sacred.questbook_register: quest_id %lld "
"out of u32 range", (long long)qid);
}
int idx = questbook_register_impl((uint32_t)qid);
if (idx < 0) { lua_pushnil(L); return 1; }
lua_pushinteger(L, idx);
return 1;
}
static int l_sacred_questbook_get_id(lua_State* L) {
int idx = (int)luaL_checkinteger(L, 1);
int64_t qid = questbook_quest_id_at(idx);
if (qid < 0) { lua_pushnil(L); return 1; }
lua_pushinteger(L, qid);
return 1;
}
// =========================================================================
// Direct entry population — the working path for NEW quests.
// =========================================================================
//
// tag-0x35 (QuestLogSet) records in custom FunkCode/QuestCode do NOT
// execute at world-load for a brand-new quest (vanilla FunkCode is
// structured into quest blocks gated by progression; appended records
// sit in an unreached path; vanilla entries get their log slots from the
// savegame 0x9a stream instead). So instead of relying on the engine to
// run our tag-0x35, we populate the registry entry DIRECTLY after
// registering it.
//
// Recon (sdk/.claude/knowledge/re/questbook_resolver.md + questbook_render.md):
// * journal render gate (FUN_006b07e0): show entry iff
// *(u32*)(entry+0x24) != 0 AND
// *(u16*)(entry+0x16C) == page+1 (or ==0 on page 0)
// * the +0x24 value is what FUN_00672740(name) returns:
// sacred_hash31(name) | 0x80000000 (0 if name not in the loaded
// resource dictionary — so the string MUST exist; we don't fake it)
// * log line 0 -> +0x24, lines 1.. -> +0x28, +0x2C, … (u32 each)
// * +0x00 = 3 and +0x04 = 1 mirror a normal vanilla quest (icon /
// text-helper path); not hard gates but match vanilla shape.
//
// FUN_00672740 is __cdecl(const char* name) — bare name, NO "res:"
// prefix (the interpreter strips it). Needs the resource dictionary
// loaded, which it is post world-load (call from sacred.on_world_load).
constexpr uintptr_t QB_RESOLVE_VA = 0x00672740;
constexpr uintptr_t QB_ENTRY_OFF_TYPE = 0x00; // u32, vanilla=3
constexpr uintptr_t QB_ENTRY_OFF_KIND = 0x04; // u32, vanilla 1/2/100
constexpr uintptr_t QB_ENTRY_OFF_LOG0 = 0x24; // u32 log slot 0 (gate 1)
constexpr uintptr_t QB_ENTRY_OFF_LOGN = 0x28; // u32 log slots 1..10
constexpr uintptr_t QB_ENTRY_OFF_PAGE = 0x16C; // u16 page id (gate 2)
// Sacred's resource-name hash (the engine's FUN_0080eaa0 / sacred_hash31).
// Pure C++ port of the verified Lua port in custom/lua/lib/text.lua
// (which is checked against all 823 ids in hash_names.csv). We compute
// the handle OURSELVES instead of calling the engine resolver
// FUN_00672740 — that resolver is __thiscall-into a lazily-created
// resource-cache singleton (DAT_017e7f68) and calling it at on_world_load
// (first walker entry, dict not yet built) crashes hard in engine code,
// uncatchable by SEH.
//
// We don't need the engine call: the journal text formatter (FUN_006b4940,
// reached from the builder FUN_006b07e0) itself does
// (id & 0x80000000) ? FUN_0080eaf0(id & 0x7fffffff) : ...
// i.e. it RE-RESOLVES the hash against the dictionary at RENDER time —
// when the journal is open and the dict is guaranteed loaded. So all we
// must deposit at entry+0x24 is `sacred_hash31(name) | 0x80000000`.
// Pure arithmetic, no engine state, safe to call any time.
static uint32_t sacred_hash31(const char* s) {
const uint32_t MOD = 999999991u; // 0x3B9AC9F7
const uint32_t MUL = 113u; // 0x71
uint32_t h = 0;
for (const unsigned char* p = (const unsigned char*)s; *p; ++p) {
uint32_t oc = *p;
if (oc >= 0x61 && oc <= 0x7a) oc -= 0x20; // ascii lower->upper
uint32_t sm = oc + h * MUL; // both mod 2^32
int64_t si = (int32_t)sm; // signed 32-bit view
int64_t r;
if (si >= 0) r = (si % (int64_t)MOD);
else r = -((-si) % (int64_t)MOD);
if (r < 0) r += 0x100000000LL;
h = (uint32_t)(r & 0xFFFFFFFFu);
}
return h & 0x7FFFFFFFu;
}
// Returns the +0x24 handle for a resource name (hash | 0x80000000), or 0
// for an empty/null name. Strips a leading "res:" if present. NO engine
// call — see sacred_hash31 note above for why.
static unsigned questbook_resolve_name(const char* name) {
if (!name || !*name) return 0;
if (strncmp(name, "res:", 4) == 0) name += 4;
if (!*name) return 0;
return sacred_hash31(name) | 0x80000000u;
}
// Populate an existing registry entry's log slots + render-gate fields so
// the journal builder shows it. `names[0]` -> +0x24 (title line), then
// +0x28, +0x2C, … for the rest. `page` 0 => first journal tab.
// Returns: 0 ok, -1 entry not found, -2 a name didn't resolve (entry left
// untouched in that case so we never write a half-built row).
static int questbook_set_log_impl(uint32_t quest_id, int page,
const char* const* names, int n_names) {
if (n_names <= 0 || n_names > 11) return -2;
// Resolve ALL names FIRST. FUN_00672740 walks the resource-dictionary
// singleton and can trigger growth of the quest-registry vector as a
// side effect — so we must NOT hold an entry pointer across it. Resolve
// up front, then scan + write back-to-back with nothing in between that
// could realloc/move the vector.
unsigned handles[11] = {0};
for (int i = 0; i < n_names; i++) {
handles[i] = questbook_resolve_name(names[i]);
if (handles[i] == 0) {
sdk_log("[questbook] set_log: name #%d '%s' did not resolve "
"(not in loaded resource dictionary) — aborting, "
"entry left clean", i, names[i] ? names[i] : "(null)");
return -2;
}
}
// NOW locate the entry (fresh begin) and write immediately.
uintptr_t e = 0;
int cnt = questbook_count_safe();
if (cnt <= 0) return -1;
__try {
uintptr_t begin = *(uintptr_t*)QB_REGISTRY_BEGIN_VA;
for (int i = 0; i < cnt; i++) {
uintptr_t cand = begin + (uintptr_t)i * QB_ENTRY_STRIDE;
if (*(uint32_t*)(cand + QB_ENTRY_OFF_QID) == quest_id) { e = cand; break; }
}
} __except (EXCEPTION_EXECUTE_HANDLER) { return -1; }
if (!e) return -1;
__try {
// Ground-truth from live F8 dumps of vanilla side quest 15001
// (active) vs main quest 1: +0x00 is the quest CATEGORY
// (3 = main, 4 = side) — NOT a completed flag. +0x04 = 2 for an
// active quest (vanilla bumps it to 100 only at a late progress
// stage). +0x0C = 1 on every active vanilla quest. Our previous
// +00=0 made the row look invalid/"completed"; +00=3 had looked
// "primary" because 3 == main category. Match an active SIDE
// quest exactly:
// +0x00 = quest CATEGORY: 3 = MAIN/story, 4 = side. The journal
// builder FUN_006b07e0:109 tests `==3` for the main-quest icon set
// and the active-quest header, and the world map follows the same
// field. Vanilla picks it by id (TriggerQuest FUN_0046c160): ids
// 1..99 are story, 100 and up are side quests — so an SDK quest
// chooses its look with its id.
*(uint32_t*)(e + QB_ENTRY_OFF_TYPE) = (quest_id <= 99) ? 3u : 4u;
*(uint32_t*)(e + QB_ENTRY_OFF_KIND) = 2; // 2 = active state
// Active bullet = +0x0C bit0 (vanilla active = 1). Set bit0 via a
// masked RMW instead of a whole-word write so a step state stamped
// earlier by questbook_set_step_done (the same byte) survives a
// re-call of set_log; mirrors set_step_done's RMW.
{
uint8_t b0c = *(uint8_t*)(e + 0x0C);
*(uint8_t*)(e + 0x0C) = (uint8_t)(b0c | 1);
}
*(uint32_t*)(e + QB_ENTRY_OFF_LOG0) = handles[0];
for (int i = 1; i < n_names; i++) {
*(uint32_t*)(e + QB_ENTRY_OFF_LOGN + (uintptr_t)(i - 1) * 4) = handles[i];
}
*(uint16_t*)(e + QB_ENTRY_OFF_PAGE) =
(uint16_t)(page <= 0 ? 0 : (page + 1));
} __except (EXCEPTION_EXECUTE_HANDLER) {
sdk_log("[questbook] set_log: write to entry %p faulted", (void*)e);
return -1;
}
sdk_log("[questbook] set_log quest_id=%u page=%d lines=%d "
"(+0x24=%08x) @ %p", quest_id, page, n_names,