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
147 changes: 144 additions & 3 deletions docs/PublicApi.md

Large diffs are not rendered by default.

11 changes: 9 additions & 2 deletions src/Archive/ArcNET.Archive/DatArchive.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ public ReadOnlyMemory<byte> GetEntryData(string name)
return DatEntryReader.ReadEntryData(_mmf, entry);
}

/// <summary>Returns the decompressed bytes of an already-resolved entry.</summary>
public ReadOnlyMemory<byte> GetEntryData(ArchiveEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
ObjectDisposedException.ThrowIf(_disposed, this);
return DatEntryReader.ReadEntryData(_mmf, entry);
}

/// <summary>Opens a readable stream over the given entry, decompressing on-the-fly if needed.</summary>
public Stream OpenEntry(string name)
{
Expand All @@ -77,8 +85,7 @@ public Stream OpenEntry(string name)
/// <summary>Reads and decompresses the given entry.</summary>
public byte[] ReadEntry(ArchiveEntry entry)
{
ObjectDisposedException.ThrowIf(_disposed, this);
return DatEntryReader.ReadEntryData(_mmf, entry).ToArray();
return GetEntryData(entry).ToArray();
}

/// <inheritdoc/>
Expand Down
1 change: 1 addition & 0 deletions src/Benchmarks/ArcNET.Benchmarks/ArcNET.Benchmarks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<ProjectReference Include="../../GameObjects/ArcNET.GameObjects/ArcNET.GameObjects.csproj" />
<ProjectReference Include="../../Formats/ArcNET.Formats/ArcNET.Formats.csproj" />
<ProjectReference Include="../../Editor/ArcNET.Editor/ArcNET.Editor.csproj" />
<ProjectReference Include="../../Diagnostics/ArcNET.Diagnostics/ArcNET.Diagnostics.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
70 changes: 70 additions & 0 deletions src/Benchmarks/ArcNET.Benchmarks/DiagnosticsBytePatternBench.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using ArcNET.Diagnostics;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;

namespace ArcNET.Benchmarks;

[MemoryDiagnoser]
[ShortRunJob]
public class DiagnosticsBytePatternBench
{
private BytePattern _pattern = null!;
private byte?[] _legacyPattern = [];
private byte[] _haystack = [];

[Params(64 * 1024)]
public int HaystackLength { get; set; }

[Params(97, 8)]
public int MatchStride { get; set; }

[GlobalSetup]
public void Setup()
{
_pattern = BytePattern.Parse("8B ?? FF 10");
_legacyPattern = _pattern.Bytes;
_haystack = new byte[HaystackLength];

for (var index = 0; index < _haystack.Length; index++)
_haystack[index] = (byte)((index * 31) & 0x7F);

for (var start = 0; start + _pattern.Length <= _haystack.Length; start += MatchStride)
{
_haystack[start] = 0x8B;
_haystack[start + 1] = (byte)(start & 0xFF);
_haystack[start + 2] = 0xFF;
_haystack[start + 3] = 0x10;
}
}

[Benchmark(Baseline = true)]
public int[] FindMatches_Legacy()
{
if (_haystack.Length < _legacyPattern.Length)
return [];

List<int> matches = [];
for (var start = 0; start <= _haystack.Length - _legacyPattern.Length; start++)
{
if (MatchesAtLegacy(start))
matches.Add(start);
}

return [.. matches];
}

[Benchmark]
public int[] FindMatches_Anchored() => _pattern.FindMatches(_haystack);

private bool MatchesAtLegacy(int start)
{
for (var index = 0; index < _legacyPattern.Length; index++)
{
var expected = _legacyPattern[index];
if (expected.HasValue && _haystack[start + index] != expected.Value)
return false;
}

return true;
}
}
206 changes: 206 additions & 0 deletions src/Benchmarks/ArcNET.Benchmarks/EditorPixelPipelineBench.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
using ArcNET.Core.Primitives;
using ArcNET.Editor;
using ArcNET.Formats;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;

namespace ArcNET.Benchmarks;

[MemoryDiagnoser]
[ShortRunJob]
public class EditorArtPreviewBuilderBench
{
private ArtFile _art = null!;
private ArtPaletteEntry[] _palette = [];
private EditorArtPreviewOptions _options = null!;

[Params(64, 256)]
public int Edge { get; set; }

[Params(EditorArtPreviewPixelFormat.Rgba32, EditorArtPreviewPixelFormat.Bgra32)]
public EditorArtPreviewPixelFormat PixelFormat { get; set; }

[Params(false, true)]
public bool FlipVertically { get; set; }

[GlobalSetup]
public void Setup()
{
var pixels = new byte[checked(Edge * Edge)];
for (var index = 0; index < pixels.Length; index++)
pixels[index] = index % 9 == 0 ? (byte)0 : (byte)((index % 255) + 1);

_palette = CreatePalette();
_art = CreateArtFile(Edge, Edge, pixels, _palette);
_options = new EditorArtPreviewOptions { PixelFormat = PixelFormat, FlipVertically = FlipVertically };
}

[Benchmark(Baseline = true)]
public byte[] BuildFrame_Legacy()
{
var frame = _art.Frames[0][0];
var width = checked((int)frame.Header.Width);
var height = checked((int)frame.Header.Height);
var pixelData = new byte[checked(width * height * 4)];
var usePaletteAlpha = UsesExplicitPaletteAlpha(_palette);

for (var destinationRow = 0; destinationRow < height; destinationRow++)
{
var sourceRow = _options.FlipVertically ? height - 1 - destinationRow : destinationRow;
for (var column = 0; column < width; column++)
{
var sourceIndex = sourceRow * width + column;
var destinationIndex = checked((destinationRow * width + column) * 4);
WritePixelLegacy(pixelData, destinationIndex, frame.Pixels[sourceIndex], usePaletteAlpha);
}
}

return pixelData;
}

[Benchmark]
public byte[] BuildFrame_PackedLookup() => EditorArtPreviewBuilder.BuildFrame(_art, 0, 0, _options).PixelData;

private static ArtPaletteEntry[] CreatePalette()
{
var palette = new ArtPaletteEntry[byte.MaxValue + 1];
for (var index = 1; index < palette.Length; index++)
{
palette[index] = new ArtPaletteEntry(
Blue: (byte)((index * 17) & 0xFF),
Green: (byte)((index * 29) & 0xFF),
Red: (byte)((index * 43) & 0xFF),
Alpha: (byte)(32 + (index % 224))
);
}

return palette;
}

private static ArtFile CreateArtFile(int width, int height, byte[] pixels, ArtPaletteEntry[] palette) =>
new()
{
Flags = ArtFlags.Static,
FrameRate = 8,
ActionFrame = 0,
FrameCount = 1,
DataSizes = new uint[8],
PaletteData1 = new uint[8],
PaletteData2 = new uint[8],
PaletteIds = [1, 0, 0, 0],
Palettes = [palette, null, null, null],
Frames =
[
[
new ArtFrame
{
Header = new ArtFrameHeader((uint)width, (uint)height, (uint)pixels.Length, 0, 0, 0, 0),
Pixels = pixels,
},
],
],
};

private void WritePixelLegacy(byte[] pixelData, int destinationIndex, byte paletteIndex, bool usePaletteAlpha)
{
if (paletteIndex == 0)
return;

var color = _palette[paletteIndex];
var alpha = usePaletteAlpha ? color.Alpha : byte.MaxValue;
switch (_options.PixelFormat)
{
case EditorArtPreviewPixelFormat.Rgba32:
pixelData[destinationIndex] = color.Red;
pixelData[destinationIndex + 1] = color.Green;
pixelData[destinationIndex + 2] = color.Blue;
pixelData[destinationIndex + 3] = alpha;
break;
case EditorArtPreviewPixelFormat.Bgra32:
pixelData[destinationIndex] = color.Blue;
pixelData[destinationIndex + 1] = color.Green;
pixelData[destinationIndex + 2] = color.Red;
pixelData[destinationIndex + 3] = alpha;
break;
default:
throw new ArgumentOutOfRangeException(nameof(_options.PixelFormat), _options.PixelFormat, null);
}
}

private static bool UsesExplicitPaletteAlpha(ArtPaletteEntry[] palette)
{
for (var index = 1; index < palette.Length; index++)
{
if (palette[index].Alpha != 0)
return true;
}

return false;
}
}

[MemoryDiagnoser]
[ShortRunJob]
public class EditorSpriteMirrorBench
{
private static readonly ArtId MirroredTileArtId = new(0x000121C1u);
private byte[] _source = [];

[Params(78, 256)]
public int Width { get; set; }

[Params(40, 256)]
public int Height { get; set; }

[GlobalSetup]
public void Setup()
{
_source = new byte[checked(Width * Height * 4)];
for (var index = 0; index < _source.Length; index++)
_source[index] = (byte)((index * 31) & 0xFF);
}

[Benchmark(Baseline = true)]
public byte[] Flip_Legacy()
{
var pixelData = (byte[])_source.Clone();
FlipPixelDataHorizontallyLegacy(pixelData, Width, Height);
return pixelData;
}

[Benchmark]
public byte[] Flip_PackedPixels()
{
var pixelData = (byte[])_source.Clone();
EditorWorkspaceMapRenderSpriteSource.ApplyCeHorizontalTileMirror(
EditorMapRenderQueueItemKind.FloorTile,
MirroredTileArtId,
pixelData,
Width,
Height
);
return pixelData;
}

private static void FlipPixelDataHorizontallyLegacy(byte[] pixelData, int width, int height)
{
const int bytesPerPixel = 4;
if (width <= 1 || height <= 0)
return;

for (var row = 0; row < height; row++)
{
var rowStart = checked(row * width * bytesPerPixel);
for (int left = 0, right = width - 1; left < right; left++, right--)
{
var leftIndex = rowStart + (left * bytesPerPixel);
var rightIndex = rowStart + (right * bytesPerPixel);
for (var channel = 0; channel < bytesPerPixel; channel++)
(pixelData[leftIndex + channel], pixelData[rightIndex + channel]) = (
pixelData[rightIndex + channel],
pixelData[leftIndex + channel]
);
}
}
}
}
32 changes: 32 additions & 0 deletions src/Diagnostics/ArcNET.Diagnostics.FileTime/BytePattern.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,22 @@ namespace ArcNET.Diagnostics;

public sealed class BytePattern
{
private readonly int _anchorIndex = -1;
private readonly byte _anchorValue;

private BytePattern(byte?[] bytes, string normalizedText)
{
Bytes = bytes;
NormalizedText = normalizedText;
for (var index = 0; index < bytes.Length; index++)
{
if (bytes[index] is not { } value)
continue;

_anchorIndex = index;
_anchorValue = value;
break;
}
}

public byte?[] Bytes { get; }
Expand Down Expand Up @@ -52,8 +64,28 @@ public int[] FindMatches(ReadOnlySpan<byte> haystack)
return [];

List<int> matches = [];
if (_anchorIndex < 0)
{
for (var start = 0; start <= haystack.Length - Bytes.Length; start++)
{
if (MatchesAt(haystack, start))
matches.Add(start);
}

return [.. matches];
}

for (var start = 0; start <= haystack.Length - Bytes.Length; start++)
{
var anchorOffset = start + _anchorIndex;
var maxAnchorOffset = haystack.Length - Bytes.Length + _anchorIndex;
var nextAnchorOffset = haystack
.Slice(anchorOffset, maxAnchorOffset - anchorOffset + 1)
.IndexOf(_anchorValue);
if (nextAnchorOffset < 0)
break;

start += nextAnchorOffset;
if (MatchesAt(haystack, start))
matches.Add(start);
}
Expand Down
22 changes: 22 additions & 0 deletions src/Diagnostics/ArcNET.Diagnostics.Tests/BytePatternTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,26 @@ public async Task ParseAndFindMatches_WhenPatternUsesWildcards_ReturnsExpectedOf
await Assert.That(pattern.NormalizedText).IsEqualTo("8B ?? FF");
await Assert.That(matches).IsEquivalentTo([0, 3]);
}

[Test]
public async Task FindMatches_WhenPatternIsOnlyWildcards_ReturnsEveryValidOffset()
{
var pattern = BytePattern.Parse("?? ??");
var haystack = new byte[] { 0x10, 0x20, 0x30, 0x40 };

var matches = pattern.FindMatches(haystack);

await Assert.That(matches).IsEquivalentTo([0, 1, 2]);
}

[Test]
public async Task FindMatches_WhenAnchorIsNotFirstByte_DoesNotReadPastLastValidCandidate()
{
var pattern = BytePattern.Parse("?? FE 10");
var haystack = new byte[] { 0x00, 0xFE, 0x10, 0x11, 0x22, 0xFE };

var matches = pattern.FindMatches(haystack);

await Assert.That(matches).IsEquivalentTo([0]);
}
}
Loading
Loading