Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ use asynchronous reads and writes for file and stream overloads and pass the can
to the underlying I/O. Parsing, serialization and compression perform synchronous CPU work between I/O operations.
Stream overloads leave the supplied stream open.

`NwcAssembly.LoadFromDirectoryAsync` and `NwcAssembly.OpenNwfAsync` read model files asynchronously
and pass cancellation through to each read. They load models sequentially in the same order as their
synchronous counterparts. Directory discovery and reference resolution use synchronous filesystem metadata.
The `load-models` phase reports each folder model, or the primary NWF and each of its reference entries,
including missing, duplicate and unsupported references.

## Coordination & Clash Detection (`NwcIO.Model.Clash`)

| Type | Description |
Expand Down
82 changes: 57 additions & 25 deletions src/NwcIO/Model/NwcAssembly.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using NwcIO.Internal;
using NwcIO.Internal.Json;

namespace NwcIO.Model;
Expand Down Expand Up @@ -230,7 +231,20 @@ public static NwcAssembly LoadFromDirectory(
NwcReaderOptions? options,
IProgress<NwcProgress>? progress,
CancellationToken cancellationToken)
=> LoadFromDirectoryCore(directoryPath, searchPatterns, recursive, options, progress, asynchronous: false, cancellationToken)
.GetSynchronousResult();

private static async ValueTask<NwcAssembly> LoadFromDirectoryCore(
string directoryPath,
IReadOnlyList<string> searchPatterns,
bool recursive,
NwcReaderOptions? options,
IProgress<NwcProgress>? progress,
bool asynchronous,
CancellationToken cancellationToken)
{
if (asynchronous) cancellationToken.ThrowIfCancellationRequested();

ArgumentNullException.ThrowIfNull(searchPatterns);
if (!Directory.Exists(directoryPath))
{
Expand Down Expand Up @@ -259,12 +273,15 @@ public static NwcAssembly LoadFromDirectory(
for (int i = 0; i < files.Length; i++)
{
cancellationToken.ThrowIfCancellationRequested();
docs.Add(NwcDocument.Open(files[i], options, null, cancellationToken));
docs.Add(await OpenModel(files[i], options, asynchronous, cancellationToken).ConfigureAwait(false));
progress?.Report(new NwcProgress("load-models", i + 1, files.Length));
}

string assemblyName = Path.GetFileName(directoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
return Create(assemblyName, docs);
cancellationToken.ThrowIfCancellationRequested();
var assembly = Create(assemblyName, docs);
cancellationToken.ThrowIfCancellationRequested();
return assembly;
}

/// <summary>
Expand All @@ -282,14 +299,24 @@ public static NwcAssembly OpenNwf(
NwcReaderOptions? options,
IProgress<NwcProgress>? progress,
CancellationToken cancellationToken)
=> OpenNwfCore(nwfPath, options, progress, asynchronous: false, cancellationToken).GetSynchronousResult();

private static async ValueTask<NwcAssembly> OpenNwfCore(
string nwfPath,
NwcReaderOptions? options,
IProgress<NwcProgress>? progress,
bool asynchronous,
CancellationToken cancellationToken)
{
if (asynchronous) cancellationToken.ThrowIfCancellationRequested();

if (!File.Exists(nwfPath))
{
throw new FileNotFoundException($"NWF file not found: {nwfPath}", nwfPath);
}

cancellationToken.ThrowIfCancellationRequested();
var primaryDoc = NwcDocument.Open(nwfPath, options, null, cancellationToken);
var primaryDoc = await OpenModel(nwfPath, options, asynchronous, cancellationToken).ConfigureAwait(false);
var baseDir = Path.GetDirectoryName(Path.GetFullPath(nwfPath)) ?? ".";

var loadedDocs = new List<NwcDocument> { primaryDoc };
Expand All @@ -307,35 +334,31 @@ public static NwcAssembly OpenNwf(
foreach (var xref in primaryDoc.XRefs.References)
{
cancellationToken.ThrowIfCancellationRequested();
// Every reference counts, loaded or not, so Completed reaches Total.
processed++;
if (!xref.TryResolve(baseDir, out string resolved))
{
unresolved.Add(xref);
progress?.Report(new NwcProgress("load-models", processed, total));
continue;
}

// Load every resolved file once, whatever the stored path spelled like.
if (!loadedPaths.Add(Path.GetFullPath(resolved)))
else if (loadedPaths.Add(Path.GetFullPath(resolved)))
{
progress?.Report(new NwcProgress("load-models", processed, total));
continue;
// Load every resolved file once, whatever the stored path spelled like.
if (resolved.EndsWith(".nwc", StringComparison.OrdinalIgnoreCase) ||
resolved.EndsWith(".nwd", StringComparison.OrdinalIgnoreCase))
{
loadedDocs.Add(await OpenModel(resolved, options, asynchronous, cancellationToken).ConfigureAwait(false));
}
else
{
skipped.Add(xref);
}
}

if (!resolved.EndsWith(".nwc", StringComparison.OrdinalIgnoreCase) &&
!resolved.EndsWith(".nwd", StringComparison.OrdinalIgnoreCase))
{
skipped.Add(xref);
progress?.Report(new NwcProgress("load-models", processed, total));
continue;
}

loadedDocs.Add(NwcDocument.Open(resolved, options, null, cancellationToken));
// Every reference counts, including entries that did not load a model.
processed++;
progress?.Report(new NwcProgress("load-models", processed, total));
}
}

cancellationToken.ThrowIfCancellationRequested();
string assemblyName = Path.GetFileNameWithoutExtension(nwfPath);
var assembly = Create(assemblyName, loadedDocs);
assembly.UnresolvedXRefs = unresolved;
Expand All @@ -353,25 +376,34 @@ public static NwcAssembly OpenNwf(
$"Skipped unsupported NWF reference: '{x.EffectivePath}'.")));
assembly.Diagnostics = diagnostics;
}

cancellationToken.ThrowIfCancellationRequested();
return assembly;
}

