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
7 changes: 7 additions & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ 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.

The document's `SaveObjAsync`, `SaveGlbAsync`, `SaveIfcAsync`, `SaveViewpointsBcfAsync`,
`SaveViewpointsXmlAsync` and `SaveHtmlViewerAsync` accept file paths or streams and a
`CancellationToken`. OBJ and IFC also accept a `TextWriter`. The compatibility formatters
run on a worker thread and forward writes and flushes to the destination's async methods with
the token. Successful path exports replace the destination atomically. Cancellation may leave
partial output in a caller-owned stream or writer, which remains 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.
Expand Down
5 changes: 4 additions & 1 deletion src/NwcIO/Compatibility/Export/BcfExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ public static void WriteViewpointsFile(IReadOnlyList<NwcSavedViewpoint> viewpoin
/// <summary>
/// Writes the saved viewpoints list as a BCF 2.1 (.bcfzip) archive into the provided stream.
/// </summary>
public static void WriteViewpoints(IReadOnlyList<NwcSavedViewpoint> viewpoints, Stream stream, string? assemblyName = null)
public static void WriteViewpoints(
IReadOnlyList<NwcSavedViewpoint> viewpoints, Stream stream, string? assemblyName = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(viewpoints);
ArgumentNullException.ThrowIfNull(stream);
Expand All @@ -79,6 +81,7 @@ public static void WriteViewpoints(IReadOnlyList<NwcSavedViewpoint> viewpoints,
// 2. Per-viewpoint topic folder
for (int i = 0; i < viewpoints.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var vp = viewpoints[i];
string topicGuid = (vp.Id ?? Guid.NewGuid()).ToString("D");
string viewpointGuid = Guid.NewGuid().ToString("D");
Expand Down
184 changes: 184 additions & 0 deletions src/NwcIO/Compatibility/Export/CompatibilityExport.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
using System.Buffers;
using System.Text;

namespace NwcIO.Internal.Export;

internal static class CompatibilityExport
{
private const int ByteBufferSize = 64 * 1024;
private const int TextBufferSize = 4096;

public static Task WriteFileAsync(
string path, Action<Stream> write, CancellationToken cancellationToken) =>
AtomicFileWriter.WriteAsync(path, output => new ValueTask(WriteAsync(output, write, cancellationToken)),
cancellationToken).AsTask();

public static Task WriteAsync(Stream output, Action<Stream> write, CancellationToken cancellationToken) =>
Task.Run(() =>
{
ArgumentNullException.ThrowIfNull(output);

// The legacy formatter runs on a worker. Every destination write still uses cancellable async I/O.
using var destination = new AsyncStream(output, cancellationToken);
write(destination);
destination.Flush();
cancellationToken.ThrowIfCancellationRequested();
}, cancellationToken);

public static Task WriteAsync(TextWriter output, Action<TextWriter> write, CancellationToken cancellationToken) =>
Task.Run(() =>
{
ArgumentNullException.ThrowIfNull(output);
using var destination = new AsyncTextWriter(output, cancellationToken);
write(destination);
destination.Flush();
cancellationToken.ThrowIfCancellationRequested();
}, cancellationToken);

public static void WriteText(Stream stream, Encoding encoding, Action<TextWriter> write)
{
using var writer = new StreamWriter(stream, encoding, ByteBufferSize, leaveOpen: true);
write(writer);
}

private sealed class AsyncStream(Stream output, CancellationToken token) : Stream
{
private byte[]? _buffer;
private bool _failed;

public override void Write(byte[] buffer, int offset, int count) => WriteMemory(buffer.AsMemory(offset, count));

public override void Write(ReadOnlySpan<byte> buffer)
{
if (buffer.IsEmpty) return;

_buffer ??= ArrayPool<byte>.Shared.Rent(ByteBufferSize);
while (!buffer.IsEmpty)
{
int count = Math.Min(buffer.Length, ByteBufferSize);
buffer[..count].CopyTo(_buffer);
WriteMemory(_buffer.AsMemory(0, count));
buffer = buffer[count..];
}
}

private void WriteMemory(ReadOnlyMemory<byte> buffer)
{
// StreamWriter and ZipArchive can attempt more writes while unwinding a failure.
if (_failed) return;
token.ThrowIfCancellationRequested();
try
{
output.WriteAsync(buffer, token).AsTask().GetAwaiter().GetResult();
}
catch
{
_failed = true;
throw;
}
}

public override void Flush()
{
if (_failed) return;
token.ThrowIfCancellationRequested();
try
{
output.FlushAsync(token).GetAwaiter().GetResult();
}
catch
{
_failed = true;
throw;
}
}

public override bool CanRead => false;
public override bool CanSeek => output.CanSeek;
public override bool CanWrite => output.CanWrite;
public override long Length => output.Length;
public override long Position
{
get => output.Position;
set
{
if (_failed) return;
token.ThrowIfCancellationRequested();
output.Position = value;
}
}

public override long Seek(long offset, SeekOrigin origin)
{
if (_failed) return output.Position;
token.ThrowIfCancellationRequested();
return output.Seek(offset, origin);
}

public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();

protected override void Dispose(bool disposing)
{
if (disposing && _buffer is not null)
{
ArrayPool<byte>.Shared.Return(_buffer);
_buffer = null;
}

base.Dispose(disposing);
}
}

private sealed class AsyncTextWriter : TextWriter
{
private readonly TextWriter _output;
private readonly CancellationToken _token;
private readonly char[] _buffer = new char[TextBufferSize];
private int _length;

public AsyncTextWriter(TextWriter output, CancellationToken token) : base(output.FormatProvider)
{
_output = output;
_token = token;
NewLine = output.NewLine;
}

public override Encoding Encoding => _output.Encoding;

public override void Write(char value)
{
Span<char> single = [value];
Write(single);
}

public override void Write(string? value) => Write(value.AsSpan());

public override void Write(ReadOnlySpan<char> buffer)
{
_token.ThrowIfCancellationRequested();
while (!buffer.IsEmpty)
{
int count = Math.Min(buffer.Length, _buffer.Length - _length);
buffer[..count].CopyTo(_buffer.AsSpan(_length));
_length += count;
buffer = buffer[count..];
if (_length == _buffer.Length) WriteBuffer();
}
}

public override void Flush()
{
WriteBuffer();
_output.FlushAsync(_token).GetAwaiter().GetResult();
}

private void WriteBuffer()
{
_token.ThrowIfCancellationRequested();
if (_length == 0) return;
_output.WriteAsync(_buffer.AsMemory(0, _length), _token).GetAwaiter().GetResult();
_length = 0;
}
}
}
24 changes: 20 additions & 4 deletions src/NwcIO/Compatibility/Export/GlbExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ public static void Write(
Stream output,
bool worldCoordinates = true,
string? generatorName = null,
IReadOnlyList<NwcSavedViewpoint>? viewpoints = null)
IReadOnlyList<NwcSavedViewpoint>? viewpoints = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(meshes);
ArgumentNullException.ThrowIfNull(materials);
Expand All @@ -73,6 +74,7 @@ public static void Write(

for (int m = 0; m < meshes.Count; m++)
{
cancellationToken.ThrowIfCancellationRequested();
var mesh = meshes[m];
var vertices = worldCoordinates ? mesh.GetWorldVertices() : mesh.Vertices;
int vCount = vertices.Count;
Expand All @@ -94,6 +96,7 @@ public static void Write(
var indices = new List<int>();
for (int i = 0; i <= faces.Count - 3; i += 3)
{
if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested();
int i0 = faces[i];
int i1 = faces[i + 1];
int i2 = faces[i + 2];
Expand All @@ -111,6 +114,7 @@ public static void Write(
var lineIndices = new List<int>();
for (int i = 0; i <= mesh.LineIndices.Count - 2; i += 2)
{
if ((i & 4095) == 0) cancellationToken.ThrowIfCancellationRequested();
int i0 = mesh.LineIndices[i];
int i1 = mesh.LineIndices[i + 1];
if (i0 < 0 || i0 >= vCount || i1 < 0 || i1 >= vCount)
Expand All @@ -135,6 +139,7 @@ public static void Write(

for (int v = 0; v < vCount;)
{
cancellationToken.ThrowIfCancellationRequested();
var batch = bin.ReserveRecords(vCount - v, 12, out int count);
for (int i = 0; i < count; i++, v++)
{
Expand Down Expand Up @@ -174,6 +179,7 @@ public static void Write(
var normals = AccumulateNormals(vertices, indices);
for (int v = 0; v < vCount;)
{
cancellationToken.ThrowIfCancellationRequested();
var batch = bin.ReserveRecords(vCount - v, 12, out int count);
for (int i = 0; i < count; i++, v++)
{
Expand Down Expand Up @@ -214,6 +220,7 @@ public static void Write(
long colOffset = bin.BeginView(colLength);
for (int v = 0; v < vCount;)
{
cancellationToken.ThrowIfCancellationRequested();
var batch = bin.ReserveRecords(vCount - v, 16, out int count);
for (int i = 0; i < count; i++, v++)
{
Expand Down Expand Up @@ -326,7 +333,8 @@ public static void Write(
GetBinChunkLength(binFile?.Length ?? 0),
generatorName ?? "NwcIO glTF 2.0 Exporter",
viewpoints,
materialsWithBlend);
materialsWithBlend,
cancellationToken);

WriteContainer(output, jsonData.Span, binFile);
}
Expand Down Expand Up @@ -383,8 +391,9 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
List<BufferViewDef> bufferViews,
long binByteLength,
string generator,
IReadOnlyList<NwcSavedViewpoint>? viewpoints = null,
HashSet<int>? materialsWithBlend = null)
IReadOnlyList<NwcSavedViewpoint>? viewpoints,
HashSet<int>? materialsWithBlend,
CancellationToken cancellationToken)
{
var json = new ArrayBufferWriter<byte>();
using (var writer = new Utf8JsonWriter(json))
Expand Down Expand Up @@ -422,6 +431,7 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
if (totalNodes > 0) writer.WriteStartArray("nodes");
for (int i = 0; i < meshes.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
writer.WriteStartObject();
writer.WriteString("name", meshes[i].Name);
writer.WriteNumber("mesh", i);
Expand All @@ -432,6 +442,7 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
{
for (int i = 0; i < cameras.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var vp = cameras[i];
var cam = vp.Camera;
writer.WriteStartObject();
Expand Down Expand Up @@ -463,6 +474,7 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
writer.WriteStartArray("cameras");
for (int i = 0; i < cameras.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var vp = cameras[i];
var cam = vp.Camera;
writer.WriteStartObject();
Expand Down Expand Up @@ -500,6 +512,7 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
if (meshes.Count > 0) writer.WriteStartArray("meshes");
for (int i = 0; i < meshes.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var m = meshes[i];
writer.WriteStartObject();
writer.WriteString("name", m.Name);
Expand Down Expand Up @@ -538,6 +551,7 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
if (materials.Count > 0) writer.WriteStartArray("materials");
for (int i = 0; i < materials.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var mat = materials[i];
writer.WriteStartObject();
writer.WriteString("name", mat.Name);
Expand Down Expand Up @@ -568,6 +582,7 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
if (accessors.Count > 0) writer.WriteStartArray("accessors");
for (int i = 0; i < accessors.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var acc = accessors[i];
writer.WriteStartObject();
writer.WriteNumber("bufferView", acc.BufferView);
Expand Down Expand Up @@ -596,6 +611,7 @@ private static ReadOnlyMemory<byte> BuildJsonChunk(
if (bufferViews.Count > 0) writer.WriteStartArray("bufferViews");
for (int i = 0; i < bufferViews.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var bv = bufferViews[i];
writer.WriteStartObject();
writer.WriteNumber("buffer", 0);
Expand Down
4 changes: 3 additions & 1 deletion src/NwcIO/Compatibility/Export/IfcExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public static void Write(
NwcDocument doc,
TextWriter writer,
NwcIfcExportOptions? options = null,
string? fileName = null)
string? fileName = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(doc);
ArgumentNullException.ThrowIfNull(writer);
Expand Down Expand Up @@ -147,6 +148,7 @@ public static void Write(

for (int m = 0; m < doc.Meshes.Count; m++)
{
cancellationToken.ThrowIfCancellationRequested();
var mesh = doc.Meshes[m];
if (activePlanes.Count > 0 && options.ClipGeometryWithSectionPlanes)
{
Expand Down
4 changes: 3 additions & 1 deletion src/NwcIO/Compatibility/Export/ObjExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ public static void Write(
TextWriter writer,
bool worldCoordinates = true,
string? sourceDocument = null,
Func<NwcMesh, string?>? objectNamePrefix = null)
Func<NwcMesh, string?>? objectNamePrefix = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(meshes);
ArgumentNullException.ThrowIfNull(writer);
Expand All @@ -54,6 +55,7 @@ public static void Write(

for (int m = 0; m < meshes.Count; m++)
{
cancellationToken.ThrowIfCancellationRequested();
var mesh = meshes[m];
var vertices = worldCoordinates ? mesh.GetWorldVertices() : mesh.Vertices;
if (vertices.Count == 0 || (mesh.Indices.Count == 0 && mesh.LineIndices.Count == 0))
Expand Down
Loading
Loading