paavohtl Claude Opus 4.6 (1M context) commited on
Commit
920c66b
Β·
1 Parent(s): d621fac

feat: port GfxDir__FindEntry to Rust, add GfxHandler__LoadDir impl

Browse files

GfxDir__FindEntry (0x566520): Hooked and verified β€” returns correct
entry pointers for all lookups during replay test. Implements:
- Case-insensitive name matching (A-Z β†’ a-z)
- 10-bit CRC hash (FUN_566390) for bucket lookup
- Pipe-separated fallback names ("path|fallback")
- Linked list traversal in hash buckets

GfxHandler__LoadDir (0x5663E0): Pure Rust implementation written but
not yet hooked. Parses .dir file format:
- Magic "DIR\x1A" validation
- Hash table allocation via vtable I/O
- Relative-to-absolute pointer fixup for 1024 buckets

Also adds: GfxHandler reset (FUN_5665F0), gfx_dir_hash helper,
DISPLAYGFX_CONSTRUCTOR and IMG_DECODE address constants.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

crates/openwa-core/src/engine/ddgame.rs CHANGED
@@ -539,6 +539,260 @@ pub unsafe fn display_layer_color_init(wrapper: *mut DDGameWrapper) {
539
  set_color(display, 3, 0x70);
540
  }
541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  /// Pure Rust implementation of GfxResource__Create_Maybe (0x4F6300).
543
  ///
544
  /// Convention: usercall(ECX=gfx_handler, EAX=name) + 1 stack(output), RET 0x4.
 
539
  set_color(display, 3, 0x70);
540
  }
541
 