/// <summary>Loads a folder asynchronously. The current implementation wraps the synchronous loader.</summary>
private static ValueTask<NwcDocument> OpenModel(
string path, NwcReaderOptions? options, bool asynchronous, CancellationToken cancellationToken) =>
asynchronous
? new ValueTask<NwcDocument>(NwcDocument.OpenAsync(path, options, cancellationToken: cancellationToken))
: ValueTask.FromResult(NwcDocument.Open(path, options, progress: null, cancellationToken));

/// <summary>Loads documents in a folder using asynchronous file reads.</summary>
public static Task<NwcAssembly> LoadFromDirectoryAsync(
string directoryPath,
string searchPattern = "*.nwc",
NwcReaderOptions? options = null,
IProgress<NwcProgress>? progress = null,
CancellationToken cancellationToken = default)
=> Task.Run(() => LoadFromDirectory(directoryPath, searchPattern, options, progress, cancellationToken), cancellationToken);
=> LoadFromDirectoryCore(directoryPath, [searchPattern], recursive: false, options, progress,
asynchronous: true, cancellationToken).AsTask();

/// <summary>Opens a .nwf asynchronously. The current implementation wraps the synchronous loader.</summary>
/// <summary>Opens a .nwf and its referenced models using asynchronous file reads.</summary>
public static Task<NwcAssembly> OpenNwfAsync(
string nwfPath,
NwcReaderOptions? options = null,
IProgress<NwcProgress>? progress = null,
CancellationToken cancellationToken = default)
=> Task.Run(() => OpenNwf(nwfPath, options, progress, cancellationToken), cancellationToken);
=> OpenNwfCore(nwfPath, options, progress, asynchronous: true, cancellationToken).AsTask();

/// <summary>
/// Builds a single document that carries the assembly scene tree, meshes with their transforms,
Expand Down
8 changes: 5 additions & 3 deletions tests/NwcIO.Tests/AssemblyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -398,8 +398,10 @@ private static void WriteNwfWithXRefs(string nwfPath, params string[] effectiveP
NwcIO.Internal.Container.NwcContainerWriter.Write(fs, [xrefStream]);
}

[Fact]
public void OpenNwf_ResolvesSubfoldersDeduplicatesAndReportsMissing()
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task OpenNwf_ResolvesSubfoldersDeduplicatesAndReportsMissing(bool asynchronous)
{
string tempDir = Path.Combine(Path.GetTempPath(), "nwcio-nwf-" + Guid.NewGuid().ToString("N"));
string archDir = Path.Combine(tempDir, "Arch");
Expand All @@ -423,7 +425,7 @@ public void OpenNwf_ResolvesSubfoldersDeduplicatesAndReportsMissing()
nowhere + "/Mech/D.nwc", // nowhere to be found: unresolved
"Textures/tex.png"); // resolves but unsupported: skipped

