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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All notable changes to the `NwcIO` library, the CLI and the `NwcIO.Scene` adapte

## [Unreleased]

### Added

- `--max-property-refs` and `NwcReaderOptions.MaxExpandedPropertyReferences` let callers raise the expanded scene tree property reference limit for large models (#288).

### Fixed

- `NwcAssembly.ToDocument()` preserves explicit node visibility when copying the assembly tree.
Expand Down
8 changes: 8 additions & 0 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ doc.SaveHtmlViewer("interactive_site.html", new NwcHtmlViewerOptions

## CLI Usage

The DbCache scene tree reader allows 134,217,728 property and property tab references by default.
Each occurrence of a shared node contributes its references to the total. Use `--max-property-refs` with a positive
32-bit integer to change the limit for a run. A higher limit can increase memory use.

```bash
nwcio model.nwd model.json --no-meshes --no-materials --no-transforms --max-property-refs 268435456 --report
```

Run standard coordination and export tasks from your terminal or CI/CD pipelines. Except `--report`, the commands below use frozen features (bug fixes only):

```bash
Expand Down
4 changes: 4 additions & 0 deletions docs/public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ The supported surface is the `NwcIO` and `NwcIO.Model.*` namespaces listed here
`NwcDocument.GetLoadedPath()` returns the full path of a document opened by filename. It returns `null` for
documents opened from a stream or created in memory. `NwcFileInfo.SourcePath` is the source path stored in the file.

`NwcReaderOptions.MaxExpandedPropertyReferences` caps the total references to property records and tabs across
all node occurrences in a DbCache scene tree. The default is 134,217,728. Set a positive `int` to change the limit.
Exceeding it throws `InvalidDataException` before the reader expands the tree. A higher limit can increase memory use.

`NwcDocument.Open` overloads for paths and streams accept an `IProgress<NwcProgress>` and
`CancellationToken`. Cancellation is checked during container scanning and between parsing phases.
A non-seekable input uses a temporary file. With `KeepStreamCatalog = false`, stream payloads
Expand Down
21 changes: 20 additions & 1 deletion src/NwcIO.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ Matrix tolerances are in document units
--catalog Include raw container stream catalog (offsets, sizes, kinds)
--no-transforms Exclude 3D transform matrices from JSON export
--no-tree Skip reading the scene tree and exclude it from JSON export
--max-property-refs <count> Cap expanded scene tree property and tab references (default: 134217728)
--no-indent Write compact JSON instead of pretty-printed indented JSON
--bvh-stats Include Bounding Volume Hierarchy (BVH) spatial index statistics
--raycast <coords> Perform 3D raycast test: "originX,originY,originZ,dirX,dirY,dirZ"
Expand Down Expand Up @@ -168,6 +169,7 @@ internal static int Run(
bool includeCatalog = false;
bool includeTransforms = true;
bool includeTree = true;
int? maxExpandedPropertyReferences = null;
bool indent = true;
bool printReport = false;

Expand Down Expand Up @@ -212,6 +214,15 @@ internal static int Run(
case "--no-tree":
includeTree = false;
break;
case "--max-property-refs":
if (!TryConsumeValue(args, ref i, arg, out string maxRefsValue, @err)) return 1;
if (!int.TryParse(maxRefsValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out int maxRefs) || maxRefs <= 0)
{
@err.WriteLine($"Error: Invalid value '{maxRefsValue}' for {arg}. Expected an integer from 1 to 2147483647.");
return 1;
}
maxExpandedPropertyReferences = maxRefs;
break;
case "--no-meshes":
readMeshes = false;
break;
Expand Down Expand Up @@ -540,6 +551,10 @@ internal static int Run(
BuildSceneTree = includeTree,
KeepStreamCatalog = includeCatalog,
};
if (maxExpandedPropertyReferences is int limit)
{
readerOptions.MaxExpandedPropertyReferences = limit;
}

if (!multipleInputs && !isDirectory && !isNwf && !isManifest)
{
Expand Down Expand Up @@ -1052,7 +1067,11 @@ int ProcessLoadedAssembly(NwcAssembly preloaded, string displayPath, string? out
@err.WriteLine($"Error: Baseline file '{explicitDiffBaseline}' not found.");
return 2;
}
var baseDoc = NwcDocument.Open(explicitDiffBaseline, new NwcReaderOptions { BuildSceneTree = includeTree });
var baseDoc = NwcDocument.Open(explicitDiffBaseline, new NwcReaderOptions
{
BuildSceneTree = includeTree,
MaxExpandedPropertyReferences = readerOptions.MaxExpandedPropertyReferences,
});
var diffReport = baseDoc.Compare(doc, new Model.Diff.NwcDiffOptions { GeometricTolerance = diffTolerance });

if (!string.IsNullOrEmpty(explicitDiffJsonPath))
Expand Down
20 changes: 13 additions & 7 deletions src/NwcIO/Internal/Parsing/HierarchyParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ internal static class HierarchyParser
// shortcut: fixed cap on expanded node occurrences against crafted DAGs (real files stay near 1M); raise it if a real model needs more
public const int MaxExpandedNodes = 1 << 23;

// shortcut: fixed cap on property and property-tab references copied into expanded nodes (every occurrence copies its node's lists, about 1 GiB at the cap), against crafted DAGs; raise it if a real model needs more
public const int MaxExpandedProperties = 1 << 27;
// Every occurrence copies its node's property and tab references, about 1 GiB at the default cap.
public const int DefaultMaxExpandedPropertyReferences = 1 << 27;

private const string Segment = "LcOpNwdLogicalHierarchy";
private const string PropsSegment = "LcOaPartitionProps";
Expand Down Expand Up @@ -43,16 +43,19 @@ internal static class HierarchyParser
/// Gives the <c>LcOaPartitionProps</c> root streams, its table of contents excluded; called once, at the first null attribute slot or
/// after the hierarchy tail. It returns null, or is null, when the file has no such segment; an empty list is a segment without streams.
/// </param>
/// <param name="maxExpandedPropertyReferences">Caps the sum of property records and tabs across all node occurrences.</param>
/// <returns>The nodes in preorder; [0] is the synthetic root (Id 0, Name <paramref name="rootName"/>, Class "Model", Tag 0).</returns>
public static IReadOnlyList<NwcNode> Read(
byte[] data,
string rootName,
bool includeProperties = true,
IReadOnlyList<Guid>? guids = null,
Func<IReadOnlyList<byte[]>?>? partitionProps = null)
Func<IReadOnlyList<byte[]>?>? partitionProps = null,
int maxExpandedPropertyReferences = DefaultMaxExpandedPropertyReferences)
{
guids ??= [];
var (top, total) = new Parser(new LcObjectReader(data, Segment), guids.Count, partitionProps ?? (() => null)).ReadStream();
var (top, total) = new Parser(new LcObjectReader(data, Segment), guids.Count, partitionProps ?? (() => null),
maxExpandedPropertyReferences).ReadStream();
return Expand(top, rootName, total, includeProperties, guids);
}

Expand Down Expand Up @@ -238,6 +241,7 @@ private sealed class Parser
{
private readonly LcObjectReader _reader;
private readonly int _guidCount;
private readonly int _maxExpandedPropertyReferences;

// Null in a parser of one LcOaPartitionProps stream, which holds roots and no nodes.
private readonly Func<IReadOnlyList<byte[]>?>? _partitionProps;
Expand All @@ -246,10 +250,12 @@ private sealed class Parser
// The roots the null attribute slots take; ReadStream sets it from the header.
private PartitionRoots? _roots;

public Parser(LcObjectReader reader, int guidCount, Func<IReadOnlyList<byte[]>?>? partitionProps)
public Parser(LcObjectReader reader, int guidCount, Func<IReadOnlyList<byte[]>?>? partitionProps,
int maxExpandedPropertyReferences = DefaultMaxExpandedPropertyReferences)
{
_reader = reader;
_guidCount = guidCount;
_maxExpandedPropertyReferences = maxExpandedPropertyReferences;
_partitionProps = partitionProps;
_readBody = ReadBody;
}
Expand Down Expand Up @@ -431,9 +437,9 @@ private void SkipDoubles(int count)
}

// Each occurrence copies its node's tab references and records, so a small DAG over a property-heavy leaf multiplies them.
if (propertyReferences > MaxExpandedProperties)
if (propertyReferences > _maxExpandedPropertyReferences)
{
throw _reader.Fail($"expanded tree exceeds {MaxExpandedProperties} property references");
throw _reader.Fail($"expanded tree exceeds {_maxExpandedPropertyReferences} property references");
}

if (height > LcObjectReader.MaxNestingDepth)
Expand Down
10 changes: 6 additions & 4 deletions src/NwcIO/Internal/Parsing/ModelGraphReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,8 @@ public static async ValueTask<ModelGraph> ReadAsync(ModelSegments segments, NwcR
{
preorder = segments.Hierarchy is null
? [new NwcNode { Id = 0, Name = rootName, Class = "Model", Tag = 0 }]
: await ReadHierarchy(segments.Hierarchy, rootName, options.ReadPropertyRecords, guids, segments.PartitionProps).ConfigureAwait(false);
: await ReadHierarchy(segments.Hierarchy, rootName, options.ReadPropertyRecords, guids, segments.PartitionProps,
options.MaxExpandedPropertyReferences).ConfigureAwait(false);
}

var meshes = new List<NwcMesh>();
Expand Down Expand Up @@ -272,12 +273,13 @@ private static Guid[] ReadGuidStore(byte[] data)

private static async ValueTask<IReadOnlyList<NwcNode>> ReadHierarchy(
LcRawStream hierarchy, string rootName, bool includeProperties, Guid[] guids,
Func<ValueTask<IReadOnlyList<byte[]>?>> partitionProps)
Func<ValueTask<IReadOnlyList<byte[]>?>> partitionProps, int maxExpandedPropertyReferences)
{
byte[] data = await hierarchy.GetDataAsync().ConfigureAwait(false);
if (!hierarchy.RequiresAsyncRead)
{
return HierarchyParser.Read(data, rootName, includeProperties, guids, () => partitionProps().GetSynchronousResult());
return HierarchyParser.Read(data, rootName, includeProperties, guids,
() => partitionProps().GetSynchronousResult(), maxExpandedPropertyReferences);
}

// The hierarchy always checks the roots on a successful parse. Defer validation failures to that same point.
Expand All @@ -296,7 +298,7 @@ private static async ValueTask<IReadOnlyList<NwcNode>> ReadHierarchy(
{
failure?.Throw();
return roots;
});
}, maxExpandedPropertyReferences);
}

// The LcOaPartitionProps root streams, once the last stream, the table of contents [i32 k][k x i32 compressed length] zero-padded
Expand Down
18 changes: 18 additions & 0 deletions src/NwcIO/NwcReaderOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ namespace NwcIO;
/// <summary>Options controlling what <see cref="NwcDocument.Open"/> reads and keeps.</summary>
public sealed class NwcReaderOptions
{
private int _maxExpandedPropertyReferences = Internal.Parsing.HierarchyParser.DefaultMaxExpandedPropertyReferences;

public static NwcReaderOptions Default { get; } = new();

/// <summary>Parse the scene-tree/property streams (default: true).</summary>
Expand Down Expand Up @@ -58,6 +60,22 @@ public sealed class NwcReaderOptions
/// </summary>
public long MaxTotalDecompressedBytes { get; set; } = Internal.Container.NwcContainerReader.DefaultMaxTotalDecompressedBytes;

/// <summary>
/// Positive cap on the total property records and property tabs referenced by nodes in the expanded DbCache
/// scene tree (default: 134,217,728). Exceeding it throws <see cref="InvalidDataException"/> before expansion.
/// Raising the cap can increase memory use.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">The assigned value is zero or negative.</exception>
public int MaxExpandedPropertyReferences
{
get => _maxExpandedPropertyReferences;
set
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value);
_maxExpandedPropertyReferences = value;
}
}

/// <summary>
/// Cap on the vertices of one geometry record on the lenient reader path (default: 200,000). Larger records are skipped.
/// Model files read through their DbCache directory use the strict geometry parser and its own bounds.
Expand Down
22 changes: 22 additions & 0 deletions tests/NwcIO.Tests/CliArgumentValidationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,28 @@ public void VersionOption_PrintsVersionAndExits0()
Assert.StartsWith("nwcio", out2.Trim());
}

[Theory]
[InlineData("0")]
[InlineData("-1")]
[InlineData("2147483648")]
[InlineData("1.5")]
[InlineData("abc")]
public void MaxPropertyRefs_InvalidValue_Exits1(string value)
{
var (exit, _, error) = Run("--max-property-refs", value);
Assert.Equal(1, exit);
Assert.Contains("for --max-property-refs", error);
Assert.Contains("Expected an integer", error);
}

[Fact]
public void MaxPropertyRefs_MissingValue_Exits1()
{
var (exit, _, error) = Run("--max-property-refs", "--report");
Assert.Equal(1, exit);
Assert.Contains("Missing argument for --max-property-refs", error);
}

[Fact]
public void ValueOption_ConsumingFlagOrOption_Exits1WithError()
{
Expand Down
44 changes: 44 additions & 0 deletions tests/NwcIO.Tests/CliExitCodeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,50 @@ public void PartitionHierarchyNwc_OpensWithAndWithoutTree()
}
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void MaxPropertyRefs_AppliesToInputAndDiffBaseline(bool useBaseline)
{
string root = TempRoot();
Directory.CreateDirectory(root);
try
{
string path = Path.Combine(root, "input.nwd");
string output = Path.Combine(root, "out.json");
string baseline = Path.Combine(root, "baseline.nwd");
string diff = Path.Combine(root, "diff.json");
byte[] file = SyntheticNwcFile.Build(HierarchyParserTests.PropertyLeafHierarchy(), null, [], []);
string[] args = [path, output, "--no-meshes", "--no-materials", "--no-transforms", "--report"];
if (useBaseline)
{
var (empty, _) = SyntheticTree.Write(1);
File.WriteAllBytes(path, SyntheticNwcFile.Build(empty, null, [], []));
File.WriteAllBytes(baseline, file);
args = [.. args, "--diff", baseline, "--diff-json", diff];
}
else
{
File.WriteAllBytes(path, file);
}

string expectedOutput = useBaseline ? diff : output;
using var error = new StringWriter();
Assert.Equal(3, NwcIO.Cli.Program.Run([.. args, "--max-property-refs", "3"], errorWriter: error));
Assert.Contains("expanded tree exceeds 3 property references", error.ToString());
Assert.False(File.Exists(expectedOutput));

using var retryError = new StringWriter();
int exit = NwcIO.Cli.Program.Run([.. args, "--max-property-refs", "4"], errorWriter: retryError);
Assert.True(exit == 0, retryError.ToString());
Assert.True(File.Exists(expectedOutput));
}
finally
{
Directory.Delete(root, true);
}
}

[Fact]
public void PartitionHierarchyFolder_OpensWithAndWithoutTree()
{
Expand Down
42 changes: 42 additions & 0 deletions tests/NwcIO.Tests/ModelGraphReaderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,48 @@ public void Open_ReadPropertyRecords_ControlsLeafProperties(bool readProperties,
Assert.Equal(expected == 0 ? 0 : 1, leaf.PropertyTabs.Count);
}

[Fact]
public async Task Open_ExpandedPropertyLimitCountsEachOccurrence_SyncAndAsync()
{
var shared = new TreeNode("Leaf", "Leaf", Slots:
[new HTab(new Tab("Data", "Data", "data", new Prop("Id", "id", 2, 1)))]);
var (hierarchy, _) = SyntheticTree.Write(1, new TreeNode("Group", "Group", Children: [shared, shared]));
byte[] file = SyntheticNwcFile.Build(hierarchy, null, [], []);
var options = new NwcReaderOptions { MaxExpandedPropertyReferences = 3, KeepStreamCatalog = false };
using var input = new MemoryStream(file);

var syncError = Assert.Throws<InvalidDataException>(() => NwcDocument.Open(input, options));
input.Position = 0;
var asyncError = await Assert.ThrowsAsync<InvalidDataException>(() => NwcDocument.OpenAsync(input, options));
Assert.Contains("expanded tree exceeds 3 property references", syncError.Message);
Assert.Equal(syncError.Message, asyncError.Message);

options.MaxExpandedPropertyReferences = 4;
input.Position = 0;
var synchronous = NwcDocument.Open(input, options);
input.Position = 0;
var asynchronous = await NwcDocument.OpenAsync(input, options);
foreach (var document in new[] { synchronous, asynchronous })
{
var group = Assert.Single(document.RootNode!.Children);
Assert.Equal(2, group.Children.Count);
Assert.All(group.Children, leaf =>
{
Assert.Single(leaf.Properties);
Assert.Single(leaf.PropertyTabs);
});
}
}

[Theory]
[InlineData(0)]
[InlineData(-1)]
public void ExpandedPropertyLimitRejectsNonPositiveValues(int limit)
{
var options = new NwcReaderOptions();
Assert.Throws<ArgumentOutOfRangeException>(() => options.MaxExpandedPropertyReferences = limit);
}

[Fact]
public void Save_StrictlyReadMeshesAndTransforms_ReopenWithSamePlacement()
{
Expand Down
Loading