542
+ /// Hash function for GfxDir entry lookup (FUN_566390).
543
+ ///
544
+ /// 10-bit CRC-like hash over the global name buffer at 0x8ACF58.
545
+ /// Operates on the already-lowercased name.
546
+ ///
547
+ /// # Safety
548
+ /// `name` must be a valid null-terminated C string pointer.
549
+ unsafe fn gfx_dir_hash(name: *const u8) -> u32 {
550
+ let mut hash: u32 = 0;
551
+ let mut p = name;
552
+ while *p != 0 {
553
+ let bit9 = (hash >> 9) & 1;
554
+ hash = ((hash << 1) | bit9) & 0x3FF;
555
+ hash = hash.wrapping_add(*p as u32) & 0x3FF;
556
+ p = p.add(1);
557
+ }
558
+ hash
559
+ }
560
+
561
+ /// Pure Rust implementation of GfxDir__FindEntry (0x566520).
562
+ ///
563
+ /// Convention: usercall(EAX=name) + 1 stack(gfx_handler), RET 0x4.
564
+ ///
565
+ /// Looks up a name in the GfxHandler's hash table. Names are case-insensitive.
566
+ /// Supports `|`-separated fallback names (e.g. "path\\file.img|fallback.img").
567
+ ///
568
+ /// Returns entry pointer or null. Entry layout:
569
+ /// - entry+0x00: next pointer (linked list)
570
+ /// - entry+0x04: value (passed to vtable[2] for cached load)
571
+ /// - entry+0x08: unknown
572
+ /// - entry+0x0C: name string (null-terminated, lowercase)
573
+ ///
574
+ /// # Safety
575
+ /// `gfx_handler` must be a valid GfxHandler with initialized hash table at +0x04.
576
+ /// `name` must be a valid null-terminated C string.
577
+ #[cfg(target_arch = "x86")]
578
+ pub unsafe fn gfx_dir_find_entry(
579
+ name: *const u8,
580
+ gfx_handler: *mut u8,
581
+ ) -> *mut u8 {
582
+ let mut current_name = name;
583
+
584
+ loop {
585
+ // Copy name to stack buffer (max 0xFF chars + null)
586
+ let mut buf = [0u8; 0x100];
587
+ let mut i = 0usize;
588
+ let mut src = current_name;
589
+ while *src != 0 && i < 0xFF {
590
+ buf[i] = *src;
591
+ src = src.add(1);
592
+ i += 1;
593
+ }
594
+ buf[i] = 0;
595
+
596
+ // Find '|' separator in buffer
597
+ let mut pipe_pos: Option<usize> = None;
598
+ for j in 0..i {
599
+ if buf[j] == b'|' {
600
+ buf[j] = 0; // truncate at pipe
601
+ pipe_pos = Some(j);
602
+ break;
603
+ }
604
+ }
605
+
606
+ // Compute next_name: pointer into original string after '|'
607
+ let next_name: *const u8 = if let Some(pos) = pipe_pos {
608
+ // Offset of '|' in buffer = pos
609
+ // Same offset in original string β†’ current_name + pos + 1
610
+ current_name.add(pos + 1)
611
+ } else {
612
+ core::ptr::null()
613
+ };
614
+
615
+ // Lowercase A-Z in buffer
616
+ for j in 0..buf.len() {
617
+ if buf[j] == 0 { break; }
618
+ if buf[j] >= b'A' && buf[j] <= b'Z' {
619
+ buf[j] += 0x20;
620
+ }
621
+ }
622
+
623
+ // Hash the lowercased name
624
+ let bucket = gfx_dir_hash(buf.as_ptr());
625
+
626
+ // Walk linked list in hash bucket
627
+ // gfx_handler+4 = pointer to bucket array (1024 entries)
628
+ let bucket_array = *(gfx_handler.add(4) as *const *const u32);
629
+ let mut entry = *bucket_array.add(bucket as usize) as *mut u8;
630
+
631
+ while !entry.is_null() {
632
+ // Compare entry name at entry+0x0C with our buffer
633
+ let entry_name = entry.add(0x0C);
634
+ let mut match_found = true;
635
+ let mut k = 0usize;
636
+ loop {
637
+ let a = *entry_name.add(k);
638
+ let b = buf[k];
639
+ if a != b {
640
+ match_found = false;
641
+ break;
642
+ }
643
+ if a == 0 { break; }
644
+ k += 1;
645
+ }
646
+
647
+ if match_found {
648
+ return entry;
649
+ }
650
+
651
+ // Next in linked list: entry+0x00
652
+ entry = *(entry as *const *mut u8);
653
+ }
654
+
655
+ // Not found β€” try fallback name after '|'
656
+ if next_name.is_null() {
657
+ return core::ptr::null_mut();
658
+ }
659
+ current_name = next_name;
660
+ }
661
+ }
662
+
663
+ /// Pure Rust implementation of FUN_5665F0 (GfxHandler reset).
664
+ ///
665
+ /// Convention: usercall(ESI=handler), plain RET. Called at start of LoadDir.
666
+ unsafe fn gfx_handler_reset(handler: *mut u8) {
667
+ *(handler.add(0x04) as *mut u32) = 0;
668
+ *(handler.add(0x08) as *mut u32) = 0;
669
+ *(handler.add(0x194) as *mut u32) = 0;
670
+
671
+ for i in 0..16u32 {
672
+ // handler+0x0C + i*0x10 = 0 (16 entries at stride 0x10)
673
+ *(handler.add(0x0C + i as usize * 0x10) as *mut u32) = 0;
674
+ // handler+0x10C + i*4 = i (index array)
675
+ *(handler.add(0x10C + i as usize * 4) as *mut u32) = i;
676
+ }
677
+
678
+ *(handler.add(400) as *mut u32) = 0; // 0x190
679
+ *(handler.add(0x18C) as *mut u32) = 0x10;
680
+ }
681
+
682
+ /// Pure Rust implementation of GfxHandler__LoadDir (0x5663E0).
683
+ ///
684
+ /// Convention: usercall(EAX=handler), plain RET. Returns 1 on success, 0 on failure.
685
+ ///
686
+ /// Reads a .dir file through the handler's vtable I/O methods:
687
+ /// - vtable[0]: read(buf, size) β†’ thiscall, returns bytes read
688
+ /// - vtable[1]: seek/reposition(size) β†’ thiscall
689
+ /// - vtable[2]: allocate(size) β†’ thiscall, returns buffer or null
690
+ ///
691
+ /// .dir file format:
692
+ /// - 4 bytes: magic "DIR\x1A" (0x1A524944)
693
+ /// - 4 bytes: total_file_size
694
+ /// - 4 bytes: data_size (hash table + entries)
695
+ /// - data: 1024-bucket hash table followed by linked list nodes
696
+ /// All pointers are relative offsets from (data_start + 4)
697
+ ///
698
+ /// # Safety
699
+ /// `handler` must be a valid GfxHandler with file handle at +0x198.
700
+ #[cfg(target_arch = "x86")]
701
+ pub unsafe fn gfx_handler_load_dir(handler: *mut u8) -> i32 {
702
+ gfx_handler_reset(handler);
703
+
704
+ let vt = *(handler as *const *const u32);
705
+ // vtable[0] = read: thiscall(handler, buf, size) -> bytes_read
706
+ let vt_read: unsafe extern "thiscall" fn(*mut u8, *mut u8, u32) -> u32 =
707
+ core::mem::transmute(*vt);
708
+ // vtable[1] = seek: thiscall(handler, size)
709
+ let vt_seek: unsafe extern "thiscall" fn(*mut u8, u32) =
710
+ core::mem::transmute(*vt.add(1));
711
+ // vtable[2] = allocate: thiscall(handler, size) -> *mut u8
712
+ let vt_alloc: unsafe extern "thiscall" fn(*mut u8, u32) -> *mut u8 =
713
+ core::mem::transmute(*vt.add(2));
714
+
715
+ // Read and validate magic
716
+ let mut magic: u32 = 0;
717
+ if vt_read(handler, &mut magic as *mut u32 as *mut u8, 4) != 4 {
718
+ return 0;
719
+ }
720
+ if magic != 0x1A524944 { // "DIR\x1A"
721
+ return 0;
722
+ }
723
+
724
+ // Read total_file_size and data_size
725
+ let mut total_file_size: u32 = 0;
726
+ if vt_read(handler, &mut total_file_size as *mut u32 as *mut u8, 4) != 4 {
727
+ return 0;
728
+ }
729
+ let mut data_size: u32 = 0;
730
+ if vt_read(handler, &mut data_size as *mut u32 as *mut u8, 4) != 4 {
731
+ return 0;
732
+ }
733
+
734
+ let alloc_size = data_size + 4;
735
+
736
+ // Try fast path: vtable[2] allocate (memory-maps the data)
737
+ let data = vt_alloc(handler, alloc_size);
738
+ *(handler.add(4) as *mut *mut u8) = data;
739
+
740
+ if data.is_null() {
741
+ // Fallback: seek past header, malloc, read entire data block
742
+ vt_seek(handler, alloc_size);
743
+
744
+ let read_size = total_file_size - data_size - 4;
745
+ let buf = wa_malloc(read_size); // WA's malloc, not system
746
+ *(handler.add(4) as *mut *mut u8) = buf;
747
+
748
+ if buf.is_null() {
749
+ return 0;
750
+ }
751
+
752
+ let bytes_read = vt_read(handler, buf, read_size);
753
+ if bytes_read != read_size {
754
+ crate::wa_alloc::wa_free(buf);
755
+ return 0;
756
+ }
757
+
758
+ // Mark as "loaded from fallback" at handler+8
759
+ *(handler.add(8) as *mut u32) = 1;
760
+ }
761
+
762
+ // Fix up relative pointers in the hash table
763
+ // 1024 buckets at data[0..0x1000], each is a pointer to a linked list node
764
+ let data = *(handler.add(4) as *const *mut u8);
765
+ let base = data as u32;
766
+
767
+ for bucket in 0..1024u32 {
768
+ let bucket_ptr = data.add(bucket as usize * 4) as *mut u32;
769
+ let entry_offset = *bucket_ptr;
770
+ if entry_offset == 0 {
771
+ continue;
772
+ }
773
+
774
+ // Convert relative offset to absolute: offset + base - 4
775
+ let entry_addr = entry_offset.wrapping_add(base).wrapping_sub(4);
776
+ *bucket_ptr = entry_addr;
777
+
778
+ // Walk linked list, fix up each next pointer
779
+ let mut node = entry_addr as *mut u32;
780
+ loop {
781
+ if node.is_null() { break; }
782
+ let next_offset = *node;
783
+ if next_offset == 0 { break; }
784
+ let next_addr = next_offset.wrapping_add(base).wrapping_sub(4);
785
+ *node = next_addr;
786
+ node = next_addr as *mut u32;
787
+ }
788
+ }
789
+
790
+ // Mark as loaded
791
+ *(handler.add(0x194) as *mut u32) = 1;
792
+
793
+ 1 // success
794
+ }
795
+
796
  /// Pure Rust implementation of GfxResource__Create_Maybe (0x4F6300).