var assembly = NwcAssembly.OpenNwf(nwfPath);
var assembly = asynchronous ? await NwcAssembly.OpenNwfAsync(nwfPath) : NwcAssembly.OpenNwf(nwfPath);

// nwf doc + A, B, C — B must appear once despite two references.
Assert.Equal(4, assembly.Models.Count);
Expand Down
127 changes: 102 additions & 25 deletions tests/NwcIO.Tests/ReaderCancellationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,56 +82,71 @@ public void Open_CanceledAfterReadContainer_StopsBeforeGeometry()
Assert.Equal(["read-container"], progress.Reports.Select(p => p.Phase));
}

[Fact]
public void LoadFromDirectory_CanceledBetweenModels_StopsAfterFirstModel()
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task LoadFromDirectory_CanceledBetweenModels_StopsAfterFirstModel(bool asynchronous)
{
string directory = TempDirectory();
try
{
foreach (var name in new[] { "a.nwc", "b.nwc", "c.nwc" })
{
NwcDocument.Create().Save(Path.Combine(directory, name));
}
NwcDocument.Create().Save(Path.Combine(directory, "a.nwc"));
File.WriteAllText(Path.Combine(directory, "b.nwc"), "Invalid model");
using var cancellation = new CancellationTokenSource();
var progress = new CollectingProgress { OnReport = p => { if (p.Phase == "load-models") cancellation.Cancel(); } };

Assert.Throws<OperationCanceledException>(() =>
NwcAssembly.LoadFromDirectory(directory, "*.nwc", null, progress, cancellation.Token));
var error = await Assert.ThrowsAnyAsync<OperationCanceledException>(() => asynchronous
? NwcAssembly.LoadFromDirectoryAsync(directory, progress: progress, cancellationToken: cancellation.Token)
: Task.FromResult(NwcAssembly.LoadFromDirectory(directory, "*.nwc", null, progress, cancellation.Token)));

Assert.Single(progress.Reports, p => p.Phase == "load-models");
Assert.Equal(cancellation.Token, error.CancellationToken);
Assert.Equal(new NwcProgress("load-models", 1, 2), Assert.Single(progress.Reports));
}
finally
{
Directory.Delete(directory, recursive: true);
}
}

[Fact]
public void OpenNwf_CanceledBetweenReferences_StopsBeforeNextReference()
[Theory]
[InlineData(false, 1)]
[InlineData(false, 2)]
[InlineData(true, 1)]
[InlineData(true, 2)]
public async Task OpenNwf_CanceledBetweenModels_StopsBeforeNextReference(bool asynchronous, int cancelAfter)
{
string directory = TempDirectory();
try
{
string nwf = Path.Combine(directory, "fed.nwf");
WriteNwf(nwf, "missing.nwc", "a.nwc");
WriteNwf(nwf, "a.nwc", "b.nwc");
NwcDocument.Create().Save(Path.Combine(directory, "a.nwc"));
File.WriteAllText(Path.Combine(directory, "b.nwc"), "Invalid model");
using var cancellation = new CancellationTokenSource();
var progress = new CollectingProgress { OnReport = _ => cancellation.Cancel() };
var progress = new CollectingProgress
{
OnReport = report => { if (report.Completed == cancelAfter) cancellation.Cancel(); },
};

Assert.Throws<OperationCanceledException>(() =>
NwcAssembly.OpenNwf(nwf, null, progress, cancellation.Token));
var error = await Assert.ThrowsAnyAsync<OperationCanceledException>(() => asynchronous
? NwcAssembly.OpenNwfAsync(nwf, progress: progress, cancellationToken: cancellation.Token)
: Task.FromResult(NwcAssembly.OpenNwf(nwf, null, progress, cancellation.Token)));

// Only the primary document was reported: the unresolved reference was never visited.
Assert.Single(progress.Reports);
Assert.Equal(cancellation.Token, error.CancellationToken);
Assert.Equal(
Enumerable.Range(1, cancelAfter).Select(completed => new NwcProgress("load-models", completed, 3)),
progress.Reports);
}
finally
{
Directory.Delete(directory, recursive: true);
}
}

