-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLithTechTextureMappingScanner.cs
More file actions
1722 lines (1516 loc) · 59.7 KB
/
LithTechTextureMappingScanner.cs
File metadata and controls
1722 lines (1516 loc) · 59.7 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
using System.Globalization;
using System.IO;
using System.Text;
namespace CFRezManager;
internal static class LithTechTextureMappingScanner
{
private const int MaxScanBytes = 512 * 1024;
private const int MaxScanFiles = 5_000;
private const int MaxRawNeedleScanBytes = 8 * 1024 * 1024;
private const int MaxRawNeedleScanFiles = 40_000;
private const int MaxMappingHits = 50;
private const int MaxRawReferenceHits = 50;
private const int MaxGlobalTableCandidates = 40;
private const int MaxShaderMaterialCandidates = 40;
private const int MaxTextureGuesses = 50;
private const int MaxCompanionCandidates = 50;
private static readonly HashSet<string> TextureExtensions = new(StringComparer.OrdinalIgnoreCase)
{
"dtx",
"dds",
"tga",
"png",
"jpg",
"jpeg",
"bmp"
};
private static readonly HashSet<string> PreferredMappingExtensions = new(StringComparer.OrdinalIgnoreCase)
{
"apf",
"cft",
"cfg",
"csv",
"dat",
"fcf",
"ini",
"json",
"lua",
"ref",
"txt",
"xml"
};
private static readonly HashSet<string> ModelReferenceExtensions = new(StringComparer.OrdinalIgnoreCase)
{
".lta",
".ltb",
".ltc",
".dat"
};
private static readonly HashSet<string> TextureReferenceExtensions = new(StringComparer.OrdinalIgnoreCase)
{
".dtx",
".dds",
".tga",
".png",
".jpg",
".jpeg",
".bmp"
};
private static readonly string[] BindingKeywords =
[
"material",
"model",
"skin",
"tex",
"texture"
];
private static readonly string[] UiPathMarkers =
[
"/ui/",
"/ui/scripts/",
"\\ui\\",
"\\ui\\scripts\\"
];
private static readonly HashSet<string> IgnoredSearchTerms = new(StringComparer.OrdinalIgnoreCase)
{
"body",
"default",
"break",
"lod",
"map",
"map2",
"mesh",
"model",
"node",
"object",
"polyhedron",
"rez",
"render",
"rf008",
"skin",
"texture",
"world"
};
public static string WriteReport(
string objPath,
ExplorerItem? root,
IReadOnlyList<LithTechObjExportSource> sources)
{
string outputDirectory = Path.GetDirectoryName(Path.GetFullPath(objPath)) ?? Environment.CurrentDirectory;
string baseName = Path.GetFileNameWithoutExtension(objPath);
if (string.IsNullOrWhiteSpace(baseName))
{
baseName = "model";
}
string reportPath = Path.Combine(outputDirectory, $"{baseName}_mapping_candidates.txt");
List<string> modelNeedles = BuildModelNeedles(sources);
List<string> textureReferences = sources
.SelectMany(source => source.Document.Meshes)
.Select(mesh => mesh.TexturePath)
.Where(path => !string.IsNullOrWhiteSpace(path))
.Select(path => path!)
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase)
.ToList();
List<string> materialHints = sources
.SelectMany(source => source.Document.Meshes)
.SelectMany(mesh => mesh.MaterialHints ?? [])
.Where(hint => !string.IsNullOrWhiteSpace(hint))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(hint => hint, StringComparer.OrdinalIgnoreCase)
.ToList();
List<TextureItem> textures = root is null ? [] : CollectTextureItems(root);
List<TextureGuess> textureGuesses = GuessTexturesByName(textures, modelNeedles, materialHints);
List<TextureItem> siblingTextureCandidates = GuessSiblingTextures(textures, sources);
List<GlobalMappingTableCandidate> allTableCandidates = root is null ? [] : FindGlobalMappingTableCandidates(root);
List<GlobalMappingTableCandidate> globalTableCandidates = allTableCandidates
.Where(candidate => candidate.ModelReferenceCount > 0)
.ToList();
List<GlobalMappingTableCandidate> shaderMaterialCandidates = allTableCandidates
.Where(IsShaderMaterialCandidate)
.ToList();
List<MappingHit> mappingHits = root is null
? []
: FindMappingHits(root, modelNeedles, textureReferences, textureGuesses);
List<RawReferenceHit> rawReferenceHits = root is null
? []
: FindRawReferenceHits(root, sources, modelNeedles);
List<CompanionMappingCandidate> companionCandidates = root is null
? []
: FindCompanionMappingCandidates(root, sources);
List<LikelyMappingCandidate> likelyMappingFiles = SelectLikelyMappingFiles(
rawReferenceHits,
mappingHits,
companionCandidates,
globalTableCandidates);
using var writer = new StreamWriter(reportPath, false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
writer.WriteLine("CF Rez Manager texture mapping candidate report");
writer.WriteLine();
writer.WriteLine($"Sources: {sources.Count.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Meshes: {sources.Sum(source => source.Document.Meshes.Count).ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Decoded texture references: {textureReferences.Count.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Indexed textures: {textures.Count.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Global mapping table candidates: {globalTableCandidates.Count.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Mapping file hits: {mappingHits.Count.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Raw exact model reference hits: {rawReferenceHits.Count.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine();
writer.WriteLine("Source Resources");
foreach (LithTechObjExportSource source in sources)
{
writer.WriteLine($"- {source.ResourcePath}");
}
writer.WriteLine();
writer.WriteLine("Most Likely Mapping Files");
if (likelyMappingFiles.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (LikelyMappingCandidate candidate in likelyMappingFiles)
{
writer.WriteLine($"- score {candidate.Score.ToString(CultureInfo.InvariantCulture)}: {candidate.Path}");
writer.WriteLine($" Reason: {candidate.Reason}");
}
}
writer.WriteLine();
writer.WriteLine("Model Search Terms");
if (modelNeedles.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (string needle in modelNeedles.Take(128))
{
writer.WriteLine($"- {needle}");
}
if (modelNeedles.Count > 128)
{
writer.WriteLine($"- ... {modelNeedles.Count - 128} more");
}
}
writer.WriteLine();
writer.WriteLine("Direct Texture References");
if (textureReferences.Count == 0)
{
writer.WriteLine("- <none found in decoded model meshes>");
}
else
{
foreach (string reference in textureReferences)
{
writer.WriteLine($"- {reference}");
}
}
writer.WriteLine();
writer.WriteLine("Material Hints From Model");
if (materialHints.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (string hint in materialHints.Take(100))
{
writer.WriteLine($"- {hint}");
}
}
writer.WriteLine();
writer.WriteLine("Texture Name Guesses");
if (textureGuesses.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (TextureGuess guess in textureGuesses.Take(MaxTextureGuesses))
{
writer.WriteLine($"- score {guess.Score.ToString(CultureInfo.InvariantCulture)}: {guess.Texture.Path}");
}
}
writer.WriteLine();
writer.WriteLine("Sibling Directory Texture Candidates");
if (siblingTextureCandidates.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (TextureItem texture in siblingTextureCandidates.Take(100))
{
writer.WriteLine($"- {texture.Path}");
}
}
writer.WriteLine();
writer.WriteLine("Likely Global Mapping Tables");
if (globalTableCandidates.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (GlobalMappingTableCandidate candidate in globalTableCandidates)
{
writer.WriteLine($"- score {candidate.Score.ToString(CultureInfo.InvariantCulture)}: {candidate.Path}");
writer.WriteLine($" Models: {candidate.ModelReferenceCount.ToString(CultureInfo.InvariantCulture)}, Textures: {candidate.TextureReferenceCount.ToString(CultureInfo.InvariantCulture)}, Keywords: {candidate.KeywordCount.ToString(CultureInfo.InvariantCulture)}");
if (candidate.ModelSamples.Count > 0)
{
writer.WriteLine($" Model refs: {string.Join(", ", candidate.ModelSamples.Take(5))}");
}
if (candidate.TextureSamples.Count > 0)
{
writer.WriteLine($" Texture refs: {string.Join(", ", candidate.TextureSamples.Take(5))}");
}
}
}
writer.WriteLine();
writer.WriteLine("Likely Shader Or Material Configs");
if (shaderMaterialCandidates.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (GlobalMappingTableCandidate candidate in shaderMaterialCandidates)
{
writer.WriteLine($"- score {candidate.Score.ToString(CultureInfo.InvariantCulture)}: {candidate.Path}");
writer.WriteLine($" Textures: {candidate.TextureReferenceCount.ToString(CultureInfo.InvariantCulture)}, Keywords: {candidate.KeywordCount.ToString(CultureInfo.InvariantCulture)}");
if (candidate.TextureSamples.Count > 0)
{
writer.WriteLine($" Texture refs: {string.Join(", ", candidate.TextureSamples.Take(8))}");
}
}
}
writer.WriteLine();
writer.WriteLine("Raw Exact Model Reference Hits");
if (rawReferenceHits.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (RawReferenceHit hit in rawReferenceHits)
{
writer.WriteLine($"- score {hit.Score.ToString(CultureInfo.InvariantCulture)}: {hit.Path}");
writer.WriteLine($" Matched model terms: {string.Join(", ", hit.MatchedModelTerms.Take(16))}");
if (hit.ModelReferences.Count > 0)
{
writer.WriteLine($" Model refs: {string.Join(", ", hit.ModelReferences.Take(8))}");
}
if (hit.TextureReferences.Count > 0)
{
writer.WriteLine($" Texture refs: {string.Join(", ", hit.TextureReferences.Take(12))}");
}
if (!string.IsNullOrWhiteSpace(hit.Snippet))
{
writer.WriteLine($" Snippet: {hit.Snippet}");
}
}
}
writer.WriteLine();
writer.WriteLine("Companion Mapping Files Near Source");
if (companionCandidates.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (CompanionMappingCandidate candidate in companionCandidates)
{
writer.WriteLine($"- score {candidate.Score.ToString(CultureInfo.InvariantCulture)}: {candidate.Path}");
if (candidate.ModelReferences.Count > 0)
{
writer.WriteLine($" Model refs: {string.Join(", ", candidate.ModelReferences.Take(8))}");
}
if (candidate.TextureReferences.Count > 0)
{
writer.WriteLine($" Texture refs: {string.Join(", ", candidate.TextureReferences.Take(12))}");
}
}
}
writer.WriteLine();
writer.WriteLine("Mapping Candidate Files");
if (mappingHits.Count == 0)
{
writer.WriteLine("- <none>");
}
else
{
foreach (MappingHit hit in mappingHits)
{
writer.WriteLine($"- {hit.Path}");
writer.WriteLine($" Matched model terms: {string.Join(", ", hit.MatchedModelTerms.Take(16))}");
if (hit.MatchedTextureTerms.Count > 0)
{
writer.WriteLine($" Matched texture terms: {string.Join(", ", hit.MatchedTextureTerms.Take(16))}");
}
if (!string.IsNullOrWhiteSpace(hit.Snippet))
{
writer.WriteLine($" Snippet: {hit.Snippet}");
}
}
}
writer.WriteLine();
writer.WriteLine("How to read this report:");
writer.WriteLine("- If direct texture references are empty, the model format parser did not find texture paths inside the model.");
writer.WriteLine("- Likely global mapping tables are ranked by files that mention both model-like resources and texture-like resources.");
writer.WriteLine("- Shader/material configs may only mention texture resources; these are separated from full model-to-texture tables.");
writer.WriteLine("- Raw exact model reference hits search file bytes for exact model terms before text decoding; these are strong mapping-table suspects.");
writer.WriteLine("- Companion files are small config/table-like files near the selected model path and may hold local material bindings.");
writer.WriteLine("- If mapping candidate files mention both model terms and texture terms, those files are likely the external binding tables.");
writer.WriteLine("- If texture guesses look correct but no mapping file hits appear, the binding may be packed in an unsupported binary table.");
return reportPath;
}
private static List<LikelyMappingCandidate> SelectLikelyMappingFiles(
IReadOnlyList<RawReferenceHit> rawReferenceHits,
IReadOnlyList<MappingHit> mappingHits,
IReadOnlyList<CompanionMappingCandidate> companionCandidates,
IReadOnlyList<GlobalMappingTableCandidate> globalTableCandidates)
{
var candidates = new List<LikelyMappingCandidate>();
foreach (RawReferenceHit hit in rawReferenceHits)
{
int score = 180 + hit.Score;
string reason = hit.TextureReferences.Count > 0
? "exact model-name byte hit with texture references"
: "exact model-name byte hit";
if (hit.TextureReferences.Count > 0)
{
score += 120;
}
candidates.Add(new LikelyMappingCandidate(hit.Path, score, reason));
}
foreach (MappingHit hit in mappingHits)
{
int score = 140 + hit.MatchedModelTerms.Count * 10 + hit.MatchedTextureTerms.Count * 30;
string reason = hit.MatchedTextureTerms.Count > 0
? "decoded text mentions model terms and likely texture names"
: "decoded text mentions model terms";
candidates.Add(new LikelyMappingCandidate(hit.Path, score, reason));
}
foreach (CompanionMappingCandidate candidate in companionCandidates)
{
int score = 110 + candidate.Score;
string reason = candidate.TextureReferences.Count > 0
? "near the source model and contains texture references"
: "near the source model and looks like a config/table file";
candidates.Add(new LikelyMappingCandidate(candidate.Path, score, reason));
}
foreach (GlobalMappingTableCandidate candidate in globalTableCandidates)
{
candidates.Add(new LikelyMappingCandidate(
candidate.Path,
90 + candidate.Score,
"global table-like file with model and texture resource references"));
}
return candidates
.GroupBy(candidate => candidate.Path, StringComparer.OrdinalIgnoreCase)
.Select(group => group.OrderByDescending(candidate => candidate.Score).First())
.OrderByDescending(candidate => candidate.Score)
.ThenBy(candidate => candidate.Path, StringComparer.OrdinalIgnoreCase)
.Take(12)
.ToList();
}
private static List<string> BuildModelNeedles(IReadOnlyList<LithTechObjExportSource> sources)
{
var terms = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (LithTechObjExportSource source in sources)
{
AddNameTerms(source.Name, terms);
AddPathTerms(source.ResourcePath, terms);
AddNameTerms(source.Document.Name, terms);
foreach (LithTechMesh mesh in source.Document.Meshes)
{
AddNameTerms(mesh.Name, terms);
}
}
return terms
.Where(IsUsefulSearchTerm)
.OrderByDescending(term => term.Length)
.ThenBy(term => term, StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static void AddNameTerms(string? name, HashSet<string> terms)
{
if (string.IsNullOrWhiteSpace(name))
{
return;
}
string withoutExtension = NormalizeSearchTerm(Path.GetFileNameWithoutExtension(name));
if (!string.IsNullOrWhiteSpace(withoutExtension) && IsUsefulSearchTerm(withoutExtension))
{
terms.Add(withoutExtension);
}
foreach (string token in SplitNameTokens(name))
{
if (IsUsefulSearchTerm(token))
{
terms.Add(token);
}
}
}
private static void AddPathTerms(string? path, HashSet<string> terms)
{
if (string.IsNullOrWhiteSpace(path))
{
return;
}
string normalized = path.Replace('\\', '/');
AddNameTerms(Path.GetFileNameWithoutExtension(normalized), terms);
foreach (string part in normalized.Split('/', StringSplitOptions.RemoveEmptyEntries))
{
if (part.Contains('.', StringComparison.Ordinal))
{
continue;
}
AddNameTerms(part, terms);
}
}
private static List<TextureItem> CollectTextureItems(ExplorerItem root)
{
var textures = new List<TextureItem>();
CollectTextureItems(root, textures);
return textures
.OrderBy(texture => texture.Path, StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static void CollectTextureItems(ExplorerItem item, List<TextureItem> textures)
{
if (item.IsFile && TextureExtensions.Contains(item.FileExtension))
{
string path = string.IsNullOrWhiteSpace(item.OutputRelativePath)
? item.Name
: item.OutputRelativePath;
textures.Add(new TextureItem(path.Replace('\\', '/'), Path.GetFileNameWithoutExtension(item.Name)));
}
foreach (ExplorerItem child in item.Children)
{
CollectTextureItems(child, textures);
}
}
private static List<TextureGuess> GuessTexturesByName(
IReadOnlyList<TextureItem> textures,
IReadOnlyList<string> modelNeedles,
IReadOnlyList<string> materialHints)
{
var modelTokens = new HashSet<string>(
modelNeedles
.SelectMany(SplitNameTokens)
.Concat(modelNeedles)
.Concat(materialHints)
.Concat(materialHints.SelectMany(SplitNameTokens))
.Where(IsUsefulSearchTerm),
StringComparer.OrdinalIgnoreCase);
return textures
.Select(texture =>
{
int score = SplitNameTokens(texture.Path)
.Count(token => IsUsefulSearchTerm(token) && modelTokens.Contains(token));
return new TextureGuess(texture, score);
})
.Where(guess => guess.Score > 0)
.OrderByDescending(guess => guess.Score)
.ThenBy(guess => guess.Texture.Path, StringComparer.OrdinalIgnoreCase)
.Take(MaxTextureGuesses)
.ToList();
}
private static List<TextureItem> GuessSiblingTextures(
IReadOnlyList<TextureItem> textures,
IReadOnlyList<LithTechObjExportSource> sources)
{
var sourceDirectories = sources
.Select(source => NormalizeDirectory(source.ResourcePath))
.Where(directory => !string.IsNullOrWhiteSpace(directory))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
if (sourceDirectories.Count == 0)
{
return [];
}
return textures
.Where(texture => sourceDirectories.Any(directory =>
NormalizeDirectory(texture.Path).Equals(directory, StringComparison.OrdinalIgnoreCase)))
.OrderBy(texture => texture.Path, StringComparer.OrdinalIgnoreCase)
.Take(200)
.ToList();
}
private static string NormalizeDirectory(string path)
{
string normalized = path.Replace('\\', '/');
int slash = normalized.LastIndexOf('/');
return slash < 0 ? string.Empty : normalized[..slash];
}
private static List<MappingHit> FindMappingHits(
ExplorerItem root,
IReadOnlyList<string> modelNeedles,
IReadOnlyList<string> textureReferences,
IReadOnlyList<TextureGuess> textureGuesses)
{
var hits = new List<MappingHit>();
int scannedFiles = 0;
foreach (ExplorerItem item in GetMappingCandidates(root, modelNeedles))
{
if (hits.Count >= MaxMappingHits || scannedFiles >= MaxScanFiles)
{
break;
}
scannedFiles++;
string? searchableText = TryReadSearchableText(item);
if (string.IsNullOrWhiteSpace(searchableText))
{
continue;
}
List<string> matchedModelTerms = FindMatches(searchableText, modelNeedles, maxMatches: 24);
if (matchedModelTerms.Count == 0)
{
continue;
}
List<string> textureTerms = textureReferences
.Concat(textureGuesses.Select(guess => guess.Texture.Name))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Where(term => !string.IsNullOrWhiteSpace(term))
.ToList();
List<string> matchedTextureTerms = FindMatches(searchableText, textureTerms, maxMatches: 24);
hits.Add(new MappingHit(
string.IsNullOrWhiteSpace(item.OutputRelativePath) ? item.Name : item.OutputRelativePath,
matchedModelTerms,
matchedTextureTerms,
CreateSnippet(searchableText, matchedModelTerms[0])));
}
return hits
.OrderByDescending(hit => hit.MatchedTextureTerms.Count)
.ThenByDescending(hit => hit.MatchedModelTerms.Count)
.ThenBy(hit => hit.Path, StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static List<RawReferenceHit> FindRawReferenceHits(
ExplorerItem root,
IReadOnlyList<LithTechObjExportSource> sources,
IReadOnlyList<string> modelNeedles)
{
List<string> exactNeedles = BuildRawExactNeedles(sources, modelNeedles);
if (exactNeedles.Count == 0)
{
return [];
}
var sourcePaths = new HashSet<string>(
sources.Select(source => NormalizeReference(source.ResourcePath)),
StringComparer.OrdinalIgnoreCase);
var hits = new List<RawReferenceHit>();
int scannedFiles = 0;
foreach (ExplorerItem item in EnumerateFiles(root))
{
if (scannedFiles >= MaxRawNeedleScanFiles)
{
break;
}
string path = string.IsNullOrWhiteSpace(item.OutputRelativePath) ? item.Name : item.OutputRelativePath;
if (sourcePaths.Contains(NormalizeReference(path)) || !ShouldScanRawReferenceCandidate(item))
{
continue;
}
scannedFiles++;
byte[]? data = TryReadItemBytes(item, MaxRawNeedleScanBytes);
if (data is null || data.Length == 0)
{
continue;
}
List<string> matchedTerms = FindRawNeedleMatches(data, exactNeedles, maxMatches: 24);
if (matchedTerms.Count == 0)
{
continue;
}
string? searchableText = TryBuildSearchText(data);
List<string> textureReferences = searchableText is null
? []
: ExtractResourceReferences(searchableText, TextureReferenceExtensions)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(40)
.ToList();
List<string> modelReferences = searchableText is null
? []
: ExtractResourceReferences(searchableText, ModelReferenceExtensions)
.Where(reference => !LooksLikeNavigationOrWorldOnlyReference(reference))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(40)
.ToList();
int keywordCount = searchableText is null
? 0
: BindingKeywords.Count(keyword => searchableText.Contains(keyword, StringComparison.OrdinalIgnoreCase));
int score = CalculateRawReferenceScore(path, item.FileExtension, matchedTerms, modelReferences.Count, textureReferences.Count, keywordCount);
string snippet = searchableText is null ? string.Empty : CreateBestSnippet(searchableText, matchedTerms);
hits.Add(new RawReferenceHit(
path,
score,
matchedTerms,
modelReferences,
textureReferences,
snippet));
}
return hits
.OrderByDescending(hit => hit.Score)
.ThenByDescending(hit => hit.TextureReferences.Count)
.ThenByDescending(hit => hit.ModelReferences.Count)
.ThenBy(hit => hit.Path, StringComparer.OrdinalIgnoreCase)
.Take(MaxRawReferenceHits)
.ToList();
}
private static List<string> BuildRawExactNeedles(
IReadOnlyList<LithTechObjExportSource> sources,
IReadOnlyList<string> modelNeedles)
{
var needles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string needle in modelNeedles)
{
if (needle.Contains('_', StringComparison.Ordinal) ||
needle.Contains('-', StringComparison.Ordinal) ||
needle.Contains('.', StringComparison.Ordinal))
{
AddRawNeedle(needle, needles);
}
}
foreach (LithTechObjExportSource source in sources)
{
AddRawNeedle(source.Name, needles);
AddRawNeedle(source.Document.Name, needles);
AddRawNeedle(Path.GetFileNameWithoutExtension(source.ResourcePath), needles);
AddRawNeedle(source.ResourcePath, needles);
AddRawNeedle(source.ResourcePath.Replace('\\', '/'), needles);
AddRawNeedle(source.ResourcePath.Replace('/', '\\'), needles);
string withoutExtension = Path.ChangeExtension(source.ResourcePath, null) ?? string.Empty;
AddRawNeedle(withoutExtension, needles);
AddRawNeedle(withoutExtension.Replace('\\', '/'), needles);
AddRawNeedle(withoutExtension.Replace('/', '\\'), needles);
}
return needles
.Where(needle => needle.Length >= 5)
.OrderByDescending(needle => needle.Length)
.ThenBy(needle => needle, StringComparer.OrdinalIgnoreCase)
.Take(64)
.ToList();
}
private static void AddRawNeedle(string? value, HashSet<string> needles)
{
if (string.IsNullOrWhiteSpace(value))
{
return;
}
string normalized = NormalizeSearchTerm(value.Trim().Trim('"', '\''));
if (normalized.Length < 5)
{
return;
}
if (IsUsefulSearchTerm(normalized) || normalized.Contains('/') || normalized.Contains('\\') || normalized.Contains('.'))
{
needles.Add(normalized);
}
}
private static bool ShouldScanRawReferenceCandidate(ExplorerItem item)
{
if (!item.IsFile)
{
return false;
}
string extension = item.FileExtension;
if (TextureExtensions.Contains(extension) ||
string.Equals(extension, "bank", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "dds", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "dtx", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "gif", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "jpg", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "jpeg", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "lta", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "ltb", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "ltc", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "ogg", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "png", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "tga", StringComparison.OrdinalIgnoreCase) ||
string.Equals(extension, "wav", StringComparison.OrdinalIgnoreCase))
{
return false;
}
string path = string.IsNullOrWhiteSpace(item.OutputRelativePath) ? item.Name : item.OutputRelativePath;
if (LooksLikeInstallerOrManifestPath(path))
{
return false;
}
long? byteCount = GetItemByteCount(item);
if (byteCount is not (> 0 and <= MaxRawNeedleScanBytes))
{
return false;
}
return PreferredMappingExtensions.Contains(extension) ||
string.IsNullOrWhiteSpace(extension) ||
LooksLikeMappingPath(path);
}
private static List<string> FindRawNeedleMatches(byte[] data, IReadOnlyList<string> needles, int maxMatches)
{
var matches = new List<string>();
foreach (string needle in needles)
{
if (ContainsAsciiIgnoreCase(data, needle))
{
matches.Add(needle);
if (matches.Count >= maxMatches)
{
break;
}
}
}
return matches;
}
private static bool ContainsAsciiIgnoreCase(byte[] data, string needle)
{
if (needle.Length == 0 || data.Length < needle.Length)
{
return false;
}
byte[] needleBytes = Encoding.ASCII.GetBytes(needle);
for (int index = 0; index <= data.Length - needleBytes.Length; index++)
{
if (AsciiEqualsIgnoreCase(data, index, needleBytes))
{
return true;
}
}
return false;
}
private static bool AsciiEqualsIgnoreCase(byte[] data, int dataOffset, byte[] needle)
{
for (int index = 0; index < needle.Length; index++)
{
byte left = ToAsciiLower(data[dataOffset + index]);
byte right = ToAsciiLower(needle[index]);
if (left != right)
{
return false;
}
}
return true;
}
private static byte ToAsciiLower(byte value)
{
return value is >= (byte)'A' and <= (byte)'Z'
? (byte)(value + 32)
: value;
}
private static int CalculateRawReferenceScore(
string path,
string extension,
IReadOnlyList<string> matchedTerms,
int modelReferenceCount,
int textureReferenceCount,
int keywordCount)
{
int score = matchedTerms.Sum(term => Math.Min(term.Length, 80)) +
Math.Min(modelReferenceCount, 20) * 8 +
Math.Min(textureReferenceCount, 30) * 12 +
keywordCount * 10;
if (PreferredMappingExtensions.Contains(extension))
{
score += 40;
}
if (LooksLikeMappingPath(path))
{
score += 30;
}
if (LooksLikeUiOnlyPath(path))
{
score -= 80;
}
return score;
}
private static List<CompanionMappingCandidate> FindCompanionMappingCandidates(
ExplorerItem root,
IReadOnlyList<LithTechObjExportSource> sources)
{
var sourceDirectoryScopes = new HashSet<string>(
sources.SelectMany(source => EnumerateSourceDirectoryScopes(source.ResourcePath)),
StringComparer.OrdinalIgnoreCase);
if (sourceDirectoryScopes.Count == 0)
{
return [];
}
var candidates = new List<CompanionMappingCandidate>();
foreach (ExplorerItem item in EnumerateFiles(root))
{
if (!ShouldScanCompanionCandidate(item))
{
continue;
}
string path = string.IsNullOrWhiteSpace(item.OutputRelativePath) ? item.Name : item.OutputRelativePath;
string directory = NormalizeDirectory(path);
if (!sourceDirectoryScopes.Contains(directory))
{
continue;
}
string? searchableText = TryReadRawSearchText(item);
if (string.IsNullOrWhiteSpace(searchableText))
{
continue;
}
List<string> modelReferences = ExtractResourceReferences(searchableText, ModelReferenceExtensions)
.Where(reference => !LooksLikeNavigationOrWorldOnlyReference(reference))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(40)
.ToList();
List<string> textureReferences = ExtractResourceReferences(searchableText, TextureReferenceExtensions)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(40)
.ToList();
int keywordCount = BindingKeywords.Count(keyword => searchableText.Contains(keyword, StringComparison.OrdinalIgnoreCase));
int score = CalculateCompanionScore(path, item.FileExtension, modelReferences.Count, textureReferences.Count, keywordCount);
if (score <= 0)
{
continue;
}
candidates.Add(new CompanionMappingCandidate(path, score, modelReferences, textureReferences));
}
return candidates
.OrderByDescending(candidate => candidate.Score)
.ThenByDescending(candidate => candidate.TextureReferences.Count)
.ThenBy(candidate => candidate.Path, StringComparer.OrdinalIgnoreCase)
.Take(MaxCompanionCandidates)
.ToList();
}
private static IEnumerable<string> EnumerateSourceDirectoryScopes(string resourcePath)
{
string directory = NormalizeDirectory(resourcePath);
for (int depth = 0; depth < 3 && !string.IsNullOrWhiteSpace(directory); depth++)
{
yield return directory;
int slash = directory.LastIndexOf('/');
if (slash <= 0)
{
break;
}
directory = directory[..slash];
}
}
private static bool ShouldScanCompanionCandidate(ExplorerItem item)
{
if (!item.IsFile)
{
return false;
}