797
  ///
798
  /// Convention: usercall(ECX=gfx_handler, EAX=name) + 1 stack(output), RET 0x4.
crates/openwa-wormkit/src/replacements/ddgame_init.rs CHANGED
@@ -15,6 +15,7 @@ use openwa_core::address::va;
15
  use openwa_core::engine::ddgame::{
16
  DDGame, ddgame_init_fields, ddgame_init_render_indices,
17
  task_state_machine_init, gfx_resource_create, display_layer_color_init,
 
18
  };
19
  use openwa_core::engine::DDGameWrapper;
20
  use crate::hook;
@@ -107,6 +108,39 @@ unsafe extern "C" fn gfx_resource_create_trampoline() {
107
  );
108
  }
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  // ─── Hook installation ──────────────────────────────────────────────────────
111
 
112
  pub fn install() -> Result<(), String> {
@@ -140,6 +174,12 @@ pub fn install() -> Result<(), String> {
140
  va::FUN_570E20,
141
  display_layer_init_trampoline as *const (),
142
  )?;
 
 
 
 
 
 
143
  }
144
 
145
  Ok(())
 
15
  use openwa_core::engine::ddgame::{
16
  DDGame, ddgame_init_fields, ddgame_init_render_indices,
17
  task_state_machine_init, gfx_resource_create, display_layer_color_init,
18
+ gfx_dir_find_entry,
19
  };