[Fact]
public void OpenNwf_ProgressReachesTotalWhenReferencesAreNotLoaded()
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task OpenNwf_ProgressReachesTotalWhenReferencesAreNotLoaded(bool asynchronous)
{
string directory = TempDirectory();
try
Expand All @@ -142,9 +157,11 @@ public void OpenNwf_ProgressReachesTotalWhenReferencesAreNotLoaded()
File.WriteAllText(Path.Combine(directory, "tex.png"), "x");
var progress = new CollectingProgress();

var assembly = NwcAssembly.OpenNwf(nwf, null, progress, CancellationToken.None);
var assembly = asynchronous
? await NwcAssembly.OpenNwfAsync(nwf, progress: progress)
: NwcAssembly.OpenNwf(nwf, null, progress, CancellationToken.None);

Assert.Equal(2, assembly.Models.Count);
Assert.Equal([nwf, Path.Combine(directory, "a.nwc")], assembly.Models.Select(model => model.GetLoadedPath()));
Assert.Single(assembly.UnresolvedXRefs);
Assert.Single(assembly.SkippedXRefs);
Assert.Equal(
Expand Down Expand Up @@ -190,17 +207,77 @@ public async Task OpenAsyncAndSaveAsync_Roundtrip()
}
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task LoadAssemblyAsync_PreCancelled_ReturnsCancelledTask(bool nwf)
{
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
var progress = new CollectingProgress();

var task = nwf
? NwcAssembly.OpenNwfAsync("", progress: progress, cancellationToken: cancellation.Token)
: NwcAssembly.LoadFromDirectoryAsync("", progress: progress, cancellationToken: cancellation.Token);

var error = await Assert.ThrowsAnyAsync<OperationCanceledException>(() => task);
Assert.Equal(cancellation.Token, error.CancellationToken);
Assert.True(task.IsCanceled);
Assert.Empty(progress.Reports);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task LoadAssemblyAsync_CancelledAtLastModel_ReturnsCancelledTask(bool nwf)
{
string directory = TempDirectory();
try
{
string path = Path.Combine(directory, "fed.nwf");
if (nwf)
{
WriteNwf(path);
}
else
{
NwcDocument.Create().Save(Path.Combine(directory, "a.nwc"));
}

using var cancellation = new CancellationTokenSource();
var progress = new CollectingProgress { OnReport = _ => cancellation.Cancel() };
var task = nwf
? NwcAssembly.OpenNwfAsync(path, progress: progress, cancellationToken: cancellation.Token)
: NwcAssembly.LoadFromDirectoryAsync(directory, progress: progress, cancellationToken: cancellation.Token);

await Assert.ThrowsAnyAsync<OperationCanceledException>(() => task);
Assert.True(task.IsCanceled);
Assert.Equal(new NwcProgress("load-models", 1, 1), Assert.Single(progress.Reports));
}
finally
{
Directory.Delete(directory, recursive: true);
}
}

[Fact]
public async Task LoadFromDirectoryAsync_LoadsModels()
public async Task LoadFromDirectoryAsync_LoadsModelsInPathOrder()
{
string directory = TempDirectory();
try
{
NwcDocument.Create().Save(Path.Combine(directory, "a.nwc"));
var b = Path.Combine(directory, "b.nwc");
var a = Path.Combine(directory, "a.nwc");
NwcDocument.Create().Save(b);
NwcDocument.Create().Save(a);
var progress = new CollectingProgress();

var assembly = await NwcAssembly.LoadFromDirectoryAsync(directory);
var assembly = await NwcAssembly.LoadFromDirectoryAsync(directory,
options: new NwcReaderOptions { KeepStreamCatalog = false }, progress: progress);

Assert.Single(assembly.Models);
Assert.Equal([a, b], assembly.Models.Select(model => model.GetLoadedPath()));
Assert.All(assembly.Models, model => Assert.Empty(model.Container.Streams));
Assert.Equal([new NwcProgress("load-models", 1, 2), new NwcProgress("load-models", 2, 2)], progress.Reports);
}
finally
{
Expand Down
Loading