-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLithTechObjExportCommand.cs
More file actions
718 lines (626 loc) · 25.1 KB
/
LithTechObjExportCommand.cs
File metadata and controls
718 lines (626 loc) · 25.1 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
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Media;
namespace CFRezManager;
internal static class LithTechObjExportCommand
{
private const int MaxObjModelBytes = 128 * 1024 * 1024;
private const int MaxObjWorldDatBytes = 256 * 1024 * 1024;
private readonly record struct ModelObjExportJob(ExplorerItem Item, string RelativePath);
private sealed record Options(string SourceRoot, string ModelQuery, string OutputPath);
public static bool IsInvocation(string[] args)
{
return args.Any(arg =>
string.Equals(arg, "--export-obj", StringComparison.OrdinalIgnoreCase) ||
string.Equals(arg, "export-obj", StringComparison.OrdinalIgnoreCase));
}
public static int Run(string[] args)
{
try
{
Options options = ParseOptions(args);
LithTechObjExportResult result = Export(options, out string mappingReportPath, out int skippedCount);
string summaryPath = Path.Combine(
Path.GetDirectoryName(result.ObjPath) ?? Environment.CurrentDirectory,
$"{Path.GetFileNameWithoutExtension(result.ObjPath)}_cli_export_result.txt");
WriteSummary(summaryPath, options, result, mappingReportPath, skippedCount);
Console.WriteLine($"OBJ: {result.ObjPath}");
Console.WriteLine($"Texture report: {result.TextureReportPath}");
Console.WriteLine($"Mapping report: {mappingReportPath}");
Console.WriteLine($"Summary: {summaryPath}");
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
}
private static Options ParseOptions(string[] args)
{
string? sourceRoot = null;
string? modelQuery = null;
string? outputPath = null;
for (int index = 0; index < args.Length; index++)
{
string arg = args[index];
if (string.Equals(arg, "--export-obj", StringComparison.OrdinalIgnoreCase) ||
string.Equals(arg, "export-obj", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (TryReadOptionValue(args, ref index, "--source-root", out string? sourceRootValue) ||
TryReadOptionValue(args, ref index, "--root", out sourceRootValue))
{
sourceRoot = sourceRootValue;
continue;
}
if (TryReadOptionValue(args, ref index, "--model", out string? modelValue) ||
TryReadOptionValue(args, ref index, "--query", out modelValue))
{
modelQuery = modelValue;
continue;
}
if (TryReadOptionValue(args, ref index, "--output", out string? outputValue) ||
TryReadOptionValue(args, ref index, "-o", out outputValue))
{
outputPath = outputValue;
continue;
}
if (modelQuery is null)
{
modelQuery = arg;
}
else if (outputPath is null)
{
outputPath = arg;
}
}
UserSettings settings = UserSettings.Load();
sourceRoot ??= Directory.Exists(settings.LastRezDirectory)
? settings.LastRezDirectory
: settings.LastDirectory;
if (string.IsNullOrWhiteSpace(sourceRoot) || !Directory.Exists(sourceRoot))
{
throw new InvalidOperationException("Missing --source-root, and no saved resource root directory is available.");
}
if (string.IsNullOrWhiteSpace(modelQuery))
{
throw new InvalidOperationException("Missing --model <model name or resource path>.");
}
if (string.IsNullOrWhiteSpace(outputPath))
{
string outputDirectory = Directory.Exists(settings.LastOutputDirectory)
? settings.LastOutputDirectory
: Environment.CurrentDirectory;
outputPath = Path.Combine(outputDirectory, $"{SanitizePathSegment(Path.GetFileNameWithoutExtension(modelQuery))}.obj");
}
return new Options(Path.GetFullPath(sourceRoot), modelQuery, Path.GetFullPath(outputPath));
}
private static bool TryReadOptionValue(string[] args, ref int index, string optionName, out string? value)
{
value = null;
string arg = args[index];
if (!string.Equals(arg, optionName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (index + 1 >= args.Length)
{
throw new InvalidOperationException($"Missing value for {optionName}.");
}
index++;
value = args[index];
return true;
}
private static LithTechObjExportResult Export(
Options options,
out string mappingReportPath,
out int skippedCount)
{
ExplorerItem root = BuildDirectoryTree(options.SourceRoot);
LoadAllArchives(root);
List<ExplorerItem> matches = FindModelItems(root, options.ModelQuery);
if (matches.Count == 0)
{
throw new InvalidOperationException($"No model matched '{options.ModelQuery}'.");
}
if (matches.Count > 50)
{
throw new InvalidOperationException($"Model query matched {matches.Count.ToString(CultureInfo.InvariantCulture)} files; use a more specific path.");
}
Func<string, ImageSource?>? globalTextureResolver = LithTechModelTextureLoader.CreateGlobalResolver(root);
Func<IEnumerable<string>, IReadOnlyList<string>>? textureConfigResolver = LithTechModelTextureConfigIndex.CreateResolver(root);
var sources = new List<LithTechObjExportSource>();
skippedCount = 0;
foreach (ModelObjExportJob job in BuildModelObjExportJobs(matches))
{
if (TryLoadModelDocument(job.Item, out LithTechModelDocument? document, out _) &&
document is not null)
{
sources.Add(new LithTechObjExportSource(
CreateObjSourceName(job),
GetObjSourceResourcePath(job.Item),
document,
CreateObjTextureResolver(job.Item, globalTextureResolver),
textureConfigResolver));
}
else
{
skippedCount++;
}
}
if (sources.Count == 0)
{
throw new InvalidOperationException("Matched files were found, but no model could be decoded for OBJ export.");
}
LithTechObjExportResult result = LithTechObjExporter.Export(options.OutputPath, sources);
mappingReportPath = LithTechTextureMappingScanner.WriteReport(result.ObjPath, root, sources);
return result;
}
private static void WriteSummary(
string summaryPath,
Options options,
LithTechObjExportResult result,
string mappingReportPath,
int skippedCount)
{
using var writer = new StreamWriter(summaryPath, false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
writer.WriteLine("CF Rez Manager command-line OBJ export");
writer.WriteLine();
writer.WriteLine($"Source root: {options.SourceRoot}");
writer.WriteLine($"Model query: {options.ModelQuery}");
writer.WriteLine($"OBJ: {result.ObjPath}");
writer.WriteLine($"Texture report: {result.TextureReportPath}");
writer.WriteLine($"Mapping report: {mappingReportPath}");
writer.WriteLine();
writer.WriteLine($"Sources: {result.SourceCount.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Meshes: {result.MeshCount.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Vertices: {result.VertexCount.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Triangles: {result.TriangleCount.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Textures exported: {result.TextureCount.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Missing textures: {result.MissingTextureCount.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Skipped matched files: {skippedCount.ToString(CultureInfo.InvariantCulture)}");
}
private static List<ExplorerItem> FindModelItems(ExplorerItem root, string query)
{
string normalizedQuery = NormalizePath(query);
bool queryLooksLikePath = normalizedQuery.Contains('/', StringComparison.Ordinal);
string queryName = Path.GetFileName(normalizedQuery);
string queryStem = Path.GetFileNameWithoutExtension(queryName);
List<ExplorerItem> modelItems = EnumerateFiles(root)
.Where(item => LithTechModelDecoder.IsCandidate(item.FileExtension) || LithTechWorldDatDecoder.IsCandidate(item.FileExtension))
.ToList();
List<ExplorerItem> exact = modelItems
.Where(item => MatchesModelQuery(item, normalizedQuery, queryName, queryStem, queryLooksLikePath, exact: true))
.ToList();
if (exact.Count > 0)
{
return exact
.OrderBy(item => item.OutputRelativePath, StringComparer.OrdinalIgnoreCase)
.ToList();
}
return modelItems
.Where(item => MatchesModelQuery(item, normalizedQuery, queryName, queryStem, queryLooksLikePath, exact: false))
.OrderBy(item => item.OutputRelativePath, StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static bool MatchesModelQuery(
ExplorerItem item,
string normalizedQuery,
string queryName,
string queryStem,
bool queryLooksLikePath,
bool exact)
{
string path = NormalizePath(string.IsNullOrWhiteSpace(item.OutputRelativePath) ? item.Name : item.OutputRelativePath);
string name = NormalizePath(item.Name);
string stem = Path.GetFileNameWithoutExtension(name);
string pathStem = NormalizePath(Path.ChangeExtension(path, null) ?? path);
if (exact)
{
bool exactPathMatch =
string.Equals(path, normalizedQuery, StringComparison.OrdinalIgnoreCase) ||
path.EndsWith("/" + normalizedQuery, StringComparison.OrdinalIgnoreCase) ||
string.Equals(pathStem, normalizedQuery, StringComparison.OrdinalIgnoreCase);
if (queryLooksLikePath)
{
return exactPathMatch;
}
return exactPathMatch ||
string.Equals(name, queryName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(stem, queryStem, StringComparison.OrdinalIgnoreCase);
}
if (queryLooksLikePath)
{
return path.Contains(normalizedQuery, StringComparison.OrdinalIgnoreCase);
}
return path.Contains(normalizedQuery, StringComparison.OrdinalIgnoreCase) ||
name.Contains(queryName, StringComparison.OrdinalIgnoreCase) ||
(!string.IsNullOrWhiteSpace(queryStem) && stem.Contains(queryStem, StringComparison.OrdinalIgnoreCase));
}
private static IEnumerable<ExplorerItem> EnumerateFiles(ExplorerItem item)
{
if (item.IsFile)
{
yield return item;
}
foreach (ExplorerItem child in item.Children)
{
foreach (ExplorerItem file in EnumerateFiles(child))
{
yield return file;
}
}
}
private static ExplorerItem BuildDirectoryTree(string folder)
{
string rootName = Path.GetFileName(folder.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
if (string.IsNullOrWhiteSpace(rootName))
{
rootName = folder;
}
var root = new ExplorerItem
{
Name = rootName,
Kind = ExplorerItemKind.Directory,
SourcePath = folder,
OutputRelativePath = string.Empty
};
PopulateDirectory(root, folder, folder);
root.SortChildren();
return root;
}
private static void PopulateDirectory(ExplorerItem parent, string folder, string rootFolder)
{
foreach (string directory in SafeEnumerateDirectories(folder))
{
string relativePath = Path.GetRelativePath(rootFolder, directory);
var directoryItem = new ExplorerItem
{
Name = Path.GetFileName(directory),
Kind = ExplorerItemKind.Directory,
SourcePath = directory,
OutputRelativePath = SanitizeRelativePath(relativePath)
};
PopulateDirectory(directoryItem, directory, rootFolder);
if (directoryItem.Children.Count > 0)
{
parent.AddChild(directoryItem);
}
}
foreach (string rezPath in SafeEnumerateRezFiles(folder))
{
parent.AddChild(CreateArchivePlaceholderItem(rezPath, rootFolder));
}
foreach (string filePath in SafeEnumerateResourceFiles(folder))
{
parent.AddChild(CreateLocalFileItem(filePath, rootFolder));
}
}
private static ExplorerItem CreateArchivePlaceholderItem(string rezPath, string rootFolder)
{
string relativePath = Path.ChangeExtension(Path.GetRelativePath(rootFolder, rezPath), null) ?? Path.GetFileNameWithoutExtension(rezPath);
return new ExplorerItem
{
Name = Path.GetFileNameWithoutExtension(rezPath),
Kind = ExplorerItemKind.RezArchive,
SourcePath = rezPath,
OutputRelativePath = SanitizeRelativePath(relativePath),
IsLoaded = false
};
}
private static ExplorerItem CreateLocalFileItem(string filePath, string rootFolder)
{
string relativePath = Path.GetRelativePath(rootFolder, filePath);
return new ExplorerItem
{
Name = Path.GetFileName(filePath),
Kind = ExplorerItemKind.LocalFile,
SourcePath = filePath,
OutputRelativePath = SanitizeRelativePath(relativePath)
};
}
private static ExplorerItem CreateArchiveChildItem(RezNode node, RezArchive archive, string parentOutputPath)
{
string outputRelativePath = CombineRelativePath(parentOutputPath, SanitizePathSegment(node.Name));
if (node is RezDirectoryNode directory)
{
return new ExplorerItem
{
Name = directory.Name,
Kind = ExplorerItemKind.RezDirectory,
SourcePath = archive.FilePath,
OutputRelativePath = outputRelativePath,
Archive = archive,
ArchiveDirectory = directory,
IsLoaded = false
};
}
var file = (RezFileNode)node;
return new ExplorerItem
{
Name = file.Name,
Kind = ExplorerItemKind.RezFile,
SourcePath = archive.FilePath,
OutputRelativePath = outputRelativePath,
Archive = archive,
ArchiveFile = file
};
}
private static IEnumerable<string> SafeEnumerateDirectories(string folder)
{
try
{
return Directory.EnumerateDirectories(folder).ToList();
}
catch
{
return [];
}
}
private static IEnumerable<string> SafeEnumerateRezFiles(string folder)
{
try
{
return Directory.EnumerateFiles(folder)
.Where(file => string.Equals(Path.GetExtension(file), ".rez", StringComparison.OrdinalIgnoreCase))
.ToList();
}
catch
{
return [];
}
}
private static IEnumerable<string> SafeEnumerateResourceFiles(string folder)
{
try
{
return Directory.EnumerateFiles(folder)
.Where(file => !string.Equals(Path.GetExtension(file), ".rez", StringComparison.OrdinalIgnoreCase))
.ToList();
}
catch
{
return [];
}
}
private static void LoadAllArchives(ExplorerItem rootItem)
{
var archives = new List<ExplorerItem>();
CollectArchiveItems(rootItem, archives);
var options = new ParallelOptions
{
MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount / 2, 1, 4)
};
Parallel.ForEach(archives, options, archive =>
{
LoadContainerChildren(archive);
LoadAllRezDirectories(archive);
});
}
private static void CollectArchiveItems(ExplorerItem item, List<ExplorerItem> archives)
{
if (item.Kind == ExplorerItemKind.RezArchive)
{
archives.Add(item);
return;
}
foreach (ExplorerItem child in item.Children)
{
CollectArchiveItems(child, archives);
}
}
private static void LoadAllRezDirectories(ExplorerItem item)
{
foreach (ExplorerItem child in item.Children.ToArray())
{
if (child.Kind == ExplorerItemKind.RezDirectory)
{
LoadContainerChildren(child);
LoadAllRezDirectories(child);
}
}
}
private static void LoadContainerChildren(ExplorerItem item)
{
if (item.IsLoaded)
{
return;
}
if (item.Kind == ExplorerItemKind.RezArchive)
{
var reader = new RezArchiveReader();
RezArchive archive = reader.Read(item.SourcePath);
item.Archive = archive;
item.ArchiveDirectory = archive.Root;
}
if (item.Archive is null || item.ArchiveDirectory is null)
{
item.IsLoaded = true;
return;
}
item.Children.Clear();
foreach (RezNode child in item.ArchiveDirectory.Children)
{
item.AddChild(CreateArchiveChildItem(child, item.Archive, item.OutputRelativePath));
}
item.SortChildren();
item.IsLoaded = true;
}
private static List<ModelObjExportJob> BuildModelObjExportJobs(IEnumerable<ExplorerItem> items)
{
var jobs = new List<ModelObjExportJob>();
var seenItems = new HashSet<ExplorerItem>();
var usedRelativePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ExplorerItem item in LithTechModelPartGrouper.ExpandNumberedSiblingParts(items))
{
string selectedRootPath = item.IsFile
? SanitizePathSegment(Path.GetFileNameWithoutExtension(item.Name))
: SanitizePathSegment(item.Name);
CollectModelObjExportJobs(item, selectedRootPath, jobs, seenItems, usedRelativePaths);
}
return jobs;
}
private static void CollectModelObjExportJobs(
ExplorerItem item,
string relativePath,
List<ModelObjExportJob> jobs,
HashSet<ExplorerItem> seenItems,
HashSet<string> usedRelativePaths)
{
if (item.Kind == ExplorerItemKind.LocalFile ||
item.Kind == ExplorerItemKind.RezFile && item.Archive is not null && item.ArchiveFile is not null)
{
if (LithTechModelDecoder.IsCandidate(item.FileExtension) || LithTechWorldDatDecoder.IsCandidate(item.FileExtension))
{
AddModelObjExportJob(item, relativePath, jobs, seenItems, usedRelativePaths);
}
return;
}
foreach (ExplorerItem child in item.Children)
{
string childRelativePath = CombineRelativePath(relativePath, SanitizePathSegment(child.Name));
CollectModelObjExportJobs(child, childRelativePath, jobs, seenItems, usedRelativePaths);
}
}
private static void AddModelObjExportJob(
ExplorerItem item,
string relativePath,
List<ModelObjExportJob> jobs,
HashSet<ExplorerItem> seenItems,
HashSet<string> usedRelativePaths)
{
if (!seenItems.Add(item))
{
return;
}
string safeRelativePath = string.IsNullOrWhiteSpace(relativePath)
? SanitizePathSegment(Path.GetFileNameWithoutExtension(item.Name))
: relativePath;
string withoutExtension = Path.ChangeExtension(safeRelativePath, null) ?? safeRelativePath;
jobs.Add(new ModelObjExportJob(item, MakeUniqueRelativePath(withoutExtension, usedRelativePaths)));
}
private static string MakeUniqueRelativePath(string relativePath, HashSet<string> usedRelativePaths)
{
if (usedRelativePaths.Add(relativePath))
{
return relativePath;
}
string? directory = Path.GetDirectoryName(relativePath);
string fileName = Path.GetFileNameWithoutExtension(relativePath);
string extension = Path.GetExtension(relativePath);
for (int index = 2; ; index++)
{
string candidateName = $"{fileName} ({index}){extension}";
string candidate = string.IsNullOrEmpty(directory)
? candidateName
: Path.Combine(directory, candidateName);
if (usedRelativePaths.Add(candidate))
{
return candidate;
}
}
}
private static string CreateObjSourceName(ModelObjExportJob job)
{
string name = Path.ChangeExtension(job.RelativePath, null) ?? job.RelativePath;
return name
.Replace(Path.DirectorySeparatorChar, '_')
.Replace(Path.AltDirectorySeparatorChar, '_')
.Replace('/', '_')
.Replace('\\', '_');
}
private static string GetObjSourceResourcePath(ExplorerItem item)
{
return string.IsNullOrWhiteSpace(item.OutputRelativePath)
? item.Name
: item.OutputRelativePath;
}
private static Func<string, ImageSource?>? CreateObjTextureResolver(
ExplorerItem item,
Func<string, ImageSource?>? globalTextureResolver)
{
Func<string, ImageSource?>? primaryResolver = LithTechModelTextureLoader.CreateResolver(item);
if (primaryResolver is null)
{
return globalTextureResolver;
}
if (globalTextureResolver is null)
{
return primaryResolver;
}
return texturePath => primaryResolver(texturePath) ?? globalTextureResolver(texturePath);
}
private static bool TryLoadModelDocument(ExplorerItem item, out LithTechModelDocument? document, out string? errorMessage)
{
document = null;
errorMessage = null;
try
{
string extension = item.FileExtension;
int maxBytes = LithTechWorldDatDecoder.IsCandidate(extension)
? MaxObjWorldDatBytes
: MaxObjModelBytes;
byte[] data = ReadExplorerFileBytes(item, maxBytes);
if (LithTechWorldDatDecoder.IsCandidate(extension))
{
return LithTechWorldDatDecoder.TryDecode(data, item.Name, out document, out errorMessage);
}
return LithTechModelDecoder.TryDecode(data, item.Name, extension, out document, out errorMessage);
}
catch (Exception ex)
{
errorMessage = ex.Message;
return false;
}
}
private static byte[] ReadExplorerFileBytes(ExplorerItem item, int maxBytes)
{
if (item.Kind == ExplorerItemKind.LocalFile)
{
var info = new FileInfo(item.SourcePath);
if (!info.Exists || info.Length < 0 || info.Length > maxBytes || info.Length > int.MaxValue)
{
throw new InvalidOperationException($"File is too large for export: {item.Name}");
}
return File.ReadAllBytes(item.SourcePath);
}
if (item.Archive is null ||
item.ArchiveFile is null ||
item.ArchiveFile.Size < 0 ||
item.ArchiveFile.Size > maxBytes)
{
throw new InvalidOperationException($"File is too large for export: {item.Name}");
}
byte[] data = new byte[item.ArchiveFile.Size];
using FileStream source = File.OpenRead(item.Archive.FilePath);
source.Position = item.ArchiveFile.DataOffset;
source.ReadExactly(data);
return data;
}
private static string SanitizeRelativePath(string relativePath)
{
string[] parts = relativePath.Split([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries);
return Path.Combine(parts.Select(SanitizePathSegment).ToArray());
}
private static string SanitizePathSegment(string value)
{
char[] invalidChars = Path.GetInvalidFileNameChars();
string sanitized = new string(value.Select(ch => invalidChars.Contains(ch) ? '_' : ch).ToArray()).Trim();
return string.IsNullOrWhiteSpace(sanitized) ? "_" : sanitized;
}
private static string CombineRelativePath(string parent, string child)
{
return string.IsNullOrEmpty(parent) ? child : Path.Combine(parent, child);
}
private static string NormalizePath(string value)
{
return value
.Trim()
.Trim('"', '\'')
.Replace('\\', '/')
.TrimStart('/');
}
}