20
  use openwa_core::engine::DDGameWrapper;
21
  use crate::hook;
 
108
  );
109
  }
110
 
111
+ // ─── GfxDir__FindEntry (0x566520) ────────────────────────────────────────────
112
+ //
113
+ // Convention: usercall(EAX=name) + 1 stack(gfx_handler), RET 0x4.
114
+
115
+ hook::usercall_trampoline!(
116
+ fn find_entry_trampoline;
117
+ impl_fn = impl_find_entry;
118
+ reg = eax;
119
+ stack_params = 1; ret_bytes = "0x4"
120
+ );
121
+
122
+ static FIND_ENTRY_LOG_COUNT: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
123
+
124
+ extern "cdecl" fn impl_find_entry(name: u32, gfx_handler: u32) -> u32 {
125
+ let result = unsafe {
126
+ gfx_dir_find_entry(name as *const u8, gfx_handler as *mut u8)
127
+ };
128
+ // Log first 20 lookups for debugging
129
+ let count = FIND_ENTRY_LOG_COUNT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
130
+ if count < 20 {
131
+ let name_str = unsafe {
132
+ let p = name as *const u8;
133
+ let mut len = 0;
134
+ while *p.add(len) != 0 && len < 64 { len += 1; }
135
+ core::str::from_utf8_unchecked(core::slice::from_raw_parts(p, len))
136
+ };
137
+ let _ = crate::log_line(&format!(
138
+ "[FindEntry] #{count}: \"{name_str}\" -> 0x{:08X}", result as u32
139
+ ));
140
+ }
141
+ result as u32
142
+ }
143
+
144
  // ─── Hook installation ──────────────────────────────────────────────────────
145
 
146
  pub fn install() -> Result<(), String> {
 
174
  va::FUN_570E20,
175
  display_layer_init_trampoline as *const (),
176
  )?;
177
+
178
+ hook::install(
179
+ "GfxDir__FindEntry",
180
+ va::GFX_DIR_FIND_ENTRY,
181
+ find_entry_trampoline as *const (),
182
+ )?;
183
  }
184
 
185
  Ok(())