diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index efd62124d..f3a6862f7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -60,7 +60,17 @@ jobs: strategy: matrix: - lib: [GBX.NET, GBX.NET.Hashing, GBX.NET.Imaging, GBX.NET.Imaging.SkiaSharp, GBX.NET.LZO, GBX.NET.ZLib, GBX.NET.NewtonsoftJson] + lib: + - GBX.NET + - GBX.NET.Hashing + - GBX.NET.Imaging + - GBX.NET.Imaging.SkiaSharp + - GBX.NET.Imaging.ImageSharp + - GBX.NET.LZO + - GBX.NET.ZLib + - GBX.NET.NewtonsoftJson + - GBX.NET.Tool + - GBX.NET.Tool.CLI name: Publish ${{ matrix.lib }} runs-on: ubuntu-latest diff --git a/Benchmarks/GBX.NET.Benchmarks/MapParseBenchmarks.cs b/Benchmarks/GBX.NET.Benchmarks/MapParseBenchmarks.cs index 9824ccf2f..5e4c76e14 100644 --- a/Benchmarks/GBX.NET.Benchmarks/MapParseBenchmarks.cs +++ b/Benchmarks/GBX.NET.Benchmarks/MapParseBenchmarks.cs @@ -11,7 +11,7 @@ public class MapParseBenchmarks public MapParseBenchmarks() { - Gbx.LZO = new MiniLZO(); + Gbx.LZO = new Lzo(); stream = new MemoryStream(File.ReadAllBytes(Path.Combine("Gbx", "CGameCtnChallenge", "GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx"))); } diff --git a/Generators/GBX.NET.Generators/ChunkL/ChunkLPropertiesWriter.cs b/Generators/GBX.NET.Generators/ChunkL/ChunkLPropertiesWriter.cs index d3d901c33..9a6a01a49 100644 --- a/Generators/GBX.NET.Generators/ChunkL/ChunkLPropertiesWriter.cs +++ b/Generators/GBX.NET.Generators/ChunkL/ChunkLPropertiesWriter.cs @@ -263,11 +263,11 @@ private void AppendPropertiesRecursive(IEnumerable members, HashSe sb.Append(" Get"); sb.Append(propName); - sb.Append("(GbxReadSettings settings = default) => "); + sb.Append("(GbxReadSettings settings = default, bool exceptions = false) => "); sb.Append(fieldName); sb.Append("File?.GetNode(ref "); sb.Append(fieldName); - sb.Append(", settings) ?? "); + sb.Append(", settings, exceptions) ?? "); sb.Append(fieldName); sb.AppendLine(";"); } diff --git a/Generators/GBX.NET.Generators/ChunkL/MemberSerializationWriter.cs b/Generators/GBX.NET.Generators/ChunkL/MemberSerializationWriter.cs index 1f8df32e5..46bd15f05 100644 --- a/Generators/GBX.NET.Generators/ChunkL/MemberSerializationWriter.cs +++ b/Generators/GBX.NET.Generators/ChunkL/MemberSerializationWriter.cs @@ -359,6 +359,11 @@ private void AppendWrite(int indent, ChunkProperty chunkProperty) sb.Append("Array"); } + if (chunkProperty.Type.PrimaryType == "data") + { + sb.Append("Data"); + } + var mappedType = MapType(chunkProperty.Type.PrimaryType, out var noMatch); if (noMatch) diff --git a/README.md b/README.md index 2024805b3..0385fe754 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ For any questions, open an issue, join the [GameBox Sandbox Discord server](http - [Modify and save a map](#modify-and-save-a-map) - [Processing multiple Gbx types](#processing-multiple-gbx-types) - [Read a large amount of replay metadata quickly](#read-a-large-amount-of-replay-metadata-quickly) +- [Tool framework](#tool-framework) - [Clarity](#clarity) - [Differences between `Gbx.Parse/Header/Node`](#differences-between-gbxparseheadernode) - [Do not repeat `gbx.Node.[any]` too often!](#do-not-repeat-gbxnodeany-too-often) @@ -172,7 +173,7 @@ C# code: using GBX.NET; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); ``` You should run this line of code **only once** for the whole program lifetime. @@ -194,7 +195,7 @@ using GBX.NET; using GBX.NET.Engines.Game; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var map = Gbx.ParseNode("Path/To/My.Map.Gbx"); @@ -221,7 +222,7 @@ using GBX.NET; using GBX.NET.Engines.Game; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var gbx = Gbx.Parse("Path/To/My.Map.Gbx"); var map = gbx.Node; // See Clarity section for more info @@ -269,7 +270,7 @@ using GBX.NET; using GBX.NET.Engines.Game; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var node = Gbx.ParseNode("Path/To/My.Gbx"); @@ -336,6 +337,42 @@ This code should only crash in case of a file system problem. Other problems wil > [!NOTE] > It is still valuable to parse the full Gbx even when you just want a piece of information available in header, because **body info overwrites header info**. So you can use the benefit of full parse to fool people tackling with the Gbx header. +## Tool framework + +Tool framework (`GBX.NET.Tool*` libraries) is a simple way to create rich tools that can be adapted to different environments. + +Currently supported environments: +- **Console** (`GBX.NET.Tool.CLI`) + +Planned environments: +- Blazor (`GBX.NET.Tool.Blazor`) - both server and WebAssembly +- HTTP server (`GBX.NET.Tool.Server`) +- Discord bot (`GBX.NET.Tool.Discord.Bot`) + +The tool framework guides you with this project structure: + +```mermaid +graph LR + A(GBX.NET.Tool) --> B(YourToolProject) + C(GBX.NET.Tool.CLI) --> D(YourToolProjectCLI) + B --> D + A --> C + E(GBX.NET) --> A + F(GBX.NET.LZO) --> C + E --> F + G(Spectre.Console) --> C +``` + +- Structure: Tool library (`YourToolProject`) and at least 1 implementation application of it (`YourToolProjectCLI`). +- Tool library references `GBX.NET.Tool` and implementation application references `GBX.NET.Tool.CLI`. +- `GBX.NET.Tool.CLI` currently uses LZO by default, no need to reference it additionally. + +Tool library has a primary tool class that implements `ITool` interface. There should be only one. + +Tool class accepts input through constructors (best one is picked according to input provided by implementation). The tool can output as "produce" (`IProductive`), which creates objects without mutating the input (for example, create MediaTracker clip from replay inputs), or "mutate" (`IMutative`) which creates objects while also causing changes to the input (for example, modifying a map without having to recreate it again). + +Samples are available [here](Samples/Tool/). + ## Clarity This section describes best practices to keep your projects clean when using GBX.NET 2. @@ -436,6 +473,22 @@ GBX.NET is a huge library when everything is included (over 1.5MB), so please us > [!NOTE] > Expect this to work only with `dotnet publish`. +However, in case you wanna use reflection on GBX.NET, it is strongly recommended to simply turn off trimming of this library. **In case of Blazor WebAssembly specifically, it's worth noting that the release build trims automatically**, so in case you're using reflection, modify your library reference: + +```xml + + false + +``` + +In case this is not enough, you can specify `TrimmerRootAssembly` on the project you're building that this library should absolutely not be trimmed: + +```xml + + + +``` + ### Explicit vs. Implicit parse *In the past, the difference between these two used to be only to reduce the amount of written code by the consumer and making the type more strict, the performance was exactly the same.* @@ -528,7 +581,7 @@ Make sure you have these framework SDKs available: **Visual Studio 2022** should be able to install those with default installation settings. Using Visual Studio 2019 will likely not work. -You should also have **.NET WebAssembly Build Tools** installed additionally to build the full solution. It may not be required, but it will definitely help figuring out some problems. +You should also have **.NET WebAssembly Build Tools** installed additionally to build the full solution. It is required for Gbx Explorer to work properly, as it uses native LZO implementation compiled into WebAssembly. In Visual Studio, you can just use Build Solution and everything should build. JetBrains Rider has been tested and also works. diff --git a/Resources/ClassId.txt b/Resources/ClassId.txt index 4bc7fe191..a3aaa097a 100644 Binary files a/Resources/ClassId.txt and b/Resources/ClassId.txt differ diff --git a/SUPPORTED_GBX_FILE_TYPES.md b/SUPPORTED_GBX_FILE_TYPES.md index ce1f0cb79..ac3b89ff3 100644 --- a/SUPPORTED_GBX_FILE_TYPES.md +++ b/SUPPORTED_GBX_FILE_TYPES.md @@ -37,5 +37,6 @@ Older extensions | Latest extension | Class | Read (whole) | Write | Read (heade | | Material.Gbx | [CPlugMaterial](Src/GBX.NET/Engines/Plug/CPlugMaterial.cs) | Up to TM2 | No | | Texture.Gbx | [CPlugBitmap](Src/GBX.NET/Engines/Plug/CPlugBitmap.cs) | Up to TMUF | No | | Light.Gbx | [CPlugLight](Src/GBX.NET/Engines/Plug/CPlugLight.cs) | Yes | Yes +| | Prefab.Gbx | [CPlugPrefab](Src/GBX.NET/Engines/Plug/CPlugPrefab.cs) | Yes | Yes - 1Safety reasons. Consider extracting `CGameCtnGhost` from `CGameCtnReplayRecord`, transfer it over to `CGameCtnMediaBlockGhost`, add it to `CGameCtnMediaClip`, and save it as `.Clip.Gbx`, which you can then import in MediaTracker. \ No newline at end of file diff --git a/Samples/Advanced/Blik/Program.cs b/Samples/Advanced/Blik/Program.cs index 8a002e5ce..3ea22997a 100644 --- a/Samples/Advanced/Blik/Program.cs +++ b/Samples/Advanced/Blik/Program.cs @@ -4,7 +4,7 @@ using GBX.NET.LZO; using GBX.NET.ZLib; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); Gbx.ZLib = new ZLib(); var gbxMap = Gbx.Parse(args[0]); diff --git a/Samples/Advanced/ItemPacker/Program.cs b/Samples/Advanced/ItemPacker/Program.cs index 73d76e159..2f098d918 100644 --- a/Samples/Advanced/ItemPacker/Program.cs +++ b/Samples/Advanced/ItemPacker/Program.cs @@ -4,7 +4,7 @@ using GBX.NET.LZO; using Microsoft.Extensions.Logging; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var logger = LoggerFactory.Create(builder => { diff --git a/Samples/Beginner/EnvimixForTM2020/Program.cs b/Samples/Beginner/EnvimixForTM2020/Program.cs index be0b71765..4ab216cce 100644 --- a/Samples/Beginner/EnvimixForTM2020/Program.cs +++ b/Samples/Beginner/EnvimixForTM2020/Program.cs @@ -5,7 +5,7 @@ using System.Text; using TmEssentials; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); Gbx.CRC32 = new CRC32(); var cars = new[] { "CarSport", "CarSnow", "CarRally", "CarDesert", "CharacterPilot" }; diff --git a/Samples/Beginner/FixDesertUpdatePillarsAfterConversion/Program.cs b/Samples/Beginner/FixDesertUpdatePillarsAfterConversion/Program.cs index d301a196c..290cba7de 100644 --- a/Samples/Beginner/FixDesertUpdatePillarsAfterConversion/Program.cs +++ b/Samples/Beginner/FixDesertUpdatePillarsAfterConversion/Program.cs @@ -2,7 +2,7 @@ using GBX.NET.Engines.Game; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var gbxMap = Gbx.Parse(args[0]); diff --git a/Samples/Beginner/FullMapInfo/Program.cs b/Samples/Beginner/FullMapInfo/Program.cs index e8b4fa24d..fa4547363 100644 --- a/Samples/Beginner/FullMapInfo/Program.cs +++ b/Samples/Beginner/FullMapInfo/Program.cs @@ -11,7 +11,7 @@ var watch = Stopwatch.StartNew(); -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var map = Gbx.ParseNode(args[0]); watch.Stop(); diff --git a/Samples/Beginner/Legomania/Program.cs b/Samples/Beginner/Legomania/Program.cs index d98bd51e6..bb8b2d697 100644 --- a/Samples/Beginner/Legomania/Program.cs +++ b/Samples/Beginner/Legomania/Program.cs @@ -8,7 +8,7 @@ return; } -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var map = Gbx.ParseNode(args[0]); diff --git a/Samples/Beginner/SolidExtract/Program.cs b/Samples/Beginner/SolidExtract/Program.cs index d8a879622..bceb972b4 100644 --- a/Samples/Beginner/SolidExtract/Program.cs +++ b/Samples/Beginner/SolidExtract/Program.cs @@ -3,7 +3,7 @@ using GBX.NET.Engines.Plug; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); foreach (var filePath in args) { diff --git a/Samples/Tool/GhostExtract/GhostExtractTool.cs b/Samples/Tool/GhostExtract/GhostExtractTool.cs index f2ea99c36..5fcae439e 100644 --- a/Samples/Tool/GhostExtract/GhostExtractTool.cs +++ b/Samples/Tool/GhostExtract/GhostExtractTool.cs @@ -7,12 +7,14 @@ namespace GhostExtract; public class GhostExtractTool : ITool, IProductive>> { + private readonly Gbx gbx; private readonly string? fileName; private readonly IEnumerable ghosts; private readonly ILogger logger; public GhostExtractTool(Gbx gbxReplay, ILogger logger) { + gbx = gbxReplay; fileName = Path.GetFileName(gbxReplay.FilePath); ghosts = gbxReplay.Node.GetGhosts(); this.logger = logger; @@ -20,6 +22,7 @@ public GhostExtractTool(Gbx gbxReplay, ILogger logger) public GhostExtractTool(Gbx gbxClip, ILogger logger) { + gbx = gbxClip; fileName = Path.GetFileName(gbxClip.FilePath); ghosts = gbxClip.Node.GetGhosts(); this.logger = logger; @@ -31,11 +34,13 @@ public IEnumerable> Produce() { logger.LogInformation("Extracting ghost {GhostIndex} from {FileName}...", i + 1, fileName); - return new Gbx(ghost) + return new Gbx(ghost, gbx.Header.Basic) { FilePath = ghost.CanBeGameVersion(GameVersion.MP3) - ? Path.Combine("Replays", "GbxTools", "GhostExtract", $"{GbxPath.GetFileNameWithoutExtension(fileName ?? "Ghost")}_{i + 1:00}.Gbx.Gbx") - : Path.Combine("Tracks", "Replays", "GbxTools", "GhostExtract", $"{GbxPath.GetFileNameWithoutExtension(fileName ?? "Ghost")}_{i + 1:00}.Gbx") + ? Path.Combine("Replays", "GbxTools", "GhostExtract", $"{GbxPath.GetFileNameWithoutExtension(fileName ?? "Ghost")}_{i + 1:00}.Ghost.Gbx") + : Path.Combine("Tracks", "Replays", "GbxTools", "GhostExtract", $"{GbxPath.GetFileNameWithoutExtension(fileName ?? "Ghost")}_{i + 1:00}.Ghost.Gbx"), + ClassIdRemapMode = gbx.ClassIdRemapMode, + PackDescVersion = gbx.PackDescVersion, }; }); } diff --git a/Samples/Tool/InputExtract/InputExtractConfig.cs b/Samples/Tool/InputExtract/InputExtractConfig.cs new file mode 100644 index 000000000..3573d6b8a --- /dev/null +++ b/Samples/Tool/InputExtract/InputExtractConfig.cs @@ -0,0 +1,8 @@ +using GBX.NET.Tool; + +namespace InputExtract; + +public class InputExtractConfig : Config +{ + public string Format { get; set; } = "test"; +} diff --git a/Samples/Tool/InputExtract/InputExtractTool.cs b/Samples/Tool/InputExtract/InputExtractTool.cs index 19f31cc2b..173c106f2 100644 --- a/Samples/Tool/InputExtract/InputExtractTool.cs +++ b/Samples/Tool/InputExtract/InputExtractTool.cs @@ -3,8 +3,10 @@ namespace InputExtract; -public class InputExtractTool : ITool +public class InputExtractTool : ITool, IConfigurable { + public InputExtractConfig Config { get; } = new(); + public InputExtractTool(CGameCtnReplayRecord replay) { diff --git a/Samples/Tool/InputExtractCLI/InputExtractCLI.csproj b/Samples/Tool/InputExtractCLI/InputExtractCLI.csproj index cfba537b0..373a64bc6 100644 --- a/Samples/Tool/InputExtractCLI/InputExtractCLI.csproj +++ b/Samples/Tool/InputExtractCLI/InputExtractCLI.csproj @@ -9,6 +9,7 @@ + diff --git a/Samples/Tool/InputExtractCLI/Program.cs b/Samples/Tool/InputExtractCLI/Program.cs index 3751555cb..cba2e8c6d 100644 --- a/Samples/Tool/InputExtractCLI/Program.cs +++ b/Samples/Tool/InputExtractCLI/Program.cs @@ -1,2 +1,4 @@ -// See https://aka.ms/new-console-template for more information -Console.WriteLine("Hello, World!"); +using GBX.NET.Tool.CLI; +using InputExtract; + +await ToolConsole.RunAsync(args); \ No newline at end of file diff --git a/Src/GBX.NET.Hashing/README.md b/Src/GBX.NET.Hashing/README.md index 9891d921d..2f6145f13 100644 --- a/Src/GBX.NET.Hashing/README.md +++ b/Src/GBX.NET.Hashing/README.md @@ -17,7 +17,7 @@ using GBX.NET.Engines.Game; using GBX.NET.LZO; using GBX.NET.Hashing; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); Gbx.CRC32 = new CRC32(); // You need to add this var map = Gbx.ParseNode("Path/To/My.Map.Gbx"); diff --git a/Src/GBX.NET.Imaging.ImageSharp/CGameCtnChallengeExtensions.cs b/Src/GBX.NET.Imaging.ImageSharp/CGameCtnChallengeExtensions.cs new file mode 100644 index 000000000..58a374854 --- /dev/null +++ b/Src/GBX.NET.Imaging.ImageSharp/CGameCtnChallengeExtensions.cs @@ -0,0 +1,156 @@ +using GBX.NET.Engines.Game; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.Processing; + +namespace GBX.NET.Imaging.ImageSharp; + +/// +/// Imaging extensions for . +/// +public static partial class CGameCtnChallengeExtensions +{ + /// + /// Gets the map thumbnail as . + /// + /// CGameCtnChallenge + /// Cancellation token. + /// Thumbnail as . + public static async ValueTask GetThumbnailImageAsync(this CGameCtnChallenge node, CancellationToken cancellationToken = default) + { + if (node.Thumbnail is null) + { + return null; + } + + using var ms = new MemoryStream(node.Thumbnail); + var image = await Image.LoadAsync(ms, cancellationToken); + + image.Mutate(x => + { + x.RotateFlip(RotateMode.Rotate180, FlipMode.Horizontal); + }); + + return image; + } + + /// + /// Gets the map thumbnail as . + /// + /// CGameCtnChallenge + /// Thumbnail as . + public static Image? GetThumbnailImage(this CGameCtnChallenge node) + { + if (node.Thumbnail is null) + { + return null; + } + + var image = Image.Load(node.Thumbnail); + + image.Mutate(x => + { + x.RotateFlip(RotateMode.Rotate180, FlipMode.Horizontal); + }); + + return image; + } + + /// + /// Exports the map's thumbnail. + /// + /// CGameCtnChallenge + /// Stream to export to. + /// Image encoder to use. + /// Cancellation token. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static async Task ExportThumbnailAsync(this CGameCtnChallenge node, Stream stream, IImageEncoder encoder, CancellationToken cancellationToken = default) + { + using var thumbnail = await node.GetThumbnailImageAsync(cancellationToken); + + if (thumbnail is null) + { + return false; + } + + await thumbnail.SaveAsync(stream, encoder, cancellationToken); + + return true; + } + + /// + /// Exports the map's thumbnail. + /// + /// CGameCtnChallenge + /// File to export to. + /// Image encoder to use. + public static void ExportThumbnail(this CGameCtnChallenge node, string fileName, IImageEncoder encoder) + { + using var fs = File.Create(fileName); + node.ExportThumbnail(fs, encoder); + } + + /// + /// Exports the map's thumbnail. + /// + /// CGameCtnChallenge + /// File to export to. + /// Image encoder to use. + /// Cancellation token. + public static async Task ExportThumbnailAsync(this CGameCtnChallenge node, string fileName, IImageEncoder encoder, CancellationToken cancellationToken = default) + { + await using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); + await node.ExportThumbnailAsync(fs, encoder, cancellationToken); + } + + /// + /// Replaces a thumbnail (any popular image format) to use for the map. + /// + /// CGameCtnChallenge + /// Stream to import from. + /// The quality level to use for the JPEG image. This is in the range from 1-100. + /// Cancellation token. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static async Task ImportThumbnailAsync(this CGameCtnChallenge node, Stream stream, int quality = 95, CancellationToken cancellationToken = default) + { + using var image = await Image.LoadAsync(stream, cancellationToken); + + image.Mutate(x => + { + x.RotateFlip(RotateMode.Rotate180, FlipMode.Horizontal); + }); + + await using var ms = new MemoryStream(); + await image.SaveAsync(ms, new JpegEncoder { Quality = quality }, cancellationToken); + + node.Thumbnail = ms.ToArray(); + + return image; + } + + /// + /// Replaces a thumbnail (any popular image format) to use for the map. + /// + /// CGameCtnChallenge + /// File to import from. + /// The quality level to use for the JPEG image. This is in the range from 1-100. + /// Cancellation token. + public static async Task ImportThumbnailAsync(this CGameCtnChallenge node, string fileName, int quality = 95, CancellationToken cancellationToken = default) + { + await using var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); + return await node.ImportThumbnailAsync(fs, quality, cancellationToken); + } + + /// + /// Replaces a thumbnail (any popular image format) to use for the map. + /// + /// CGameCtnChallenge + /// File to import from. + /// The quality level to use for the JPEG image. This is in the range from 0-100. + public static Image ImportThumbnail(this CGameCtnChallenge node, string fileName, int quality = 95) + { + using var fs = File.OpenRead(fileName); + return node.ImportThumbnail(fs, quality); + } +} diff --git a/Src/GBX.NET.Imaging.ImageSharp/CGameCtnCollectorExtensions.cs b/Src/GBX.NET.Imaging.ImageSharp/CGameCtnCollectorExtensions.cs new file mode 100644 index 000000000..646dbfbeb --- /dev/null +++ b/Src/GBX.NET.Imaging.ImageSharp/CGameCtnCollectorExtensions.cs @@ -0,0 +1,303 @@ +using System.Runtime.InteropServices; +using GBX.NET.Engines.GameData; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; + +namespace GBX.NET.Imaging.ImageSharp; + +/// +/// Imaging extensions for . +/// +public static partial class CGameCtnCollectorExtensions +{ + /// + /// Gets the collector's icon as . + /// + /// CGameCtnCollector + /// Cancellation token. + /// Icon as . Null if and is . + public static async ValueTask GetIconImageAsync(this CGameCtnCollector node, CancellationToken cancellationToken = default) + { + if (node.Icon is not null) + { + return GetIconImage(node.Icon); + } + + if (node.IconWebP is null) + { + return null; + } + + await using var ms = new MemoryStream(node.IconWebP); + var webpBitmap = await Image.LoadAsync(ms, cancellationToken); + + webpBitmap.Mutate(x => + { + x.Rotate(RotateMode.Rotate180); + x.Flip(FlipMode.Horizontal); + }); + + return webpBitmap; + } + + /// + /// Gets the collector's icon as . + /// + /// CGameCtnCollector + /// Cancellation token. + /// Icon as . Null if and is . + public static Image? GetIconImage(this CGameCtnCollector node) + { + if (node.Icon is not null) + { + return GetIconImage(node.Icon); + } + + if (node.IconWebP is null) + { + return null; + } + + var webpBitmap = Image.Load(node.IconWebP); + + webpBitmap.Mutate(x => + { + x.Rotate(RotateMode.Rotate180); + x.Flip(FlipMode.Horizontal); + }); + + return webpBitmap; + } + + /// + /// Exports the collector's icon. + /// + /// CGameCtnCollector + /// Stream to export to. + /// Image encoder to use. + /// Cancellation token. + /// True if successful. False if and is . + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static async Task ExportIconAsync(this CGameCtnCollector node, Stream stream, IImageEncoder encoder, CancellationToken cancellationToken = default) + { + using var icon = await node.GetIconImageAsync(cancellationToken); + + if (icon is null) + { + return false; + } + + await icon.SaveAsync(stream, encoder, cancellationToken); + + return true; + } + + /// + /// Exports the collector's icon as PNG. + /// + /// CGameCtnCollector + /// Stream to export to. + /// Cancellation token. + /// True if successful. False if and is . + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static async Task ExportIconAsync(this CGameCtnCollector node, Stream stream, CancellationToken cancellationToken = default) + { + return await ExportIconAsync(node, stream, new PngEncoder(), cancellationToken); + } + + /// + /// Exports the collector's icon. + /// + /// CGameCtnCollector + /// File to export to. + /// Image encoder to use. + /// True if successful. False if and is . + public static bool ExportIcon(this CGameCtnCollector node, string fileName, IImageEncoder encoder) + { + if (node.Icon is null && node.IconWebP is null) + { + return false; + } + + using var fs = File.Create(fileName); + return node.ExportIcon(fs, encoder); + } + + /// + /// Exports the collector's icon. + /// + /// CGameCtnCollector + /// File to export to. + /// Image encoder to use. + /// Cancellation token. + /// True if successful. False if and is . + public static async ValueTask ExportIconAsync(this CGameCtnCollector node, string fileName, IImageEncoder encoder, CancellationToken cancellationToken = default) + { + if (node.Icon is null && node.IconWebP is null) + { + return false; + } + + await using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true); + return await node.ExportIconAsync(fs, encoder, cancellationToken); + } + + /// + /// Exports the collector's icon as PNG. + /// + /// CGameCtnCollector + /// File to export to. + /// Cancellation token. + /// True if successful. False if and is . + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static async Task ExportIconAsync(this CGameCtnCollector node, string fileName, CancellationToken cancellationToken = default) + { + return await ExportIconAsync(node, fileName, new PngEncoder(), cancellationToken); + } + + /// + /// Replaces the collector's raw RGB icon with a WebP encoded icon. WebP is only accepted in TM2020. + /// + /// CGameCtnCollector + /// Cancellation token. + /// True if successful. False if is . + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static async ValueTask UpgradeIconToWebPAsync(this CGameCtnCollector node, CancellationToken cancellationToken = default) + { + if (node.Icon is null) + { + return false; + } + + using var image = GetFlippedIconImage(node.Icon); + await using var iconStream = new MemoryStream(); + await image.SaveAsWebpAsync(iconStream, cancellationToken); + node.IconWebP = iconStream.ToArray(); + node.Icon = null; + return true; + } + + // public static bool DowngradeIconToRaw(this CGameCtnCollector node) + + /// + /// Replaces an icon (any popular image format) to use for the collector. + /// + /// CGameCtnCollector + /// Stream to import from. + /// If icon should be imported as WebP, which is used in TM2020 since April 2022. + /// Cancellation token. + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public static async Task ImportIconAsync(this CGameCtnCollector node, Stream stream, bool webp = false, CancellationToken cancellationToken = default) + { + using var image = await Image.LoadAsync(stream, cancellationToken); + + image.Mutate(x => + { + x.Rotate(RotateMode.Rotate180); + x.Flip(FlipMode.Horizontal); + }); + + await using var ms = new MemoryStream(); + + if (webp) + { + await image.SaveAsWebpAsync(ms, cancellationToken); + node.IconWebP = ms.ToArray(); + return image; + } + + var width = image.Width; + var height = image.Height; + var data = new Color[width, height]; + + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + data[x, y] = new((int)image[x, height - y - 1].Rgba); + } + } + + node.Icon = data; + + return image; + } + + /// + /// Replaces an icon (any popular image format) to use for the collector. + /// + /// CGameCtnChallenge + /// File to import from. + /// If icon should be imported as WebP, which is used in TM2020 since April 2022. + /// Cancellation token. + public static async Task ImportIconAsync(this CGameCtnCollector node, string fileName, bool webp = false, CancellationToken cancellationToken = default) + { + await using var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); + return await node.ImportIconAsync(fs, webp, cancellationToken); + } + + /// + /// Replaces an icon (any popular image format) to use for the collector. + /// + /// CGameCtnChallenge + /// File to import from. + /// If icon should be imported as WebP, which is used in TM2020 since April 2022. + public static Image ImportIcon(this CGameCtnCollector node, string fileName, bool webp = false) + { + using var fs = File.OpenRead(fileName); + return node.ImportIcon(fs, webp); + } + + private static Image GetImage(int[] data, int width, int height) + { + var image = new Image(width, height); + + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + image[x, y] = new Rgba32((uint)data[y * width + x]); + } + } + + return image; + } + + private static Image? GetIconImage(Color[,] icon) + { + var width = icon.GetLength(0); + var height = icon.GetLength(1); + + var data = new int[width * height]; + + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + data[y * width + x] = icon[x, y].ToRgba(); + } + } + + return GetImage(data, width, height); + } + + private static Image GetFlippedIconImage(Color[,] icon) + { + int width = icon.GetLength(0); + int height = icon.GetLength(1); + int[] array = new int[width * height]; + + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + array[y * width + x] = icon[x, height - y - 1].ToRgba(); + } + } + + return GetImage(array, width, height); + } +} diff --git a/Src/GBX.NET.Imaging.ImageSharp/GBX.NET.Imaging.ImageSharp.csproj b/Src/GBX.NET.Imaging.ImageSharp/GBX.NET.Imaging.ImageSharp.csproj index 39a986a54..3e1603091 100644 --- a/Src/GBX.NET.Imaging.ImageSharp/GBX.NET.Imaging.ImageSharp.csproj +++ b/Src/GBX.NET.Imaging.ImageSharp/GBX.NET.Imaging.ImageSharp.csproj @@ -2,7 +2,7 @@ GBX.NET.Imaging.ImageSharp - 1.0.0-alpha1 + 1.0.0 BigBang1112 Copyright (c) 2024 Petr Pivoňka @@ -15,7 +15,7 @@ - net8.0;net6.0;netstandard2.0 + net8.0;net6.0 12 enable enable @@ -37,7 +37,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -50,6 +50,10 @@ all runtime; build; native; contentfiles; analyzers + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/Src/GBX.NET.Imaging.ImageSharp/LICENSE b/Src/GBX.NET.Imaging.ImageSharp/LICENSE new file mode 100644 index 000000000..b1598afef --- /dev/null +++ b/Src/GBX.NET.Imaging.ImageSharp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Petr Pivoňka + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Src/GBX.NET.Imaging.ImageSharp/README.md b/Src/GBX.NET.Imaging.ImageSharp/README.md index 802853932..eb436e411 100644 --- a/Src/GBX.NET.Imaging.ImageSharp/README.md +++ b/Src/GBX.NET.Imaging.ImageSharp/README.md @@ -1 +1,54 @@ -# GBX.NET.Imaging.ImageSharp \ No newline at end of file +# GBX.NET.Imaging.ImageSharp + +[![NuGet](https://img.shields.io/nuget/vpre/GBX.NET.Imaging.SkiaSharp?style=for-the-badge&logo=nuget)](https://www.nuget.org/packages/GBX.NET.Imaging.ImageSharp/) +[![Discord](https://img.shields.io/discord/1012862402611642448?style=for-the-badge&logo=discord)](https://discord.gg/tECTQcAWC9) + +Provides extensions for image handling in GBX.NET using ImageSharp. + +Async methods are available. + +## Framework support + +- .NET 8 +- .NET 6 + +## Usage + +### Export thumbnail from map + +You can use `CGameCtnChallenge.Thumbnail` to get the pure JPEG bytes, but the thumbnail is going to be upside down. This is a long-standing bug in Nadeo games. `ExportThumbnail` method flips this thumbnail correctly. + +```cs +using GBX.NET; +using GBX.NET.Engines.Game; +using GBX.NET.Imaging.ImageSharp; // You need to add this + +var map = Gbx.ParseHeaderNode("Path/To/My.Map.Gbx"); + +map.ExportThumbnail("MyThumbnail.jpg", new JpegEncoder { Quality = quality }); +``` + +### Export icon from any `CGameCtnCollector` + +This includes any Item.Gbx, Block.Gbx, Macroblock.Gbx, EDClassic.Gbx, Collection.Gbx, and many more... + +For TM2020 after April 2022 update, the WEBP icon is also rotated correctly. + +```cs +using GBX.NET; +using GBX.NET.Engines.GameData; // Note it's GameData now instead of Game +using GBX.NET.Imaging.ImageSharp; // You need to add this + +var node = Gbx.ParseHeaderNode("Path/To/My.Item.Gbx"); + +if (node is CGameCtnCollector collector) +{ + collector.ExportIcon("MyIcon.png"); +} +``` + +Quality should not be degraded as the icon is processed with either pure color bytes or lossless WEBP and exported to PNG as default. Use the `encoder` parameter to tweak the export. + +## License + +GBX.NET.Imaging.SkiaSharp library is MIT Licensed. \ No newline at end of file diff --git a/Src/GBX.NET.Imaging.SkiaSharp/CGameCtnCollectorExtensions.cs b/Src/GBX.NET.Imaging.SkiaSharp/CGameCtnCollectorExtensions.cs index 58b473489..5775dabe5 100644 --- a/Src/GBX.NET.Imaging.SkiaSharp/CGameCtnCollectorExtensions.cs +++ b/Src/GBX.NET.Imaging.SkiaSharp/CGameCtnCollectorExtensions.cs @@ -13,18 +13,18 @@ public static class CGameCtnCollectorExtensions /// Gets the collector's icon as . /// /// CGameCtnCollector - /// Icon as . Null if and is null. + /// Icon as . Null if and is . public static SKBitmap? GetIconBitmap(this CGameCtnCollector node) { if (node.Icon is null) { - if (node.IconWebP is not null) + if (node.IconWebP is null) { - using var webpBitmap = SKBitmap.Decode(node.IconWebP); - return webpBitmap.Rotate180FlipX(); + return null; } - return null; + using var webpBitmap = SKBitmap.Decode(node.IconWebP); + return webpBitmap.Rotate180FlipX(); } var width = node.Icon.GetLength(0); @@ -32,13 +32,30 @@ public static class CGameCtnCollectorExtensions var data = new int[width * height]; - for (var y = 0; y < height; y++) +#if NET6_0_OR_GREATER + if (RuntimeInformation.ProcessArchitecture == Architecture.Wasm) { - for (var x = 0; x < width; x++) + for (var y = 0; y < height; y++) { - data[y * width + x] = node.Icon[x, y].ToArgb(); + for (var x = 0; x < width; x++) + { + data[y * width + x] = node.Icon[x, y].ToRgba(); + } } } + else + { +#endif + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + data[y * width + x] = node.Icon[x, y].ToArgb(); + } + } +#if NET6_0_OR_GREATER + } +#endif return GetBitmap(data, width, height); } @@ -50,7 +67,7 @@ public static class CGameCtnCollectorExtensions /// Stream to export to. /// Image format to use. /// The quality level to use for the image. This is in the range from 0-100. Not all formats (for example, PNG) respect or support it. - /// True if successful. False if and is null. + /// True if successful. False if and is . public static bool ExportIcon(this CGameCtnCollector node, Stream stream, SKEncodedImageFormat format, int quality) { using var icon = node.GetIconBitmap(); @@ -62,7 +79,7 @@ public static bool ExportIcon(this CGameCtnCollector node, Stream stream, SKEnco /// /// CGameCtnCollector /// Stream to export to. - /// True if successful. False if and is null. + /// True if successful. False if and is . public static bool ExportIcon(this CGameCtnCollector node, Stream stream) { return ExportIcon(node, stream, SKEncodedImageFormat.Png, 100); @@ -75,7 +92,7 @@ public static bool ExportIcon(this CGameCtnCollector node, Stream stream) /// File to export to. /// Image format to use. /// The quality level to use for the image. This is in the range from 0-100. Not all formats (for example, PNG) respect or support it. - /// True if successful. False if and is null. + /// True if successful. False if and is . public static bool ExportIcon(this CGameCtnCollector node, string fileName, SKEncodedImageFormat format, int quality) { if (node.Icon is null && node.IconWebP is null) @@ -92,7 +109,7 @@ public static bool ExportIcon(this CGameCtnCollector node, string fileName, SKEn /// /// CGameCtnCollector /// File to export to. - /// True if successful. False if and is null. + /// True if successful. False if and is . public static bool ExportIcon(this CGameCtnCollector node, string fileName) { return ExportIcon(node, fileName, SKEncodedImageFormat.Png, 100); @@ -102,7 +119,7 @@ public static bool ExportIcon(this CGameCtnCollector node, string fileName) /// Replaces the collector's raw RGB icon with a WebP encoded icon. WebP is only accepted in TM2020. /// /// CGameCtnCollector - /// True if successful. False if is null. + /// True if successful. False if is . public static bool UpgradeIconToWebP(this CGameCtnCollector node) { if (node.Icon is null) @@ -113,16 +130,34 @@ public static bool UpgradeIconToWebP(this CGameCtnCollector node) int width = node.Icon.GetLength(0); int height = node.Icon.GetLength(1); int[] array = new int[width * height]; - for (int y = 0; y < height; y++) + +#if NET6_0_OR_GREATER + if (RuntimeInformation.ProcessArchitecture == Architecture.Wasm) + { + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + array[y * width + x] = node.Icon[x, height - y - 1].ToRgba(); + } + } + } + else { - for (int x = 0; x < width; x++) +#endif + for (int y = 0; y < height; y++) { - array[y * width + x] = node.Icon[x, height - y - 1].ToArgb(); + for (int x = 0; x < width; x++) + { + array[y * width + x] = node.Icon[x, height - y - 1].ToArgb(); + } } +#if NET6_0_OR_GREATER } +#endif using var bitmap = GetBitmap(array, width, height); - var iconStream = new MemoryStream(); + using var iconStream = new MemoryStream(); bitmap.Encode(iconStream, SKEncodedImageFormat.Webp, 100); node.IconWebP = iconStream.ToArray(); node.Icon = null; @@ -131,6 +166,55 @@ public static bool UpgradeIconToWebP(this CGameCtnCollector node) // public static bool DowngradeIconToRaw(this CGameCtnCollector node) + /// + /// Replaces an icon (any popular image format) to use for the collector. + /// + /// CGameCtnCollector + /// Stream to import from. + /// If icon should be imported as WebP, which is used in TM2020 since April 2022. + public static SKBitmap ImportIcon(this CGameCtnCollector node, Stream stream, bool webp = false) + { + using var bitmap = SKBitmap.Decode(stream); + using var rotated = bitmap.Rotate180FlipX(); + using var ms = new MemoryStream(); + + if (webp) + { + rotated.Encode(ms, SKEncodedImageFormat.Webp, 100); + node.IconWebP = ms.ToArray(); + return rotated; + } + + // later replace with GetPixels + var width = rotated.Width; + var height = rotated.Height; + var data = new Color[width, height]; + + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + data[x, y] = new Color((int)(uint)rotated.GetPixel(x, y)); + } + } + + node.Icon = data; + + return rotated; + } + + /// + /// Replaces an icon (any popular image format) to use for the collector. + /// + /// CGameCtnChallenge + /// File to import from. + /// If icon should be imported as WebP, which is used in TM2020 since April 2022. + public static SKBitmap ImportIcon(this CGameCtnCollector node, string fileName, bool webp = false) + { + using var fs = File.OpenRead(fileName); + return node.ImportIcon(fs, webp); + } + private static SKBitmap GetBitmap(int[] data, int width, int height) { var bitmap = new SKBitmap(); diff --git a/Src/GBX.NET.Imaging.SkiaSharp/GBX.NET.Imaging.SkiaSharp.csproj b/Src/GBX.NET.Imaging.SkiaSharp/GBX.NET.Imaging.SkiaSharp.csproj index c44f3e61f..e78680032 100644 --- a/Src/GBX.NET.Imaging.SkiaSharp/GBX.NET.Imaging.SkiaSharp.csproj +++ b/Src/GBX.NET.Imaging.SkiaSharp/GBX.NET.Imaging.SkiaSharp.csproj @@ -2,7 +2,7 @@ GBX.NET.Imaging.SkiaSharp - 1.0.1 + 1.1.0 BigBang1112 Provides extensions for image handling in GBX.NET (Google's Skia with SkiaSharp). Copyright (c) 2024 Petr Pivoňka diff --git a/Src/GBX.NET.Imaging/CGameCtnCollectorExtensions.cs b/Src/GBX.NET.Imaging/CGameCtnCollectorExtensions.cs index a06eebdbd..8d0fcb00f 100644 --- a/Src/GBX.NET.Imaging/CGameCtnCollectorExtensions.cs +++ b/Src/GBX.NET.Imaging/CGameCtnCollectorExtensions.cs @@ -14,7 +14,7 @@ public static class CGameCtnCollectorExtensions /// Gets the collector's icon as . /// /// CGameCtnCollector - /// Icon as . Null if is null. + /// Icon as . Null if is . public static Bitmap? GetIconBitmap(this CGameCtnCollector node) { if (node.Icon is null) return null; diff --git a/Src/GBX.NET.Imaging/GBX.NET.Imaging.csproj b/Src/GBX.NET.Imaging/GBX.NET.Imaging.csproj index a3b636826..fc4f540bf 100644 --- a/Src/GBX.NET.Imaging/GBX.NET.Imaging.csproj +++ b/Src/GBX.NET.Imaging/GBX.NET.Imaging.csproj @@ -39,7 +39,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Src/GBX.NET.LZO/GBX.NET.LZO.csproj b/Src/GBX.NET.LZO/GBX.NET.LZO.csproj index af94649b2..0faf5332b 100644 --- a/Src/GBX.NET.LZO/GBX.NET.LZO.csproj +++ b/Src/GBX.NET.LZO/GBX.NET.LZO.csproj @@ -2,9 +2,9 @@ GBX.NET.LZO - 2.0.0 + 2.1.0 BigBang1112 - An LZO compression plugin for GBX.NET to allow de/serialization of compressed Gbx bodies. This official implementation uses minilzo 2.06. + An LZO compression plugin for GBX.NET to allow de/serialization of compressed Gbx bodies. This official implementation uses lzo 2.10 from NativeSharpLzo and minilzo 2.06 port by zzattack. Copyright (c) 2024 Petr Pivoňka https://github.com/BigBang1112/gbx-net logo_icon_outline.png @@ -41,6 +41,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Src/GBX.NET.LZO/Lzo.cs b/Src/GBX.NET.LZO/Lzo.cs new file mode 100644 index 000000000..e59e1fcef --- /dev/null +++ b/Src/GBX.NET.LZO/Lzo.cs @@ -0,0 +1,21 @@ +using GBX.NET.Extensions; + +namespace GBX.NET.LZO; + +public sealed class Lzo : ILzo +{ + public byte[] Compress(byte[] data) + { + return SharpLzo.Lzo.Compress(SharpLzo.CompressionMode.Lzo1x_999, data); + } + + public void Decompress(in Span input, byte[] output) + { + var result = SharpLzo.Lzo.TryDecompress(input, input.Length, output, out var _); + + if (result != SharpLzo.LzoResult.OK) + { + throw new SharpLzo.LzoException(result); + } + } +} diff --git a/Src/GBX.NET.LZO/README.md b/Src/GBX.NET.LZO/README.md index ce68f8323..f11f65328 100644 --- a/Src/GBX.NET.LZO/README.md +++ b/Src/GBX.NET.LZO/README.md @@ -3,7 +3,7 @@ [![NuGet](https://img.shields.io/nuget/vpre/GBX.NET.LZO?style=for-the-badge&logo=nuget)](https://www.nuget.org/packages/GBX.NET.LZO/) [![Discord](https://img.shields.io/discord/1012862402611642448?style=for-the-badge&logo=discord)](https://discord.gg/tECTQcAWC9) -An LZO compression plugin for GBX.NET to allow de/serialization of compressed Gbx bodies. This official implementation uses minilzo 2.06. +An LZO compression plugin for GBX.NET to allow de/serialization of compressed Gbx bodies. This official implementation uses lzo 2.10 from NativeSharpLzo and minilzo 2.06 port by zzattack. The compression logic is split up from the read/write logic to **allow GBX.NET 2 library to be distributed under the MIT license**, as Oberhumer distributes the open source version of LZO under the GNU GPL v3. Therefore, using GBX.NET.LZO 2 requires you to license your project under the GNU GPL v3, see [License](#license). @@ -11,7 +11,9 @@ The compression logic is split up from the read/write logic to **allow GBX.NET 2 ## Usage -At the beginning of your program execution, you add the `Gbx.LZO = new MiniLZO();` to prepare the LZO compression. It should be run **only once**. +At the beginning of your program execution, you add the `Gbx.LZO = new Lzo();` to prepare the LZO compression. It should be run **only once**. + +The `Lzo` implementation uses `999` compression, which is slightly more efficient than the compression used by Nadeo games. > This project example expects you to have `enable`. If this does not work for you, add `using System.Linq;`. @@ -20,7 +22,7 @@ using GBX.NET; using GBX.NET.Engines.Game; using GBX.NET.LZO; // Add this -Gbx.LZO = new MiniLZO(); // Add this ONLY ONCE and before you start using Parse methods +Gbx.LZO = new Lzo(); // Add this ONLY ONCE and before you start using Parse methods var map = Gbx.ParseNode("Path/To/My.Map.Gbx"); @@ -29,6 +31,17 @@ Console.WriteLine($"Block count: {map.GetBlocks().Count()}"); You should not get the LZO exception anymore when you read a compressed Gbx file. +### MiniLZO + +If you want to use the port of minilzo 2.06, just use the `MiniLZO` class. MiniLZO uses `1` compression which is less efficient than the one used by Nadeo games. + +```cs +using GBX.NET.LZO; + +Gbx.LZO = new MiniLZO(); +``` + + ## License GBX.NET.LZO library is GNU GPL v3 Licensed. diff --git a/Src/GBX.NET.NewtonsoftJson/GBX.NET.NewtonsoftJson.csproj b/Src/GBX.NET.NewtonsoftJson/GBX.NET.NewtonsoftJson.csproj index 9a4d465c4..ec8e74d5b 100644 --- a/Src/GBX.NET.NewtonsoftJson/GBX.NET.NewtonsoftJson.csproj +++ b/Src/GBX.NET.NewtonsoftJson/GBX.NET.NewtonsoftJson.csproj @@ -2,7 +2,7 @@ GBX.NET.NewtonsoftJson - 1.0.0 + 1.0.1 BigBang1112 Better and easier JSON serialization with polymorphic support for GBX.NET objects. Copyright (c) 2024 Petr Pivoňka @@ -19,6 +19,9 @@ 12 enable enable + true + true + true true true diff --git a/Src/GBX.NET.NewtonsoftJson/GbxJson.cs b/Src/GBX.NET.NewtonsoftJson/GbxJson.cs new file mode 100644 index 000000000..5d5bb438a --- /dev/null +++ b/Src/GBX.NET.NewtonsoftJson/GbxJson.cs @@ -0,0 +1,67 @@ +using GBX.NET.Engines.MwFoundations; +using Newtonsoft.Json; + +#if NET6_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; +#endif + +namespace GBX.NET.NewtonsoftJson; + +public static class GbxJson +{ +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonExtensions.JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static string Serialize(this Gbx gbx, bool indented = true) + { + return JsonExtensions.ToJson(gbx, indented); + } + +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonExtensions.JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static string Serialize(this CMwNod node, bool indented = true) + { + return JsonExtensions.ToJson(node, indented); + } + +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonExtensions.JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static void Serialize(this Gbx gbx, TextWriter writer, bool indented = true) + { + JsonExtensions.ToJson(gbx, writer, indented); + } + +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonExtensions.JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static void Serialize(this CMwNod node, TextWriter writer, bool indented = true) + { + JsonExtensions.ToJson(node, writer, indented); + } + +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonExtensions.JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static void Serialize(this Gbx gbx, Stream stream, bool indented = true) + { + JsonExtensions.ToJson(gbx, stream, indented); + } + +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonExtensions.JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static void Serialize(this CMwNod node, Stream stream, bool indented = true) + { + JsonExtensions.ToJson(node, stream, indented); + } + +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonExtensions.JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + internal static Gbx? DeserializeGbx(string json) where T : CMwNod + { + return JsonConvert.DeserializeObject>(json); + } +} diff --git a/Src/GBX.NET.NewtonsoftJson/JsonExtensions.cs b/Src/GBX.NET.NewtonsoftJson/JsonExtensions.cs index 034270951..87799fda7 100644 --- a/Src/GBX.NET.NewtonsoftJson/JsonExtensions.cs +++ b/Src/GBX.NET.NewtonsoftJson/JsonExtensions.cs @@ -3,10 +3,16 @@ using Newtonsoft.Json; using Newtonsoft.Json.Converters; +#if NET6_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; +#endif + namespace GBX.NET.NewtonsoftJson; public static class JsonExtensions { + internal const string JsonSerializationRequiresUnreferencedCodeMessage = "Newtonsoft.Json serialization is not supported with trimming nor AOT."; + private static readonly JsonSerializerSettings settings = new() { TypeNameHandling = TypeNameHandling.Auto, @@ -20,39 +26,57 @@ static JsonExtensions() settings.Converters.Add(new StringEnumConverter()); } +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonSerializationRequiresUnreferencedCodeMessage)] +#endif public static string ToJson(this Gbx gbx, bool indented = true) { return JsonConvert.SerializeObject(gbx, indented ? Formatting.Indented : Formatting.None, settings); } - public static string ToJson(this CMwNod node, bool indented = true) +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static string ToJson(this CMwNod node, bool indented = true) { return JsonConvert.SerializeObject(node, indented ? Formatting.Indented : Formatting.None, settings); } - public static void ToJson(this Gbx gbx, TextWriter writer, bool indented = true) +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static void ToJson(this Gbx gbx, TextWriter writer, bool indented = true) { CreateSerializer(indented).Serialize(writer, gbx); } - public static void ToJson(this CMwNod node, TextWriter writer, bool indented = true) +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static void ToJson(this CMwNod node, TextWriter writer, bool indented = true) { CreateSerializer(indented).Serialize(writer, node); } - public static void ToJson(this Gbx gbx, Stream stream, bool indented = true) +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static void ToJson(this Gbx gbx, Stream stream, bool indented = true) { using var writer = new StreamWriter(stream); CreateSerializer(indented).Serialize(writer, gbx); } - public static void ToJson(this CMwNod node, Stream stream, bool indented = true) +#if NET6_0_OR_GREATER + [RequiresUnreferencedCode(JsonSerializationRequiresUnreferencedCodeMessage)] +#endif + public static void ToJson(this CMwNod node, Stream stream, bool indented = true) { using var writer = new StreamWriter(stream); CreateSerializer(indented).Serialize(writer, node); } - private static JsonSerializer CreateSerializer(bool indented) + private static JsonSerializer CreateSerializer(bool indented) { var serializer = JsonSerializer.Create(settings); serializer.Formatting = indented ? Formatting.Indented : Formatting.None; diff --git a/Src/GBX.NET.NewtonsoftJson/README.md b/Src/GBX.NET.NewtonsoftJson/README.md index d26dace68..703a13bdb 100644 --- a/Src/GBX.NET.NewtonsoftJson/README.md +++ b/Src/GBX.NET.NewtonsoftJson/README.md @@ -15,7 +15,7 @@ Provides extensions for JSON serialization with `Newtonsoft.Json`. ### Convert Gbx and any `CMwNod` to JSON -Additional package `GBX.NET.LZO` is required in this example.Additional package `GBX.NET.LZO` is required in this example. +Additional package `GBX.NET.LZO` is required in this example. ```cs using GBX.NET; @@ -23,7 +23,7 @@ using GBX.NET.Engines.Game; using GBX.NET.LZO; using GBX.NET.NewtonsoftJson; // Add this -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var gbx = Gbx.Parse("Path/To/My.Map.Gbx"); @@ -33,7 +33,7 @@ string jsonNode = gbx.Node.ToJson(); ### Print JSON of Gbx to console using `TextWriter` -Additional package `GBX.NET.LZO` is required in this example.Additional package `GBX.NET.LZO` is required in this example. +Additional package `GBX.NET.LZO` is required in this example. ```cs using GBX.NET; @@ -41,7 +41,7 @@ using GBX.NET.Engines.Game; using GBX.NET.LZO; using GBX.NET.NewtonsoftJson; // Add this -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var gbx = Gbx.Parse("Path/To/My.Map.Gbx"); diff --git a/Src/GBX.NET.Tool.CLI/ArgsResolver.cs b/Src/GBX.NET.Tool.CLI/ArgsResolver.cs new file mode 100644 index 000000000..738447c19 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/ArgsResolver.cs @@ -0,0 +1,145 @@ +using GBX.NET.Tool.CLI.Exceptions; +using GBX.NET.Tool.CLI.Inputs; + +namespace GBX.NET.Tool.CLI; + +internal sealed class ArgsResolver +{ + private readonly string[] args; + private readonly HttpClient client; + + public bool HasArgs => args.Length > 0; + + public ArgsResolver(string[] args, HttpClient http) + { + this.args = args; + this.client = http; + } + + public ToolSettings Resolve(ConsoleSettings consoleOptions) + { + if (!HasArgs) + { + return new ToolSettings { ConsoleSettings = consoleOptions }; + } + + var configOverwrites = new Dictionary(); + var inputs = new List(); + + var argsEnumerator = args.AsEnumerable().GetEnumerator(); + + while (argsEnumerator.MoveNext()) + { + var arg = argsEnumerator.Current; + + if (arg == "--disable-update-check") + { + consoleOptions.DisableUpdateCheck = true; + continue; + } + + if (arg == "--skip-intro") + { + consoleOptions.SkipIntro = true; + continue; + } + + if (arg == "--no-pause") + { + consoleOptions.NoPause = true; + continue; + } + + if (arg == "--config" || arg == "-c") + { + if (!argsEnumerator.MoveNext()) + { + throw new ConsoleProblemException("Missing config name."); + } + + var configName = argsEnumerator.Current; + + if (!File.Exists(configName)) + { + throw new ConsoleProblemException("Config does not exist."); + } + + consoleOptions.ConfigName = configName; + continue; + } + + if (arg.StartsWith("--config:") || arg.StartsWith("-c:")) + { + var configKey = arg.Substring(arg.IndexOf(':') + 1); + + if (!argsEnumerator.MoveNext()) + { + throw new ConsoleProblemException("Missing config value."); + } + + var configValue = argsEnumerator.Current; + + configOverwrites[configKey] = configValue; + continue; + } + + if (arg == "--output" || arg == "-o") + { + if (!argsEnumerator.MoveNext()) + { + throw new ConsoleProblemException("Missing output path."); + } + + var outputPath = argsEnumerator.Current; + + consoleOptions.OutputDirPath = outputPath; + continue; + } + + if (arg == "--direct-output" || arg == "-d") + { + consoleOptions.DirectOutput = true; + continue; + } + + if (arg.StartsWith('-')) + { + continue; + } + + // - check http:// and https:// for URLs + // - check for individual files and files in zip archives + // - check for folders + // - check for stdin (maybe?) + // - check for configured user data path + if (Directory.Exists(arg)) + { + inputs.Add(new DirectoryInput(arg)); + continue; + } + + if (File.Exists(arg)) + { + inputs.Add(new FileInput(arg)); + continue; + } + + if (Uri.TryCreate(arg, UriKind.Absolute, out var uri)) + { + if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) + { + inputs.Add(new UriInput(client, uri)); + } + + continue; + } + } + + return new ToolSettings + { + Inputs = inputs, + ConfigOverwrites = configOverwrites, + ConsoleSettings = consoleOptions + }; + } +} diff --git a/Src/GBX.NET.Tool.CLI/ConsoleSettings.cs b/Src/GBX.NET.Tool.CLI/ConsoleSettings.cs new file mode 100644 index 000000000..9fc0fde56 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/ConsoleSettings.cs @@ -0,0 +1,14 @@ +using Microsoft.Extensions.Logging; + +namespace GBX.NET.Tool.CLI; + +public sealed record ConsoleSettings +{ + public bool DisableUpdateCheck { get; set; } + public bool SkipIntro { get; set; } + public bool NoPause { get; set; } + public bool DirectOutput { get; set; } = true; + public string? OutputDirPath { get; set; } + public string? ConfigName { get; set; } + public LogLevel LogLevel { get; set; } = LogLevel.Information; +} diff --git a/Src/GBX.NET.Tool.CLI/DynamicCodeMessages.cs b/Src/GBX.NET.Tool.CLI/DynamicCodeMessages.cs new file mode 100644 index 000000000..21bddb97f --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/DynamicCodeMessages.cs @@ -0,0 +1,9 @@ +namespace GBX.NET.Tool.CLI; + +internal static class DynamicCodeMessages +{ + internal const string MakeGenericTypeMessage = "This method uses reflection (MakeGenericType) to create collections for constructors."; + internal const string JsonSerializeMessage = "If context is null, this method uses reflection for JSON serialization and deserialization."; + internal const string DynamicRunMessage = "This method uses reflection (MakeGenericType) to create collections for constructors. Though if the tool does not use collections in constructors, it could work. ToolConsoleOptions.JsonSerializerContext should be also set for correct JSON serialization and deserialization. Please test the build."; + internal const string UnreferencedRunMessage = "ToolConsoleOptions.JsonSerializerContext should be set for correct JSON serialization and deserialization."; +} diff --git a/Src/GBX.NET.Tool.CLI/GBX.NET.Tool.CLI.csproj b/Src/GBX.NET.Tool.CLI/GBX.NET.Tool.CLI.csproj index 0eeb36c00..2d6f00d8e 100644 --- a/Src/GBX.NET.Tool.CLI/GBX.NET.Tool.CLI.csproj +++ b/Src/GBX.NET.Tool.CLI/GBX.NET.Tool.CLI.csproj @@ -1,17 +1,65 @@  - net8.0 + GBX.NET.Tool.CLI + 0.1.0 + BigBang1112 + CLI implementation for the GBX.NET tool framework using Spectre.Console. + Copyright (c) 2024 Petr Pivoňka + https://github.com/BigBang1112/gbx-net + logo_icon_outline.png + README.md + gbx, tool, cli, console, trackmania, shootmania, maniaplanet, gamebox, net, chunk + + GPL-3.0-or-later + true + + + + net8.0 + 12 enable enable + true true + + true + true + snupkg + + true + true + + false + bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers + + + + diff --git a/Src/GBX.NET.Tool.CLI/Inputs/DirectoryInput.cs b/Src/GBX.NET.Tool.CLI/Inputs/DirectoryInput.cs new file mode 100644 index 000000000..9b47c4c1e --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/Inputs/DirectoryInput.cs @@ -0,0 +1,27 @@ + +using GBX.NET.Exceptions; + +namespace GBX.NET.Tool.CLI.Inputs; + +internal sealed record DirectoryInput(string DirectoryPath) : Input +{ + public override async Task ResolveAsync(CancellationToken cancellationToken) + { + var files = Directory.GetFiles(DirectoryPath, "*.*", SearchOption.AllDirectories); + + var tasks = files.Select>(async file => + { + try + { + await using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); + return await Gbx.ParseAsync(stream, cancellationToken: cancellationToken); + } + catch (NotAGbxException) + { + return await File.ReadAllBytesAsync(file, cancellationToken); + } + }); + + return await Task.WhenAll(tasks); + } +} diff --git a/Src/GBX.NET.Tool.CLI/Inputs/FileInput.cs b/Src/GBX.NET.Tool.CLI/Inputs/FileInput.cs new file mode 100644 index 000000000..9ab93ce2b --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/Inputs/FileInput.cs @@ -0,0 +1,20 @@ + +using GBX.NET.Exceptions; + +namespace GBX.NET.Tool.CLI.Inputs; + +internal sealed record FileInput(string FilePath) : Input +{ + public override async Task ResolveAsync(CancellationToken cancellationToken) + { + try + { + await using var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); + return await Gbx.ParseAsync(stream, cancellationToken: cancellationToken); + } + catch (NotAGbxException) + { + return File.ReadAllBytesAsync(FilePath, cancellationToken); + } + } +} diff --git a/Src/GBX.NET.Tool.CLI/Inputs/Input.cs b/Src/GBX.NET.Tool.CLI/Inputs/Input.cs new file mode 100644 index 000000000..68ed465e6 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/Inputs/Input.cs @@ -0,0 +1,7 @@ + +namespace GBX.NET.Tool.CLI.Inputs; + +internal abstract record Input +{ + public abstract Task ResolveAsync(CancellationToken cancellationToken); +} diff --git a/Src/GBX.NET.Tool.CLI/Inputs/UriInput.cs b/Src/GBX.NET.Tool.CLI/Inputs/UriInput.cs new file mode 100644 index 000000000..807d2d6f9 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/Inputs/UriInput.cs @@ -0,0 +1,24 @@ + +using GBX.NET.Exceptions; + +namespace GBX.NET.Tool.CLI.Inputs; + +internal sealed record UriInput(HttpClient Http, Uri Uri) : Input +{ + public override async Task ResolveAsync(CancellationToken cancellationToken) + { + using var response = await Http.GetAsync(Uri, cancellationToken); + + response.EnsureSuccessStatusCode(); + + try + { + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + return await Gbx.ParseAsync(stream, cancellationToken: cancellationToken); + } + catch (NotAGbxException) + { + return await response.Content.ReadAsByteArrayAsync(cancellationToken); + } + } +} diff --git a/Src/GBX.NET.Tool.CLI/Json/ToolJsonContext.cs b/Src/GBX.NET.Tool.CLI/Json/ToolJsonContext.cs new file mode 100644 index 000000000..94f406b19 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/Json/ToolJsonContext.cs @@ -0,0 +1,7 @@ +using System.Text.Json.Serialization; + +namespace GBX.NET.Tool.CLI; + +[JsonSerializable(typeof(ConsoleSettings))] +[JsonSourceGenerationOptions(WriteIndented = true)] +internal sealed partial class ToolJsonContext : JsonSerializerContext; diff --git a/Src/GBX.NET.Tool.CLI/LICENSE b/Src/GBX.NET.Tool.CLI/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Src/GBX.NET.Tool.CLI/OutputDistributor.cs b/Src/GBX.NET.Tool.CLI/OutputDistributor.cs new file mode 100644 index 000000000..1a37ff6cb --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/OutputDistributor.cs @@ -0,0 +1,65 @@ +namespace GBX.NET.Tool.CLI; + +internal sealed class OutputDistributor +{ + private readonly string runningDir; + private readonly ToolSettings toolSettings; + private readonly SpectreConsoleLogger logger; + + private readonly string outputDir; + + public OutputDistributor(string runningDir, ToolSettings toolSettings, SpectreConsoleLogger logger) + { + this.runningDir = runningDir; + this.toolSettings = toolSettings; + this.logger = logger; + + outputDir = string.IsNullOrWhiteSpace(toolSettings.ConsoleSettings.OutputDirPath) + ? Path.Combine(runningDir, "Output") + : toolSettings.ConsoleSettings.OutputDirPath; + } + + public async Task DistributeOutputsAsync(IEnumerable outputs, CancellationToken cancellationToken) + { + foreach (var output in outputs) + { + await DistributeOutputAsync(output, cancellationToken); + } + } + + public async ValueTask DistributeOutputAsync(object? output, CancellationToken cancellationToken) + { + switch (output) + { + case IEnumerable objList: + await DistributeOutputsAsync(objList, cancellationToken); + break; + case null: + break; + case Gbx gbx: + var filePath = gbx.FilePath ?? "Generated.Gbx"; + + if (toolSettings.ConsoleSettings.DirectOutput) + { + filePath = Path.GetFileName(filePath); + } + + var finalPath = Path.Combine(outputDir, filePath); + var dirPath = Path.GetDirectoryName(finalPath); + + if (!string.IsNullOrWhiteSpace(dirPath)) + { + Directory.CreateDirectory(dirPath); + } + + await using (var fs = new FileStream(finalPath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true)) + { + gbx.Save(fs); + } + + break; + default: + throw new NotSupportedException($"Output type '{output.GetType().Name}' is not supported."); + } + } +} \ No newline at end of file diff --git a/Src/GBX.NET.Tool.CLI/README.md b/Src/GBX.NET.Tool.CLI/README.md new file mode 100644 index 000000000..b570ff513 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/README.md @@ -0,0 +1,14 @@ +# GBX.NET.Tool.CLI + +[![NuGet](https://img.shields.io/nuget/vpre/GBX.NET.Tool.CLI?style=for-the-badge&logo=nuget)](https://www.nuget.org/packages/GBX.NET.Tool.CLI/) +[![Discord](https://img.shields.io/discord/1012862402611642448?style=for-the-badge&logo=discord)](https://discord.gg/tECTQcAWC9) + +CLI implementation for the GBX.NET tool framework using `Spectre.Console`. + +## Framework support + +- .NET 8 + +## License + +GBX.NET.Tool.CLI library is GNU GPL v3 Licensed. \ No newline at end of file diff --git a/Src/GBX.NET.Tool.CLI/SettingsManager.cs b/Src/GBX.NET.Tool.CLI/SettingsManager.cs new file mode 100644 index 000000000..2c6ceb3c3 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/SettingsManager.cs @@ -0,0 +1,141 @@ +using Microsoft.Extensions.Logging; +using Spectre.Console; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace GBX.NET.Tool.CLI; + +internal sealed class SettingsManager +{ + private static readonly JsonSerializerOptions jsonOptions = new() + { + WriteIndented = true + }; + + private readonly string runningDir; + + public SettingsManager(string runningDir) + { + this.runningDir = runningDir; + } + + public async Task GetOrCreateFileAsync( + string fileName, + JsonTypeInfo typeInfo, + bool resetOnException = false, + ILogger? logger = null, + CancellationToken cancellationToken = default) where T : new() + { + T result; + + var filePath = Path.Combine(runningDir, fileName + ".json"); + + if (File.Exists(filePath)) + { + logger?.LogDebug("File {FileName} exists. Deserializing...", fileName); + + try + { + await using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: true); + result = await JsonSerializer.DeserializeAsync(fs, typeInfo, cancellationToken) ?? new(); + } + catch (Exception ex) + { + if (!resetOnException) + { + throw; + } + + AnsiConsole.WriteException(ex); + + result = new(); + } + } + else + { + result = new(); + + logger?.LogDebug("File {FileName} does not exist.", fileName); + + var directory = Path.GetDirectoryName(filePath); + + if (!string.IsNullOrWhiteSpace(directory)) + { + Directory.CreateDirectory(directory); + } + } + + logger?.LogDebug("Creating and serializing {FileName}...", fileName); + + await using var fsCreate = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true); + await JsonSerializer.SerializeAsync(fsCreate, result, typeInfo, cancellationToken); + + return result; + } + + [RequiresDynamicCode(DynamicCodeMessages.JsonSerializeMessage)] + [RequiresUnreferencedCode(DynamicCodeMessages.JsonSerializeMessage)] + public async Task PopulateConfigAsync(string configName, Config config, JsonSerializerContext? context, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrWhiteSpace(configName); + + var configType = config.GetType(); + var existingConfig = default(Config); + + var configDir = Path.Combine(runningDir, "Config", configName); + var mainConfigFilePath = Path.Combine(configDir, "Config.json"); + + if (File.Exists(mainConfigFilePath)) + { + await using var fs = new FileStream(mainConfigFilePath, FileMode.Open, FileAccess.Read, FileShare.None, 4096, useAsync: true); + + existingConfig = context is null + ? (Config?)await JsonSerializer.DeserializeAsync(fs, configType, jsonOptions, cancellationToken) + : (Config?)await JsonSerializer.DeserializeAsync(fs, configType, context, cancellationToken: cancellationToken); + } + else + { + Directory.CreateDirectory(configDir); + } + + foreach (var prop in configType.GetProperties().Where(x => x.CanWrite)) + { + if (existingConfig is not null) + { + prop.SetValue(config, prop.GetValue(existingConfig)); + } + + if (Attribute.IsDefined(prop, typeof(ExternalFileAttribute))) + { + var att = prop.GetCustomAttribute()!; + + var filePath = Path.Combine(configDir, att.FileName + ".json"); + + if (File.Exists(filePath)) + { + await using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 4096, useAsync: true); + + var value = context is null + ? await JsonSerializer.DeserializeAsync(fs, prop.PropertyType, jsonOptions, cancellationToken) + : await JsonSerializer.DeserializeAsync(fs, prop.PropertyType, context, cancellationToken: cancellationToken); + + prop.SetValue(config, value); + } + } + } + + await using var fsCreate = new FileStream(mainConfigFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true); + + if (context is null) + { + await JsonSerializer.SerializeAsync(fsCreate, config, configType, jsonOptions, cancellationToken); + } + else + { + await JsonSerializer.SerializeAsync(fsCreate, config, configType, context, cancellationToken); + } + } +} diff --git a/Src/GBX.NET.Tool.CLI/SpectreConsoleLogger.cs b/Src/GBX.NET.Tool.CLI/SpectreConsoleLogger.cs index 3141c6ad0..372730402 100644 --- a/Src/GBX.NET.Tool.CLI/SpectreConsoleLogger.cs +++ b/Src/GBX.NET.Tool.CLI/SpectreConsoleLogger.cs @@ -29,7 +29,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except return; } - AnsiConsole.MarkupLine($" {GetLevelString(logLevel)} {formatter(state, exception)}"); + AnsiConsole.MarkupLine($" {GetLevelString(logLevel)} {Markup.Escape(formatter(state, exception))}"); } private static string GetLevelString(LogLevel level) => level switch diff --git a/Src/GBX.NET.Tool.CLI/ToolConsole.cs b/Src/GBX.NET.Tool.CLI/ToolConsole.cs index 730c3e7e6..f1118496f 100644 --- a/Src/GBX.NET.Tool.CLI/ToolConsole.cs +++ b/Src/GBX.NET.Tool.CLI/ToolConsole.cs @@ -1,29 +1,68 @@ -using GBX.NET.Tool.CLI.Exceptions; +using GBX.NET.LZO; +using GBX.NET.Tool.CLI.Exceptions; using Microsoft.Extensions.Logging; using Spectre.Console; using System.Diagnostics.CodeAnalysis; namespace GBX.NET.Tool.CLI; -public class ToolConsole<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces | DynamicallyAccessedMemberTypes.PublicConstructors)] T> where T : class, ITool +/// +/// Represents the CLI implementation of GBX.NET tool. +/// +/// Tool type. +public class ToolConsole<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces | DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods)] T> where T : class, ITool { private readonly string[] args; private readonly HttpClient http; + private readonly ToolConsoleOptions options; - public ToolConsole(string[] args, HttpClient http) + private readonly string runningDir; + private readonly SettingsManager settingsManager; + private readonly ArgsResolver argsResolver; + + private bool noPause; + + /// + /// Initializes a new instance of the class. + /// + /// Command line arguments. + /// HTTP client to use for requests. + /// Options for the tool console. These should be hardcoded for purpose. + /// , , or is null. + public ToolConsole(string[] args, HttpClient http, ToolConsoleOptions options) + { + this.args = args ?? throw new ArgumentNullException(nameof(args)); + this.http = http ?? throw new ArgumentNullException(nameof(http)); + this.options = options ?? throw new ArgumentNullException(nameof(options)); + + runningDir = AppDomain.CurrentDomain.BaseDirectory; + settingsManager = new SettingsManager(runningDir); + argsResolver = new ArgsResolver(args, http); + } + + static ToolConsole() { - this.args = args; - this.http = http; + Gbx.LZO = new Lzo(); } - public static async Task> RunAsync(string[] args) + /// + /// Runs the tool CLI implementation with the specified arguments. + /// + /// Command line arguments. Use the 'args' keyword here. + /// Options for the tool console. These should be hardcoded for purpose. + /// Result of the tool execution (if wanted to use later). + [RequiresDynamicCode(DynamicCodeMessages.DynamicRunMessage)] + [RequiresUnreferencedCode(DynamicCodeMessages.UnreferencedRunMessage)] + public static async Task> RunAsync(string[] args, ToolConsoleOptions? options = null) { + ArgumentNullException.ThrowIfNull(args); + using var http = new HttpClient(); - http.DefaultRequestHeaders.Add("User-Agent", "GBX.NET.Tool.CLI"); + http.DefaultRequestHeaders.UserAgent.ParseAdd("GBX.NET.Tool.CLI"); using var cts = new CancellationTokenSource(); - var tool = new ToolConsole(args, http); + var tool = new ToolConsole(args, http, options ?? new()); try { @@ -32,76 +71,247 @@ public static async Task> RunAsync(string[] args) catch (ConsoleProblemException ex) { AnsiConsole.MarkupInterpolated($"[yellow]{ex.Message}[/]"); - AnsiConsole.WriteLine(); - AnsiConsole.Markup("Press any key to continue..."); - Console.ReadKey(true); } catch (OperationCanceledException) { AnsiConsole.Markup("[yellow]Operation canceled.[/]"); - AnsiConsole.WriteLine(); - AnsiConsole.Markup("Press any key to continue..."); - Console.ReadKey(true); } catch (Exception ex) { AnsiConsole.WriteException(ex); - AnsiConsole.WriteLine(); - AnsiConsole.Markup("Press any key to continue..."); - Console.ReadKey(true); + } + + if (!tool.noPause) + { + PressAnyKeyToContinue(); } return new ToolConsoleRunResult(tool); } + [RequiresDynamicCode(DynamicCodeMessages.DynamicRunMessage)] + [RequiresUnreferencedCode(DynamicCodeMessages.UnreferencedRunMessage)] private async Task RunAsync(CancellationToken cancellationToken) { + // Load console settings from file if exists otherwise create one + var consoleSettings = await settingsManager.GetOrCreateFileAsync("ConsoleSettings", + ToolJsonContext.Default.ConsoleSettings, + cancellationToken: cancellationToken); + + var toolSettings = argsResolver.Resolve(consoleSettings); + + // Not ideal mutative state, but it's fine for now + noPause = toolSettings.ConsoleSettings.NoPause; + + var logger = new SpectreConsoleLogger(toolSettings.ConsoleSettings.LogLevel); + + logger.LogDebug("Running directory: {RunningDir}", runningDir); + logger.LogDebug("CLI settings from file: {Settings}", toolSettings.ConsoleSettings); + logger.LogDebug("Settings/config overwrites: {Overwrites}", toolSettings.ConfigOverwrites.Count == 0 + ? "None" + : string.Join(", ", toolSettings.ConfigOverwrites.Select(kv => $"{kv.Key}={kv.Value}"))); + logger.LogDebug("Inputs: {Inputs}", toolSettings.Inputs.Count == 0 + ? "None" + : string.Join(", ", toolSettings.Inputs)); + logger.LogTrace("No pause: {NoPause}", noPause); + + var introWriterTask = default(Task); + + if (!toolSettings.ConsoleSettings.SkipIntro) + { + introWriterTask = IntroWriter.WriteIntroAsync(args); + } + + logger.LogTrace("Checking for updates..."); + // Request update info and additional stuff - var updateChecker = ToolUpdateChecker.Check(http); - - await IntroWriter.WriteIntroAsync(args); + var updateChecker = toolSettings.ConsoleSettings.DisableUpdateCheck + ? null + : ToolUpdateChecker.Check(http, cancellationToken); + + if (introWriterTask is not null) + { + await introWriterTask; + logger.LogTrace("Intro finished."); + } // Check for updates here if received. If not, check at the end of the tool execution - var updateCheckCompleted = await updateChecker.TryCompareVersionAsync(cancellationToken); + var updateCheckCompleted = updateChecker is null + || await updateChecker.TryCompareVersionAsync(); + + logger.LogDebug("Update check completed: {UpdateCheckCompleted}", updateCheckCompleted); AnsiConsole.WriteLine(); - var logger = new SpectreConsoleLogger(); + // See what the tool can do + var toolFunctionality = ToolFunctionalityResolver.Resolve(logger); + + if (toolSettings.Inputs.Count == 0) + { + // write tool specific intro + if (!string.IsNullOrWhiteSpace(options.IntroText)) + { + AnsiConsole.WriteLine(); + AnsiConsole.WriteLine(options.IntroText); + } + + if (!updateCheckCompleted && updateChecker is not null) + { + await updateChecker.CompareVersionAsync(); + } + + AnsiConsole.WriteLine(); + + throw new ConsoleProblemException("No files were passed to the tool.\nPlease drag and drop files onto the executable, or include the input paths as the command line arguments.\nFile paths, directory paths, or URLs are supported in any order."); + } // If the tool has setup, apply tool things below to setup - // See what the tool can do - var toolFunctionality = ToolFunctionalityResolver.Resolve(logger); + var toolInstanceMaker = new ToolInstanceMaker(toolFunctionality, toolSettings, logger); + var outputDistributor = new OutputDistributor(runningDir, toolSettings, logger); - // Read the files from the arguments - // Quickly invalidate ones that do not meet functionality + AnsiConsole.WriteLine(); + logger.LogInformation("Starting tool instance creation..."); + AnsiConsole.WriteLine(); + var counter = 0; - // Check again for updates if not done before - if (!updateCheckCompleted) + await foreach (var toolInstance in toolInstanceMaker.MakeToolInstancesAsync(cancellationToken)) { - updateCheckCompleted = await updateChecker.TryCompareVersionAsync(cancellationToken); - } + counter++; + logger.LogInformation("Tool instance #{Number} created.", counter); - // Instantiate the tool + // Load config into each instance (may be worth caching later) - // Run all produce methods in parallel and run mutate methods in sequence + if (toolInstance is IConfigurable configurable) + { + var configName = string.IsNullOrWhiteSpace(toolSettings.ConsoleSettings.ConfigName) ? "Default" + : toolSettings.ConsoleSettings.ConfigName; + + logger.LogInformation("Populating tool config (name: {ConfigName}, type: {ConfigType})...", configName, typeof(Config)); + + await settingsManager.PopulateConfigAsync(configName, configurable.Config, options.JsonSerializerContext, cancellationToken); + } + + // Run all produce methods in parallel and run mutate methods in sequence + + if (toolFunctionality.ProduceMethods.Length == 1) + { + logger.LogInformation("Producing..."); + + var produceMethod = toolFunctionality.ProduceMethods[0]; + var result = produceMethod.Invoke(toolInstance, null); + + if (result is IEnumerable) + { + logger.LogInformation("Producing for each distributed output..."); + } + else + { + logger.LogInformation("Produced! Distributing output..."); + } - await AnsiConsole.Progress() - .StartAsync(async ctx => + await outputDistributor.DistributeOutputAsync(result, cancellationToken); + } + else if (toolFunctionality.ProduceMethods.Length > 1) { - // Define tasks - var task1 = ctx.AddTask("[green]Reticulating splines[/]"); - var task2 = ctx.AddTask("[green]Folding space[/]"); + logger.LogInformation("Producing ({Count} methods)...", toolFunctionality.ProduceMethods.Length); + + var produceTasks = toolFunctionality.ProduceMethods + .Select(method => Task.Run(() => method.Invoke(toolInstance, null))) + .ToList(); - while (!ctx.IsFinished) + while (produceTasks.Count > 0) { - // Simulate some work - await Task.Delay(250); + var completedTask = await Task.WhenAny(produceTasks); + produceTasks.Remove(completedTask); + + var result = completedTask.Result; - // Increment - task1.Increment(1.5); - task2.Increment(0.5); + if (result is IEnumerable) + { + if (produceTasks.Count > 0) + { + logger.LogInformation("Producing for each distributed output ({Count} remaining)...", produceTasks.Count); + } + else + { + logger.LogInformation("Producing for each distributed output (last output)..."); + } + } + else + { + if (produceTasks.Count > 0) + { + logger.LogInformation("Produced! Distributing output ({Count} remaining)...", produceTasks.Count); + } + else + { + logger.LogInformation("Produced! Distributing last output..."); + } + } + + await outputDistributor.DistributeOutputAsync(result, cancellationToken); } - }); + } + + if (toolFunctionality.MutateMethods.Length == 1) + { + logger.LogInformation("Mutating..."); + + var mutateMethod = toolFunctionality.MutateMethods[0]; + var result = mutateMethod.Invoke(toolInstance, null); + + if (result is IEnumerable) + { + logger.LogInformation("Mutationing while distributing output..."); + } + else + { + logger.LogInformation("Mutated! Distributing output..."); + } + + await outputDistributor.DistributeOutputAsync(result, cancellationToken); + } + else if (toolFunctionality.MutateMethods.Length > 1) + { + for (int i = 0; i < toolFunctionality.MutateMethods.Length; i++) + { + logger.LogInformation("Mutating ({Count}/{Total})...", i + 1, toolFunctionality.MutateMethods.Length); + + var mutateMethod = toolFunctionality.MutateMethods[i]; + var result = mutateMethod.Invoke(toolInstance, null); + + if (result is IEnumerable) + { + logger.LogInformation("Mutating while distributing output..."); + } + else + { + logger.LogInformation("Mutated! Distributing output..."); + } + + await outputDistributor.DistributeOutputAsync(result, cancellationToken); + } + } + + logger.LogInformation("Tool instance #{Number} completed.", counter); + } + + AnsiConsole.WriteLine(); + + logger.LogInformation("Completed!"); + + // Check again for updates if not done before + if (!updateCheckCompleted && updateChecker is not null) + { + await updateChecker.CompareVersionAsync(); + } + } + + private static void PressAnyKeyToContinue() + { + AnsiConsole.WriteLine(); + AnsiConsole.Markup("Press any key to continue..."); + Console.ReadKey(true); } } diff --git a/Src/GBX.NET.Tool.CLI/ToolConsoleOptions.cs b/Src/GBX.NET.Tool.CLI/ToolConsoleOptions.cs new file mode 100644 index 000000000..4fdd50e96 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/ToolConsoleOptions.cs @@ -0,0 +1,9 @@ +using System.Text.Json.Serialization; + +namespace GBX.NET.Tool.CLI; + +public sealed record ToolConsoleOptions +{ + public string IntroText { get; init; } = string.Empty; + public JsonSerializerContext? JsonSerializerContext { get; init; } +} diff --git a/Src/GBX.NET.Tool.CLI/ToolConsoleRunResult.cs b/Src/GBX.NET.Tool.CLI/ToolConsoleRunResult.cs index 9f56ae551..e1c48f0fa 100644 --- a/Src/GBX.NET.Tool.CLI/ToolConsoleRunResult.cs +++ b/Src/GBX.NET.Tool.CLI/ToolConsoleRunResult.cs @@ -2,5 +2,5 @@ namespace GBX.NET.Tool.CLI; -public sealed record ToolConsoleRunResult<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces | DynamicallyAccessedMemberTypes.PublicConstructors)] T>(ToolConsole Tool) +public sealed record ToolConsoleRunResult<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces | DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods)] T>(ToolConsole Tool) where T : class, ITool; diff --git a/Src/GBX.NET.Tool.CLI/ToolInstanceMaker.cs b/Src/GBX.NET.Tool.CLI/ToolInstanceMaker.cs new file mode 100644 index 000000000..3d4c9a1ba --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/ToolInstanceMaker.cs @@ -0,0 +1,283 @@ +using GBX.NET.Tool.CLI.Exceptions; +using GBX.NET.Tool.CLI.Inputs; +using Microsoft.Extensions.Logging; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace GBX.NET.Tool.CLI; + +internal sealed class ToolInstanceMaker where T : ITool +{ + private readonly ToolFunctionality toolFunctionality; + private readonly ToolSettings toolSettings; + private readonly ILogger logger; + + private readonly Dictionary resolvedInputs = []; + private readonly HashSet usedObjects = []; + private readonly List unprocessedObjects = []; + + public ToolInstanceMaker(ToolFunctionality toolFunctionality, ToolSettings toolSettings, ILogger logger) + { + this.toolFunctionality = toolFunctionality; + this.toolSettings = toolSettings; + this.logger = logger; + } + + [RequiresDynamicCode(DynamicCodeMessages.MakeGenericTypeMessage)] + public async IAsyncEnumerable MakeToolInstancesAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + // Each loop iteration defines tool instance + do + { + var paramsForCtor = Array.Empty(); + var pickedCtor = default(ConstructorInfo); + + logger.LogInformation("Resolving new tool instance..."); + + // Tries to pick the FIRST valid constructor + foreach (var constructor in toolFunctionality.Constructors) + { + // Tests the constructor with input values + // If successful, returns the array of parameters to provide to it + // The array can be empty if parameterless constructor was picked + // If not, null is returned + paramsForCtor = await TryPickConstructorAsync(constructor, cancellationToken); + + if (paramsForCtor is not null) + { + pickedCtor = constructor; + break; + } + + logger.LogInformation("Constructor {Constructor} is not valid with these inputs.", constructor); + } + + // If no valid constructor was found + if (pickedCtor is null) + { + logger.LogWarning("No valid constructor found for the tool."); + throw new ConsoleProblemException("Invalid files passed to the tool."); + } + + logger.LogInformation("Creating new tool instance..."); + + // Instantiate the tool + yield return (T)pickedCtor.Invoke(paramsForCtor); + } + while (unprocessedObjects.Count > 0); + // Continue creating more tool instances if there are unused resolved objects left + } + + [RequiresDynamicCode(DynamicCodeMessages.MakeGenericTypeMessage)] + private async Task TryPickConstructorAsync(ConstructorInfo constructor, CancellationToken cancellationToken) + { + var parameters = constructor.GetParameters(); + + if (parameters.Length == 0) + { + // inputless tools? + return []; + } + + var paramsForCtor = new object[parameters.Length]; + var index = 0; + + foreach (var parameter in parameters) + { + var type = parameter.ParameterType; + + // Non-generic types + + if (type == typeof(ILogger)) + { + paramsForCtor[index++] = logger; + continue; + } + + if (type == typeof(Gbx)) + { + // Retrieve the next unused resolved object of any Gbx type + // Null is returned if there's no match + var paramObj = await GetParameterObjectAsync(obj => obj is Gbx, cancellationToken); + + if (paramObj is null) + { + // Constructor is not valid for this configuration + return null; + } + + paramsForCtor[index++] = paramObj; + continue; + } + + if (!type.IsGenericType) + { + continue; + } + + // Generic types + + var typeDef = type.GetGenericTypeDefinition(); + + if (typeDef == typeof(Gbx<>)) + { + var nodeType = type.GetGenericArguments()[0]; + + // Retrieve the next unused resolved object of Gbx with this generic arg type (no covariance) + // Null is returned if there's no match + var paramObj = await GetParameterObjectAsync(obj => obj is Gbx gbx && gbx.Node?.GetType() == nodeType, cancellationToken); + + if (paramObj is null) + { + // Constructor is not valid for this configuration + return null; + } + + paramsForCtor[index++] = paramObj; + continue; + } + + // Currently only generic IEnumerable<> is recognized from collections + if (typeDef == typeof(IEnumerable<>)) + { + var elementType = type.GetGenericArguments()[0]; + + // Create a List to populate and pass to constructor + // This cannot be handled properly in NativeAOT complication + var finalCollection = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType))!; + + // Maybe unprocessedObjects logic missing here? + // Could break if there's single Gbx param and then an IEnumerable afterwards + + // Resolve inputs into individual objects, iterated one by one (no collection should appear here) + await foreach (var resolvedObject in EnumerateResolvedObjectsAsync(cancellationToken)) + { + // objects that were already sent to parameters should not be provided again in next instances + if (usedObjects.Contains(resolvedObject)) + { + continue; + } + + // Only objects that match the exact element type will be counted (for now) + if (resolvedObject.GetType() == elementType) + { + // Object is added to the list that will be passed to the constructor + finalCollection.Add(resolvedObject); + usedObjects.Add(resolvedObject); + } + else + { + // Objects that don't match the type are saved for later checks + unprocessedObjects.Add(resolvedObject); + } + } + + paramsForCtor[index++] = finalCollection; + + continue; + } + } + + return paramsForCtor; + } + + private async Task GetParameterObjectAsync(Predicate predicate, CancellationToken cancellationToken) + { + // if there are leftover objects from previous instance + if (unprocessedObjects.Count > 0) + { + var obj = unprocessedObjects[0]; + + // check if the leftover fits this parameter + if (predicate(obj)) + { + usedObjects.Add(obj); + unprocessedObjects.RemoveAt(0); + return obj; + } + } + + var paramForCtor = default(object); + + // Resolve inputs into individual objects, iterated one by one (no collection should appear here) + await foreach (var resolvedObject in EnumerateResolvedObjectsAsync(cancellationToken)) + { + // objects that were already sent to parameters should not be provided again in next instances + if (usedObjects.Contains(resolvedObject)) + { + continue; + } + + // Only objects that match the predicate will be used for the parameter + // It doesn't need to know the ctor parameter type, but the object HAS to be implicitly castable to the ctor type + if (predicate(resolvedObject)) + { + // If there's already a parameter object, save the new one for later checks + if (paramForCtor is not null) + { + unprocessedObjects.Add(resolvedObject); + continue; + } + + paramForCtor = resolvedObject; + usedObjects.Add(resolvedObject); + } + } + + return paramForCtor; + } + + private async IAsyncEnumerable EnumerateResolvedObjectsAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + foreach (var input in toolSettings.Inputs) + { + // Resolve objects from input and cache them + if (!resolvedInputs.TryGetValue(input, out var resolvedObject)) + { + resolvedObject = await input.ResolveAsync(cancellationToken); + resolvedInputs.Add(input, resolvedObject); + } + + // Skip unresolved inputs + if (resolvedObject is null) + { + continue; + } + + // If resolved object is a collection, iterate through it immediately + // Collection in a collection is not supported + if (resolvedObject is IEnumerable enumerable) + { + foreach (var obj in enumerable) + { + if (obj is IEnumerable) + { + continue; + } + + yield return obj; + } + } + else + { + yield return resolvedObject; + } + } + } + + private static bool IsTypeOrBaseType(Type? givenType, Type expectedType) + { + while (givenType is not null) + { + if (givenType == expectedType) + { + return true; + } + + givenType = givenType.BaseType; + } + + return false; + } +} diff --git a/Src/GBX.NET.Tool.CLI/ToolSettings.cs b/Src/GBX.NET.Tool.CLI/ToolSettings.cs new file mode 100644 index 000000000..bb7f6c7c2 --- /dev/null +++ b/Src/GBX.NET.Tool.CLI/ToolSettings.cs @@ -0,0 +1,10 @@ +using GBX.NET.Tool.CLI.Inputs; + +namespace GBX.NET.Tool.CLI; + +internal sealed class ToolSettings +{ + public ConsoleSettings ConsoleSettings { get; init; } = new(); + public Dictionary ConfigOverwrites { get; init; } = []; + public IReadOnlyCollection Inputs { get; init; } = []; +} diff --git a/Src/GBX.NET.Tool.CLI/ToolUpdateChecker.cs b/Src/GBX.NET.Tool.CLI/ToolUpdateChecker.cs index e3b6798bd..dfec2ad1d 100644 --- a/Src/GBX.NET.Tool.CLI/ToolUpdateChecker.cs +++ b/Src/GBX.NET.Tool.CLI/ToolUpdateChecker.cs @@ -11,19 +11,26 @@ public ToolUpdateChecker(Task updateInfoResponseTask) this.updateInfoResponseTask = updateInfoResponseTask; } - public static ToolUpdateChecker Check(HttpClient client) + public static ToolUpdateChecker Check(HttpClient client, CancellationToken cancellationToken) { - var responseTask = client.GetAsync("https://api.github.com/repos/GBX.NET/GBX.NET.Tool/releases/latest"); + var responseTask = client.GetAsync("https://api.github.com/repos/GBX.NET/GBX.NET.Tool/releases/latest", cancellationToken); return new ToolUpdateChecker(responseTask); } - public async ValueTask TryCompareVersionAsync(CancellationToken cancellationToken) + public async ValueTask TryCompareVersionAsync() { if (!updateInfoResponseTask.IsCompleted) { return false; } + await CompareVersionAsync(); + + return true; + } + + public async Task CompareVersionAsync() + { AnsiConsole.WriteLine(); var updateInfoResponse = await updateInfoResponseTask; @@ -52,7 +59,5 @@ public async ValueTask TryCompareVersionAsync(CancellationToken cancellati AnsiConsole.WriteLine(); AnsiConsole.Write(new Rule().RuleStyle("yellow dim")); } - - return true; } } diff --git a/Src/GBX.NET.Tool/ExternalFileAttribute.cs b/Src/GBX.NET.Tool/ExternalFileAttribute.cs new file mode 100644 index 000000000..7d41d7fb9 --- /dev/null +++ b/Src/GBX.NET.Tool/ExternalFileAttribute.cs @@ -0,0 +1,11 @@ +namespace GBX.NET.Tool; + +/// +/// Attribute to mark a config property to be serialized as an external file. +/// +/// The name of the file to be created and read from. +[AttributeUsage(AttributeTargets.Property)] +public class ExternalFileAttribute(string fileName) : Attribute +{ + public string FileName { get; } = fileName; +} diff --git a/Src/GBX.NET.Tool/GBX.NET.Tool.csproj b/Src/GBX.NET.Tool/GBX.NET.Tool.csproj index bac9d2484..964179ed5 100644 --- a/Src/GBX.NET.Tool/GBX.NET.Tool.csproj +++ b/Src/GBX.NET.Tool/GBX.NET.Tool.csproj @@ -1,11 +1,58 @@  - net8.0 + GBX.NET.Tool + 0.1.0 + BigBang1112 + Base library for creating rich tools for different environments with GBX.NET. + Copyright (c) 2024 Petr Pivoňka + https://github.com/BigBang1112/gbx-net + logo_icon_outline.png + README.md + gbx, tool, trackmania, shootmania, maniaplanet, gamebox, net, chunk + + MIT + + + + net8.0 + 12 enable enable + true + true + + true + true + snupkg + + true + true + + false + bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers + + + diff --git a/Src/GBX.NET.Tool/IConfigurable.cs b/Src/GBX.NET.Tool/IConfigurable.cs index f2c6e4fee..2302eed71 100644 --- a/Src/GBX.NET.Tool/IConfigurable.cs +++ b/Src/GBX.NET.Tool/IConfigurable.cs @@ -1,6 +1,6 @@ namespace GBX.NET.Tool; -public interface IConfigurable where TConfig : Config +public interface IConfigurable where TConfig : Config { - TConfig Config { get; set; } + TConfig Config { get; } } \ No newline at end of file diff --git a/Src/GBX.NET.Tool/README.md b/Src/GBX.NET.Tool/README.md new file mode 100644 index 000000000..0b3bb3889 --- /dev/null +++ b/Src/GBX.NET.Tool/README.md @@ -0,0 +1,14 @@ +# GBX.NET.Tool + +[![NuGet](https://img.shields.io/nuget/vpre/GBX.NET.Tool?style=for-the-badge&logo=nuget)](https://www.nuget.org/packages/GBX.NET.Tool/) +[![Discord](https://img.shields.io/discord/1012862402611642448?style=for-the-badge&logo=discord)](https://discord.gg/tECTQcAWC9) + +Base library for creating rich tools for different environments with GBX.NET. + +## Framework support + +- .NET 8 + +## License + +GBX.NET.Tool library is MIT Licensed. \ No newline at end of file diff --git a/Src/GBX.NET.Tool/ToolFunctionality.cs b/Src/GBX.NET.Tool/ToolFunctionality.cs index 835689e49..baf4add6f 100644 --- a/Src/GBX.NET.Tool/ToolFunctionality.cs +++ b/Src/GBX.NET.Tool/ToolFunctionality.cs @@ -1,6 +1,11 @@ -namespace GBX.NET.Tool; +using System.Reflection; + +namespace GBX.NET.Tool; public sealed class ToolFunctionality where T : ITool { - public required object?[] InputParameters { get; init; } + public required ConstructorInfo[] Constructors { get; init; } + public required MethodInfo[] ProduceMethods { get; init; } + public required MethodInfo[] MutateMethods { get; init; } + public required Type? ConfigType { get; init; } } diff --git a/Src/GBX.NET.Tool/ToolFunctionalityResolver.cs b/Src/GBX.NET.Tool/ToolFunctionalityResolver.cs index 4d458d731..910ce9e2f 100644 --- a/Src/GBX.NET.Tool/ToolFunctionalityResolver.cs +++ b/Src/GBX.NET.Tool/ToolFunctionalityResolver.cs @@ -1,37 +1,87 @@ using Microsoft.Extensions.Logging; using System.Diagnostics.CodeAnalysis; +using System.Reflection; namespace GBX.NET.Tool; /// /// Resolves tool functionality to use in the tool console. /// -public sealed class ToolFunctionalityResolver<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces | DynamicallyAccessedMemberTypes.PublicConstructors)] T> where T : ITool +public sealed class ToolFunctionalityResolver<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces | DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods)] T> where T : ITool { public static ToolFunctionality Resolve(ILogger logger) { - logger.LogInformation("Resolving tool properties..."); + logger.LogInformation("Resolving tool functionality..."); - var type = typeof(T); + var ctors = ResolveConstructors(logger); - ResolveInterfaces(type); + ResolveInterfaces(out var produceMethods, out var mutateMethods, out var configType, logger); - var paramObjects = ResolveConstructors(type, logger); - - logger.LogInformation("Tool properties resolved successfully."); + logger.LogInformation("Tool functionality resolved successfully."); return new ToolFunctionality { - InputParameters = paramObjects + Constructors = ctors, + ProduceMethods = produceMethods, + MutateMethods = mutateMethods, + ConfigType = configType }; } - private static void ResolveInterfaces(Type type) + private static ConstructorInfo[] ResolveConstructors(ILogger logger) { - foreach (var interfaceType in type.GetInterfaces()) + var ctors = typeof(T).GetConstructors(); + + if (ctors.Length == 0) + { + throw new Exception("No public constructors found."); + } + + if (logger.IsEnabled(LogLevel.Information)) + { + foreach (var ctor in ctors) + { + var parameters = ctor.GetParameters(); + if (parameters.Length == 0) + { + logger.LogInformation("Default constructor found."); + continue; + } + + logger.LogInformation("Constructor with parameters found: {Parameters}", string.Join(", ", parameters.Select(x => FormatType(x.ParameterType)))); + } + + logger.LogInformation("The most suitable one will be picked to create tool instances."); + } + + return ctors; + } + + private static void ResolveInterfaces( + out MethodInfo[] produceMethods, + out MethodInfo[] mutateMethods, + out Type? configType, + ILogger logger) + { + var methods = typeof(T).GetMethods(); + + if (logger.IsEnabled(LogLevel.Debug)) + { + foreach (var method in methods) + { + logger.LogDebug("Public tool method: {MethodName}", method.Name); + } + } + + var prodMethods = new List(); + var mutMethods = new List(); + configType = null; + + foreach (var interfaceType in typeof(T).GetInterfaces()) { if (interfaceType == typeof(ITool)) { + logger.LogDebug("Tool interface found."); continue; } @@ -39,60 +89,43 @@ private static void ResolveInterfaces(Type type) if (genericType == typeof(IConfigurable<>)) { - var configType = interfaceType.GetGenericArguments()[0]; + configType = interfaceType.GetGenericArguments()[0]; + logger.LogInformation("Tool is configurable: {ConfigType}", FormatType(configType)); continue; } if (genericType == typeof(IProductive<>)) { var producedType = interfaceType.GetGenericArguments()[0]; + var method = methods.Single(m => m.Name == nameof(IProductive.Produce) && m.ReturnType == producedType); + prodMethods.Add(method); + logger.LogInformation("Tool produces new data: {ProducedType}", FormatType(producedType)); continue; } if (genericType == typeof(IMutative<>)) { var producedType = interfaceType.GetGenericArguments()[0]; + var method = methods.Single(m => m.Name == nameof(IMutative.Mutate) && m.ReturnType == producedType); + mutMethods.Add(method); + logger.LogInformation("Tool mutates data: {ProducedType} (in CLI, only mutated in memory)", FormatType(producedType)); continue; } } + + produceMethods = prodMethods.ToArray(); + mutateMethods = mutMethods.ToArray(); } - private static object?[] ResolveConstructors(Type type, ILogger logger) + private static string FormatType(Type type) { - foreach (var ctor in type.GetConstructors()) + if (type.IsGenericType) { - var parameters = ctor.GetParameters(); - - if (parameters.Length == 0) - { - // input-less tools? - continue; - } - - var ctorUsable = true; - var paramObjects = new object?[parameters.Length]; - - // Check for constructor parameters - for (int i = 0; i < parameters.Length; i++) - { - var parameter = parameters[i]; - - if (parameter.ParameterType == typeof(ILogger)) - { - paramObjects[i] = logger; - continue; - } - - ctorUsable = false; - break; - } - - if (ctorUsable) - { - return paramObjects; - } + var name = type.Name.Substring(0, type.Name.IndexOf('`')); + var args = type.GetGenericArguments().Select(FormatType); + return $"{name}<{string.Join(", ", args)}>"; } - return []; + return type.Name; } } diff --git a/Src/GBX.NET.ZLib/README.md b/Src/GBX.NET.ZLib/README.md index 8709da1d4..73033e73e 100644 --- a/Src/GBX.NET.ZLib/README.md +++ b/Src/GBX.NET.ZLib/README.md @@ -21,7 +21,7 @@ using GBX.NET.Engines.Game; using GBX.NET.LZO; using GBX.NET.ZLib; // Add this -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); Gbx.ZLib = new ZLib(); // Add this ONLY ONCE and before you start using Parse methods var ghost = Gbx.ParseNode("Path/To/My.Ghost.Gbx"); diff --git a/Src/GBX.NET/Color.cs b/Src/GBX.NET/Color.cs index 2285fae55..f0b4cb064 100644 --- a/Src/GBX.NET/Color.cs +++ b/Src/GBX.NET/Color.cs @@ -10,6 +10,7 @@ public Color(int argb) : this((argb >> 16) & 0xFF, (argb >> 8) & 0xFF, argb & 0x } public int ToArgb() => ((int)A << 24) | ((int)R << 16) | ((int)G << 8) | (int)B; + public int ToRgba() => ((int)A << 24) | ((int)B << 16) | ((int)G << 8) | (int)R; public override string ToString() { diff --git a/Src/GBX.NET/Components/GbxRefTable.cs b/Src/GBX.NET/Components/GbxRefTable.cs index f46dc17e3..f3b5f4ffc 100644 --- a/Src/GBX.NET/Components/GbxRefTable.cs +++ b/Src/GBX.NET/Components/GbxRefTable.cs @@ -37,7 +37,7 @@ public string GetFullFilePath(GbxRefTableFile file) return Path.GetFullPath(GetFilePath(file)); } - public CMwNod? LoadNode(GbxRefTableFile file, GbxReadSettings settings = default) + public CMwNod? LoadNode(GbxRefTableFile file, GbxReadSettings settings = default, bool exceptions = false) { if (file is null) { @@ -77,6 +77,12 @@ public string GetFullFilePath(GbxRefTableFile file) { scope?.Dispose(); logger?.LogError(ex, "Failed to load node from file: {FilePath}", filePath); + + if (exceptions) + { + throw; + } + return default; } } @@ -104,6 +110,12 @@ public string GetFullFilePath(GbxRefTableFile file) { scope?.Dispose(); logger?.LogError(ex, "Failed to load node from file: {Length} bytes", data.Length); + + if (exceptions) + { + throw; + } + return default; } } @@ -111,9 +123,9 @@ public string GetFullFilePath(GbxRefTableFile file) return default; } - public T? LoadNode(GbxRefTableFile file, GbxReadSettings settings = default) where T : CMwNod + public T? LoadNode(GbxRefTableFile file, GbxReadSettings settings = default, bool exceptions = false) where T : CMwNod { - return LoadNode(file, settings) as T; + return LoadNode(file, settings, exceptions) as T; } internal static GbxRefTable? Parse(GbxReader reader, GbxHeader header, string? fileSystemPath) diff --git a/Src/GBX.NET/Components/GbxRefTableFile.cs b/Src/GBX.NET/Components/GbxRefTableFile.cs index 8fb0ce42a..f45504213 100644 --- a/Src/GBX.NET/Components/GbxRefTableFile.cs +++ b/Src/GBX.NET/Components/GbxRefTableFile.cs @@ -14,14 +14,14 @@ public override string ToString() return $"{FilePath}, Flags: {Flags}, UseFile: {UseFile}"; } - public T? GetNode(ref T? cachedNode, GbxReadSettings settings = default) where T : CMwNod + public T? GetNode(ref T? cachedNode, GbxReadSettings settings = default, bool exceptions = false) where T : CMwNod { if (cachedNode is not null) { return cachedNode; } - return cachedNode = RefTable.LoadNode(this, settings); + return cachedNode = RefTable.LoadNode(this, settings, exceptions); } public string GetFullPath() diff --git a/Src/GBX.NET/Engines/Function/CFuncShaderLayerUV.chunkl b/Src/GBX.NET/Engines/Function/CFuncShaderLayerUV.chunkl index c9d410d3b..17f978898 100644 --- a/Src/GBX.NET/Engines/Function/CFuncShaderLayerUV.chunkl +++ b/Src/GBX.NET/Engines/Function/CFuncShaderLayerUV.chunkl @@ -11,7 +11,7 @@ CFuncShaderLayerUV 0x05015000 0x00A (base: 0x009) base - vec2 + vec2 U03 0x00D vec2 diff --git a/Src/GBX.NET/Engines/Game/CGameCtnBlock.chunkl b/Src/GBX.NET/Engines/Game/CGameCtnBlock.chunkl index 786b7c513..624431024 100644 --- a/Src/GBX.NET/Engines/Game/CGameCtnBlock.chunkl +++ b/Src/GBX.NET/Engines/Game/CGameCtnBlock.chunkl @@ -14,10 +14,22 @@ archive short Flags v1+ int Flags - if Flags == -1 - return if (Flags & (1 << 15)) != 0 id Author CGameCtnBlockSkin Skin - if (Flags & (1 << 20)) != 0 - CGameWaypointSpecialProperty WaypointSpecialProperty \ No newline at end of file + v2+ + if (Flags & (1 << 19)) != 0 + CScenePhyCharSpecialProperty PhyCharSpecialProperty + if (Flags & (1 << 20)) != 0 + CGameWaypointSpecialProperty WaypointSpecialProperty + if (Flags & (1 << 18)) != 0 + SSquareCardEventIds[] SquareCardEventIds + if (Flags & (1 << 17)) != 0 + id DecalId + int DecalIntensity = 1 + int DecalVariant = -1 + +archive SSquareCardEventIds + int + int + ident[] \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Game/CGameCtnBlock.cs b/Src/GBX.NET/Engines/Game/CGameCtnBlock.cs index 0ef1be968..47634271b 100644 --- a/Src/GBX.NET/Engines/Game/CGameCtnBlock.cs +++ b/Src/GBX.NET/Engines/Game/CGameCtnBlock.cs @@ -7,7 +7,10 @@ public partial class CGameCtnBlock : IGameCtnBlockTM10, IGameCtnBlockTMSX, IGame { private const int GroundBit = 12; private const int ClipBit = 13; + private const int PillarBit = 14; private const int SkinnableBit = 15; + private const int ReplacementBit = 16; + private const int DecalBit = 17; private const int WaypointBit = 20; private const int GhostBit = 28; private const int FreeBit = 29; @@ -56,12 +59,18 @@ public Ident BlockModel /// public Int3 Coord { get => coord; set => coord = value; } - private int flags; + /// + /// Facing direction of the block. + /// + public Direction Direction { get; set; } + + private int flags; /// /// Flags of the block. If the blocks version is 0, this value can be presented as . /// public int Flags { get => flags; set => flags = value; } + [Obsolete("Flags are now always presented. There's no point to use this anymore.")] public bool HasFlags => flags != -1; /// @@ -69,14 +78,8 @@ public Ident BlockModel /// public byte? Variant { - get => HasFlags ? (byte)(flags & VariantMax) : null; - set - { - if (HasFlags) - { - flags = (flags & ~VariantMax) | (value ?? 0); - } - } + get => (byte)(flags & VariantMax); + set => flags = (flags & ~VariantMax) | (value ?? 0); } /// @@ -84,14 +87,8 @@ public byte? Variant /// public byte? SubVariant { - get => HasFlags ? (byte?)((flags >> SubVariantOffset) & SubVariantMax) : null; - set - { - if (HasFlags) - { - flags = (flags & ~(SubVariantMax << SubVariantOffset)) | ((value ?? 0) << SubVariantOffset); - } - } + get => (byte?)((flags >> SubVariantOffset) & SubVariantMax); + set => flags = (flags & ~(SubVariantMax << SubVariantOffset)) | ((value ?? 0) << SubVariantOffset); } /// @@ -104,7 +101,7 @@ public bool IsGround } /// - /// If the block is considered as clip. Taken from flags. + /// If the block is considered as clip. Also known as IsEditable. Taken from flags. /// public bool IsClip { @@ -112,6 +109,15 @@ public bool IsClip set => SetFlagBit(ClipBit, value); } + /// + /// Taken from flags. + /// + public bool IsPillar + { + get => IsFlagBitSet(PillarBit); + set => SetFlagBit(PillarBit, value); + } + private CGameCtnBlockSkin? skin; /// /// Used skin on the block. @@ -121,11 +127,6 @@ public CGameCtnBlockSkin? Skin get => skin; set { - if (!HasFlags) - { - return; - } - if (value is null && string.IsNullOrEmpty(Author)) // it may be needed to have this complex set on Author prop too { flags &= ~(1 << SkinnableBit); @@ -139,10 +140,20 @@ public CGameCtnBlockSkin? Skin /// /// Taken from flags. /// + public bool IsReplacement + { + get => IsFlagBitSet(ReplacementBit); + set => SetFlagBit(ReplacementBit, value); + } + + /// + /// Taken from flags. + /// + [Obsolete("This bit has been resolved. If absolutely needed, equivalent is !string.IsNullOrEmpty(DecalId).")] public bool Bit17 { - get => IsFlagBitSet(17); - set => SetFlagBit(17, value); + get => IsFlagBitSet(DecalBit); + set => SetFlagBit(DecalBit, value); } private CGameWaypointSpecialProperty? waypointSpecialProperty; @@ -204,6 +215,13 @@ public bool IsFree /// public MacroblockInstance? MacroblockReference { get; set; } + private string? decalId; + public string? DecalId + { + get => decalId; + set => SetFlagBitAndObject(DecalBit, ref decalId, value); + } + byte IGameCtnBlockTM10.Variant { get => Variant.GetValueOrDefault(); set => Variant = value; } byte IGameCtnBlockTMSX.Variant { get => Variant.GetValueOrDefault(); set => Variant = value; } byte IGameCtnBlockTMSX.SubVariant { get => SubVariant.GetValueOrDefault(); set => SubVariant = value; } @@ -221,15 +239,10 @@ public override string ToString() return $"{nameof(CGameCtnBlock)}: {Name} {coord}"; } - private bool IsFlagBitSet(int bit) => HasFlags && (flags & (1 << bit)) != 0; + private bool IsFlagBitSet(int bit) => (flags & (1 << bit)) != 0; private void SetFlagBit(int bit, bool value) { - if (!HasFlags) - { - return; - } - if (value) { flags |= 1 << bit; @@ -242,11 +255,6 @@ private void SetFlagBit(int bit, bool value) private void SetFlagBitAndObject(int bit, ref T? obj, T? value) { - if (!HasFlags) - { - return; - } - if (value is null) { flags &= ~(1 << bit); @@ -260,4 +268,7 @@ private void SetFlagBitAndObject(int bit, ref T? obj, T? value) [ChunkGenerationOptions(StructureKind = StructureKind.SeparateReadAndWrite)] public partial class Chunk03057002; + + [ArchiveGenerationOptions( StructureKind = StructureKind.SeparateReadAndWrite )] + public partial class SSquareCardEventIds; } diff --git a/Src/GBX.NET/Engines/Game/CGameCtnChallenge.chunkl b/Src/GBX.NET/Engines/Game/CGameCtnChallenge.chunkl index adcaaa994..229070578 100644 --- a/Src/GBX.NET/Engines/Game/CGameCtnChallenge.chunkl +++ b/Src/GBX.NET/Engines/Game/CGameCtnChallenge.chunkl @@ -208,7 +208,7 @@ CGameCtnChallenge 0x03043000 // A map. 0x03A (skippable, ignore) -0x03D (skippable, ignore) [MP3, TMT, MP4] // lightmaps +0x03D (skippable) [MP3, TMT, MP4] // lightmaps 0x03E (skippable) [MP3, TMT, MP4, TM2020] // CarMarksBuffer version @@ -318,7 +318,7 @@ CGameCtnChallenge 0x03043000 // A map. int int -0x05B (skippable, ignore) [TM2020] // lightmaps +0x05B (skippable, base: 0x03D) [TM2020] // lightmaps TM2020 0x05C (skippable, ignore) [TM2020] @@ -373,6 +373,37 @@ archive LightmapFrame data Data2 v6+ data Data3 + +archive ProbeGridBoxOld + int + int + int + int + int + int + int + int + int + float + float + float + +archive ProbeGridBox + int + int + int + int + int + int + int + int + int + float + float + float + float + float + float enum MapKind // The map's intended use. EndMarker diff --git a/Src/GBX.NET/Engines/Game/CGameCtnChallenge.cs b/Src/GBX.NET/Engines/Game/CGameCtnChallenge.cs index 08c28b64f..0f4a051ab 100644 --- a/Src/GBX.NET/Engines/Game/CGameCtnChallenge.cs +++ b/Src/GBX.NET/Engines/Game/CGameCtnChallenge.cs @@ -218,7 +218,7 @@ public bool CreatedWithGamepadEditor [AppliedWithChunk] [AppliedWithChunk] [AppliedWithChunk] - public int? NbBlocks => Blocks?.Count(x => x.Name != "Unassigned1"); + public int? NbBlocks => Blocks?.Count; private UInt128? hashedPassword; [AppliedWithChunk] @@ -236,20 +236,26 @@ public UInt128? HashedPassword } } + private bool hasLightmaps; [AppliedWithChunk] - public bool HasLightmaps { get; set; } + public bool HasLightmaps { get => hasLightmaps; set => hasLightmaps = value; } + [AppliedWithChunk(sinceVersion: 9)] [AppliedWithChunk] + [AppliedWithChunk] public int? LightmapVersion { get; set; } [AppliedWithChunk] + [AppliedWithChunk] public CHmsLightMapCache? LightmapCache { get; set; } [AppliedWithChunk] + [AppliedWithChunk] public LightmapFrame[]? LightmapFrames { get; set; } [ZLibData] [AppliedWithChunk] + [AppliedWithChunk] public CompressedData? LightmapCacheData { get; set; } private IList? anchoredObjects; @@ -265,7 +271,7 @@ public UInt128? HashedPassword public CScriptTraitsMetadata? ScriptMetadata { get => scriptMetadata; set => scriptMetadata = value; } [AppliedWithChunk] - public int? NbBakedBlocks => bakedBlocks?.Count(x => x.Name != "Unassigned1"); + public int? NbBakedBlocks => bakedBlocks?.Count; private IList? bakedBlocks; [AppliedWithChunk] @@ -284,26 +290,35 @@ public UInt128? HashedPassword [AppliedWithChunk] public IList? MacroblockInstances { get; set; } + private bool hasCustomCamThumbnail; + [AppliedWithChunk] + [AppliedWithChunk] + public bool HasCustomCamThumbnail { get => hasCustomCamThumbnail; set => hasCustomCamThumbnail = value; } + private Vec3 thumbnailPosition; [AppliedWithChunk] + [AppliedWithChunk] [AppliedWithChunk] [AppliedWithChunk] public Vec3 ThumbnailPosition { get => thumbnailPosition; set => thumbnailPosition = value; } private float thumbnailFov; [AppliedWithChunk] + [AppliedWithChunk] [AppliedWithChunk] [AppliedWithChunk] public float ThumbnailFov { get => thumbnailFov; set => thumbnailFov = value; } private float thumbnailNearClipPlane; [AppliedWithChunk] + [AppliedWithChunk] [AppliedWithChunk] [AppliedWithChunk] public float ThumbnailNearClipPlane { get => thumbnailNearClipPlane; set => thumbnailNearClipPlane = value; } private float thumbnailFarClipPlane; [AppliedWithChunk] + [AppliedWithChunk] [AppliedWithChunk] [AppliedWithChunk] public float ThumbnailFarClipPlane { get => thumbnailFarClipPlane; set => thumbnailFarClipPlane = value; } @@ -339,14 +354,9 @@ public string GetEnvironment() return Collection ?? throw new Exception("Environment not available"); } - public IEnumerable GetBlocks(bool includeUnassigned1 = true) + public IEnumerable GetBlocks() { - if (includeUnassigned1) - { - return blocks ?? []; - } - - return blocks?.Where(x => x.Name != "Unassigned1") ?? []; + return blocks ?? []; } public IEnumerable GetAnchoredObjects() @@ -509,13 +519,13 @@ public void RemovePassword() /// /// Position of the block. /// An enumerable of blocks. - public IEnumerable GetBlocks(Int3 pos) => GetBlocks(includeUnassigned1: false).Where(x => x.Coord == pos); + public IEnumerable GetBlocks(Int3 pos) => GetBlocks().Where(x => x.Coord == pos); /// /// Retrieves ghost blocks on the map. /// /// An enumerable of ghost blocks. - public IEnumerable GetGhostBlocks() => GetBlocks(includeUnassigned1: false).Where(x => x.IsGhost); + public IEnumerable GetGhostBlocks() => GetBlocks().Where(x => x.IsGhost); public CGameCtnBlock PlaceBlock( Ident blockModel, @@ -669,11 +679,30 @@ public void RemoveAll() RemoveAllOffZone(); } - IEnumerable IGameCtnChallengeTM10.GetBlocks() => GetBlocks(includeUnassigned1: true); - IEnumerable IGameCtnChallengeTMSX.GetBlocks() => GetBlocks(includeUnassigned1: true); - IEnumerable IGameCtnChallengeTMF.GetBlocks() => GetBlocks(includeUnassigned1: true); - IEnumerable IGameCtnChallengeMP4.GetBlocks(bool includeUnassigned1) => GetBlocks(includeUnassigned1); - IEnumerable IGameCtnChallengeTM2020.GetBlocks() => GetBlocks(includeUnassigned1: true); + /// + /// Generates an approximate map UID using that is applied to and returned. + /// + /// A random map UID. + public string GenerateMapUid() => MapUid = MapUtils.GenerateMapUid(); + + /// + /// Generates an approximate map UID using that is applied to and returned. + /// + /// A consistent map UID, based on the seed. + public string GenerateMapUid(int seed) => MapUid = MapUtils.GenerateMapUid(seed); + + /// + /// Generates an approximate map UID using that is applied to and returned. + /// + /// A random map UID. + /// Thrown when is null. + public string GenerateMapUid(Random random) => MapUid = MapUtils.GenerateMapUid(random); + + IEnumerable IGameCtnChallengeTM10.GetBlocks() => GetBlocks(); + IEnumerable IGameCtnChallengeTMSX.GetBlocks() => GetBlocks(); + IEnumerable IGameCtnChallengeTMF.GetBlocks() => GetBlocks(); + IEnumerable IGameCtnChallengeMP4.GetBlocks() => GetBlocks(); + IEnumerable IGameCtnChallengeTM2020.GetBlocks() => GetBlocks(); IEnumerable IGameCtnChallengeMP4.GetBakedBlocks() => GetBakedBlocks(); IEnumerable IGameCtnChallengeTM2020.GetBakedBlocks() => GetBakedBlocks(); IGameCtnBlockTM10? IGameCtnChallengeTM10.GetBlock(Int3 pos) => GetBlock(pos); @@ -735,10 +764,7 @@ public partial class Chunk0304301F : IVersionable { public int Version { get; set; } = 6; - public bool U01; - public ulong? U02; - - public bool IsUnlimiter2 { get; set; } + public bool NeedUnlock; public override void Read(CGameCtnChallenge n, GbxReader r) { @@ -746,45 +772,22 @@ public override void Read(CGameCtnChallenge n, GbxReader r) n.mapName = r.ReadString(); n.decoration = r.ReadIdent(); n.size = r.ReadInt3(); - U01 = r.ReadBoolean(); + NeedUnlock = r.ReadBoolean(); Version = r.ReadInt32(); var nbBlocks = r.ReadInt32(); n.blocks = new List(nbBlocks); - var isUnlimiter = default(bool?); - for (var i = 0; i < nbBlocks; i++) { var block = r.ReadReadable(Version); - n.blocks.Add(block); - - if (block.Flags != -1) - { - continue; - } - - isUnlimiter ??= block.Name.StartsWith("TMUnlimiter 2"); - if (isUnlimiter.Value) - { - IsUnlimiter2 = isUnlimiter.Value; - } - else + if (Version >= 6) { - i--; + block.Coord -= new Int3(1, 0, 1); } - } - if (IsUnlimiter2) - { - U02 = r.ReadUInt64(); - return; - } - - while ((r.PeekUInt32() & 0xC0000000) > 0) - { - n.blocks.Add(r.ReadReadable(Version)); + n.blocks.Add(block); } } @@ -794,9 +797,15 @@ public override void Write(CGameCtnChallenge n, GbxWriter w) w.Write(n.mapName); w.Write(n.decoration); w.Write(n.size); - w.Write(U01); + w.Write(NeedUnlock); w.Write(Version); + if (Version < 6) + { + w.WriteListWritable(n.blocks, version: Version); + return; + } + w.Write(n.NbBlocks.GetValueOrDefault()); if (n.blocks is null) @@ -806,27 +815,61 @@ public override void Write(CGameCtnChallenge n, GbxWriter w) foreach (var block in n.blocks) { - w.WriteWritable(block, Version); - } - - if (IsUnlimiter2) - { - w.Write(U02.GetValueOrDefault()); + try + { + block.Coord += new Int3(1, 0, 1); + w.WriteWritable(block, Version); + } + finally + { + block.Coord -= new Int3(1, 0, 1); + } } } } public partial class Chunk0304303D { - public override void Read(CGameCtnChallenge n, GbxReader r) + public int U01; + public int? U02; + public int? U03; + public int? U04; + public int? U05; + public int? U06; + public int? U07; + public byte[]? U08; + public int U09; + public int U10; + public float? U11; + public int? U12; + + public override void ReadWrite(CGameCtnChallenge n, GbxReaderWriter rw) { - n.HasLightmaps = r.ReadBoolean(); // true is SHmsLightMapCacheSmall is not empty + rw.Boolean(ref n.hasLightmaps); // true if SHmsLightMapCacheSmall is not empty if (!n.HasLightmaps) { return; } + ReadWriteLightMapCacheSmall(n, rw); + } + + internal void ReadWriteLightMapCacheSmall(CGameCtnChallenge n, GbxReaderWriter rw) + { + if (rw.Reader is not null) + { + ReadLightMapCacheSmall(n, rw.Reader); + } + + if (rw.Writer is not null) + { + WriteLightMapCacheSmall(n, rw.Writer); + } + } + + private void ReadLightMapCacheSmall(CGameCtnChallenge n, GbxReader r) + { n.LightmapVersion = r.ReadInt32(); if (n.LightmapVersion < 2) @@ -846,23 +889,26 @@ public override void Read(CGameCtnChallenge n, GbxReader r) n.LightmapCacheData = new CompressedData(r.ReadInt32(), r.ReadData()); + if (Gbx.ZLib is null) + { + return; + } + using var ms = n.LightmapCacheData.OpenDecompressedMemoryStream(); - using var rBuffer = new GbxReader(ms); + var rBuffer = new GbxReader(ms); rBuffer.LoadFrom(r); n.LightmapCache = rBuffer.ReadNode(); + + var rw = new GbxReaderWriter(rBuffer); + ReadWriteTheRestOfCompressedData(n, rw); } - public override void Write(CGameCtnChallenge n, GbxWriter w) + private void WriteLightMapCacheSmall(CGameCtnChallenge n, GbxWriter w) { - w.Write(n.HasLightmaps); + var lightmapVersion = n.LightmapVersion.GetValueOrDefault(8); - if (!n.HasLightmaps) - { - return; - } - - w.Write(n.LightmapVersion.GetValueOrDefault()); + w.Write(lightmapVersion); if (n.LightmapVersion < 2) { @@ -870,13 +916,26 @@ public override void Write(CGameCtnChallenge n, GbxWriter w) return; } - w.Write(n.LightmapFrames?.Length ?? 0); + if (n.LightmapVersion >= 5) + { + w.Write(n.LightmapFrames?.Length ?? 0); + } - w.WriteArrayWritable(n.LightmapFrames, version: n.LightmapVersion.GetValueOrDefault(8)); + foreach (var frame in n.LightmapFrames ?? []) + { + w.WriteWritable(frame, version: lightmapVersion); + } - if (n.LightmapCacheData is null) + if (Gbx.ZLib is null) { - throw new Exception("Lightmap cache data is not available."); + if (n.LightmapCacheData is null) + { + throw new ZLibNotDefinedException(); + } + + w.Write(n.LightmapCacheData.UncompressedSize); + w.WriteData(n.LightmapCacheData.Data); + return; } using var ms = new MemoryStream(); @@ -885,23 +944,205 @@ public override void Write(CGameCtnChallenge n, GbxWriter w) wBuffer.WriteNode(n.LightmapCache); - if (Gbx.ZLib is null) - { - throw new Exception("ZLib is not imported (IZLib)."); - } + var rw = new GbxReaderWriter(wBuffer); + ReadWriteTheRestOfCompressedData(n, rw); ms.Position = 0; using var compressedMs = new MemoryStream(); - Gbx.ZLib.Compress(ms, compressedMs); - w.Write(compressedMs.Length); - compressedMs.CopyTo(w.BaseStream); + w.Write((int)ms.Length); + w.Write((int)compressedMs.Length); + compressedMs.WriteTo(w.BaseStream); + } + + private void ReadWriteTheRestOfCompressedData(CGameCtnChallenge n, GbxReaderWriter rw) + { + rw.Int32(ref U01); + + if (n.LightmapVersion >= 3) + { + rw.Int32(ref U02); + rw.Int32(ref U03); + rw.Int32(ref U04); + rw.Int32(ref U05); + rw.Int32(ref U06); + + if (n.LightmapVersion >= 4) + { + rw.Int32(ref U07); + + if (n.LightmapVersion < 5) + { + rw.Data(ref U08); + } + else if (n.LightmapFrames is not null) + { + foreach (var frame in n.LightmapFrames) + { + frame.U01 = rw.Data(frame.U01); + frame.U02 = rw.Single(frame.U02); + + if (n.LightmapVersion >= 6) + { + // NHmsLightMapCache::ArchiveToZip + frame.Version = rw.Int32(frame.Version); + + if (frame.Version < 2) + { + frame.U03 = rw.Single(frame.U03); + frame.U04 = rw.Int32(frame.U04); + + if (frame.Version != 0) + { + frame.U05 = rw.Int32(frame.U05); + } + + frame.U06 = rw.Int32(frame.U06); + frame.U07 = rw.Int32(frame.U07); + frame.U08 = rw.Int32(frame.U08); + frame.U09 = rw.Iso4(frame.U09); + frame.U10 = rw.Array(frame.U10); + } + else + { + frame.U11 = rw.Single(frame.U11); + frame.U12 = rw.Int32(frame.U12); + + if (frame.Version >= 5) + { + frame.U39 = rw.Single(frame.U39); + frame.U40 = rw.Int32(frame.U40); + + if (frame.Version >= 6) + { + frame.U41 = rw.Single(frame.U41); + frame.U42 = rw.Int32(frame.U42); + } + } + + frame.U13 = rw.Int32(frame.U13); + frame.U14 = rw.Int32(frame.U14); + frame.U15 = rw.Int32(frame.U15); + + if (frame.Version < 4) + { + frame.U16 = rw.ArrayReadableWritable(frame.U16); + } + else + { + frame.U17 = rw.ArrayReadableWritable(frame.U17); + } + + frame.U18 = rw.Array(frame.U18); + frame.U19 = rw.Array(frame.U19); + + if (frame.Version >= 3) + { + frame.U20 = rw.Int32(frame.U20); + frame.U21 = rw.Int32(frame.U21); + frame.U22 = rw.Int32(frame.U22); + frame.U23 = rw.Int32(frame.U23); + frame.U24 = rw.Int32(frame.U24); + frame.U25 = rw.Int32(frame.U25); + + if (frame.Version >= 4) + { + frame.U33 = rw.Int32(frame.U33); + frame.U34 = rw.Int32(frame.U34); + frame.U35 = rw.Int32(frame.U35); + } + + frame.U26 = rw.Single(frame.U26); + frame.U27 = rw.Single(frame.U27); + frame.U28 = rw.Single(frame.U28); + frame.U29 = rw.Single(frame.U29); + frame.U30 = rw.Single(frame.U30); + frame.U31 = rw.Single(frame.U31); + frame.U32 = rw.Array(frame.U32); + } + } + // + + if (n.LightmapVersion >= 8) + { + frame.U36 = rw.Int32(frame.U36); + frame.U37 = rw.Int32(frame.U37); + + // Unchecked + if (n.LightmapVersion >= 10) + { + frame.U38 = rw.Int32(frame.U38); + } + } + } + } + } + } + } + + rw.Int32(ref U09); + rw.Int32(ref U10); + + if (n.LightmapVersion < 5) + { + rw.Single(ref U11); + } + + if (n.LightmapVersion >= 7) + { + rw.Int32(ref U12); + } } } [ArchiveGenerationOptions(StructureKind = StructureKind.SeparateReadAndWrite)] - public partial class LightmapFrame; + public partial class LightmapFrame : IVersionable + { + public byte[]? U01 { get; set; } + public float U02 { get; set; } + public int Version { get; set; } + public float? U03 { get; set; } + public int? U04 { get; set; } + public int? U05 { get; set; } + public int? U06 { get; set; } + public int? U07 { get; set; } + public int? U08 { get; set; } + public Iso4? U09 { get; set; } + public short[]? U10 { get; set; } + public float? U11 { get; set; } + public int? U12 { get; set; } + public int? U13 { get; set; } + public int? U14 { get; set; } + public int? U15 { get; set; } + public ProbeGridBoxOld[]? U16 { get; set; } + public ProbeGridBox[]? U17 { get; set; } + public Int2[]? U18 { get; set; } + public short[]? U19 { get; set; } + public int? U20 { get; set; } + public int? U21 { get; set; } + public int? U22 { get; set; } + public int? U23 { get; set; } + public int? U24 { get; set; } + public int? U25 { get; set; } + public float? U26 { get; set; } + public float? U27 { get; set; } + public float? U28 { get; set; } + public float? U29 { get; set; } + public float? U30 { get; set; } + public float? U31 { get; set; } + public int[]? U32 { get; set; } + public int? U33 { get; set; } + public int? U34 { get; set; } + public int? U35 { get; set; } + public int? U36 { get; set; } + public int? U37 { get; set; } + public int? U38 { get; set; } + public float? U39 { get; set; } + public int? U40 { get; set; } + public float? U41 { get; set; } + public int? U42 { get; set; } + } public partial class Chunk03043040 : IVersionable { @@ -938,15 +1179,14 @@ public override void Read(CGameCtnChallenge n, GbxReader r) { var blockIndexes = r.ReadArray(); // block indexes, -1 means itemIndexes will have the value instead var usedBlocks = new CGameCtnBlock?[blockIndexes.Length]; - var blocksWithoutUnassigned = n.blocks!.Where(x => x.Flags != -1).ToArray(); - + for (var i = 0; i < blockIndexes.Length; i++) { var index = blockIndexes[i]; if (index > -1) { - usedBlocks[i] = blocksWithoutUnassigned[index]; + usedBlocks[i] = n.blocks![index]; } } @@ -1249,17 +1489,8 @@ public override void Read(CGameCtnChallenge n, GbxReader r) for (var i = 0; i < nbBakedBlocks; i++) { var block = r.ReadReadable(BlocksVersion); + block.Coord -= new Int3(1, 0, 1); n.bakedBlocks.Add(block); - - if (block.Flags == -1) - { - i--; - } - } - - while ((r.PeekUInt32() & 0xC0000000) > 0) - { - n.bakedBlocks.Add(r.ReadReadable(BlocksVersion)); } U01 = r.ReadInt32(); @@ -1272,13 +1503,28 @@ public override void Write(CGameCtnChallenge n, GbxWriter w) w.Write(Version); w.Write(BlocksVersion); - w.Write(n.NbBakedBlocks.GetValueOrDefault()); - - if (n.bakedBlocks is not null) + if (BlocksVersion < 6) { - foreach (var block in n.bakedBlocks) + w.WriteListWritable(n.bakedBlocks, version: BlocksVersion); + } + else + { + w.Write(n.NbBakedBlocks.GetValueOrDefault()); + + if (n.bakedBlocks is not null) { - w.WriteWritable(block, BlocksVersion); + foreach (var block in n.bakedBlocks) + { + try + { + block.Coord += new Int3(1, 0, 1); + w.WriteWritable(block, BlocksVersion); + } + finally + { + block.Coord -= new Int3(1, 0, 1); + } + } } } @@ -1434,6 +1680,30 @@ public override void ReadWrite(CGameCtnChallenge n, GbxReaderWriter rw) } } + public partial class Chunk0304305B : IVersionable + { + public int Version { get; set; } + + public bool U01; + public bool U02; + + public override void ReadWrite(CGameCtnChallenge n, GbxReaderWriter rw) + { + rw.VersionInt32(this); + + n.HasLightmaps = rw.Boolean(n.HasLightmaps); + rw.Boolean(ref U01); + rw.Boolean(ref U02); + + if (!n.HasLightmaps) + { + return; + } + + ReadWriteLightMapCacheSmall(n, rw); + } + } + public partial class Chunk0304305F : IVersionable { /// diff --git a/Src/GBX.NET/Engines/Game/CGameCtnCollection.chunkl b/Src/GBX.NET/Engines/Game/CGameCtnCollection.chunkl index 9f7ea948a..c5e5e3fb2 100644 --- a/Src/GBX.NET/Engines/Game/CGameCtnCollection.chunkl +++ b/Src/GBX.NET/Engines/Game/CGameCtnCollection.chunkl @@ -179,10 +179,10 @@ CGameCtnCollection 0x03033000 0x034 version - CFuncShaderLayerUV FidFuncShaderCloudsX2 - CPlugBitmap FidPlugBitmapCloudsX2 + CFuncShaderLayerUV FidFuncShaderCloudsX2 (external) + CPlugBitmap FidPlugBitmapCloudsX2 (external) v1+ - CPlugBitmap VehicleEnvLayerFidBitmap + CPlugBitmap VehicleEnvLayerFidBitmap (external) int VehicleEnvLayer 0x036 // OffZone_FogMatter @@ -192,7 +192,36 @@ CGameCtnCollection 0x03033000 0x037 // TerrainHeightOffset float TerrainHeightOffset -0x038 (ignore) +0x038 + version + v3- + float + v0= + float + float + v1+ + Water Water1 (version: Version) + Water Water2 (version: Version) + v4+ + Water Water1 (version: Version) + Water Water2 (version: Version) + Water Water3 (version: Version) + Water Water4 (version: Version) + v5+ + CPlugBitmap WaterGBitmapNormal (external) + float WaterGBumpSpeedUV + float WaterGBumpScaleUV + float WaterGBumpScale + float WaterGRefracPertub + v7+ + int // not seen in code + float CameraMinHeight + v3- + bool // CSystemFidsFolder something? + bool IsWaterMultiHeight + v2- + float + float WaterFogClampAboveDist 0x039 version @@ -280,4 +309,15 @@ enum EVehicleEnvLayer archive ZoneString id Base - id Replacement \ No newline at end of file + id Replacement + +archive Water + id + float + float + v3+ + float? + v2+ + int? // NodeRef? + v7+ + int? // not seen in code \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Game/CGameCtnGhost.PlayerInputData.cs b/Src/GBX.NET/Engines/Game/CGameCtnGhost.PlayerInputData.cs index be97b1a50..220f604ad 100644 --- a/Src/GBX.NET/Engines/Game/CGameCtnGhost.PlayerInputData.cs +++ b/Src/GBX.NET/Engines/Game/CGameCtnGhost.PlayerInputData.cs @@ -11,544 +11,544 @@ namespace GBX.NET.Engines.Game; public partial class CGameCtnGhost { - /// - /// Set of inputs. - /// - public partial class PlayerInputData - { - public enum EVersion - { - _2017_07_07 = 7, - _2017_09_12 = 8, - _2020_04_08 = 11, - _2020_07_20 = 12 - } - - private enum EStart - { - NotStarted, - Character, - Vehicle, - VehicleMix - } - - private ImmutableList? inputChanges; - private ImmutableList? inputs; - - public IList InputChanges - { - get - { - if (inputChanges is null) - { - var inputEnumerable = version is <= EVersion._2017_09_12 - ? ProcessShootmaniaInputChanges() - : ProcessTrackmaniaInputChanges(); - - inputChanges = inputEnumerable.ToImmutableList(); - } - - return inputChanges; - } - } + /// + /// Set of inputs. + /// + public partial class PlayerInputData + { + public enum EVersion + { + _2017_07_07 = 7, + _2017_09_12 = 8, + _2020_04_08 = 11, + _2020_07_20 = 12 + } + + private enum EStart + { + NotStarted, + Character, + Vehicle, + VehicleMix + } + + private ImmutableList? inputChanges; + private ImmutableList? inputs; + + public IList InputChanges + { + get + { + if (inputChanges is null) + { + var inputEnumerable = version is <= EVersion._2017_09_12 + ? ProcessShootmaniaInputChanges() + : ProcessTrackmaniaInputChanges(); + + inputChanges = inputEnumerable.ToImmutableList(); + } + + return inputChanges; + } + } public ImmutableList Inputs => inputs ??= version is <= EVersion._2017_09_12 ? ProcessShootmaniaInputs().ToImmutableList() : ProcessTrackmaniaInputs(); - private static bool StateIsDifferent(int bit, out bool result, int states, int? prevStates) - { - var mask = 1 << bit; - return StateIsDifferentWithMask(mask, out result, states, prevStates); - } - - private static bool StateIsDifferentWithMask(int mask, out bool result, int states, int? prevStates) - { - var masked = states & mask; - result = masked != 0; - - if (prevStates is null) - { - return result; - } - - return masked != (prevStates & mask); - } - - private static bool StateIsDifferent(int bit, out bool result, ulong states, ulong? prevStates) - { - var mask = (ulong)1 << bit; - return StateIsDifferentWithMask(mask, out result, states, prevStates); - } - - private static bool StateIsDifferentWithMask(ulong mask, out bool result, ulong states, ulong? prevStates) - { - var masked = states & mask; - result = masked != 0; - - if (prevStates is null) - { - return result; - } - - return masked != (prevStates & mask); - } - - internal IEnumerable ProcessShootmaniaInputs() - { - if (data is null) - { - yield break; + private static bool StateIsDifferent(int bit, out bool result, int states, int? prevStates) + { + var mask = 1 << bit; + return StateIsDifferentWithMask(mask, out result, states, prevStates); + } + + private static bool StateIsDifferentWithMask(int mask, out bool result, int states, int? prevStates) + { + var masked = states & mask; + result = masked != 0; + + if (prevStates is null) + { + return result; } - var r = new BitReader(data); - - var prevStrafe = NET.Inputs.EStrafe.None; - var prevWalk = NET.Inputs.EWalk.None; - var prevVertical = default(byte); - var prevStatesFull = default(int?); - var prevStates2Bit = default(byte?); - var prevAction = default(bool); - var prevGunTrigger = default(bool); - - for (var i = 0; i < ticks; i++) - { - var time = new TimeInt32(i * 10); - - var sameMouse = r.ReadBit(); - - if (!sameMouse) - { - var mouseAccuX = r.ReadUInt16(); - var mouseAccuY = r.ReadUInt16(); - - yield return new MouseAccu(time, mouseAccuX, mouseAccuY); - } - - var sameValuesAfter = r.ReadBit(); - var sameValue = sameValuesAfter; - - if (!sameValuesAfter) - { - sameValue = r.ReadBit(); - } - - if (!sameValue) - { - var strafe = (Inputs.EStrafe)r.Read2Bit(); - if (strafe == NET.Inputs.EStrafe.Corrupted) throw new Exception("Corrupted inputs. (strafe == 2)"); - - if (strafe != prevStrafe) - { - yield return new Strafe(time, strafe); - prevStrafe = strafe; - } - - var walk = (Inputs.EWalk)r.Read2Bit(); - if (walk == NET.Inputs.EWalk.Corrupted) throw new Exception("Corrupted inputs. (walk == 2)"); - - if (walk != prevWalk) - { - yield return new Walk(time, walk); - prevWalk = walk; - } - - if (version == EVersion._2017_09_12) - { - var vertical = r.Read2Bit(); - - if (vertical != prevVertical) - { - yield return new Vertical(time, vertical); - prevVertical = vertical; - } - } - } - - if (sameValuesAfter) - { - continue; - } - - sameValue = r.ReadBit(); - - if (sameValue) - { - continue; - } - - var onlyGunTriggerAndAction = r.ReadBit(); - - if (onlyGunTriggerAndAction) - { - var states2Bit = r.Read2Bit(); - - if (states2Bit == prevStates2Bit) - { - continue; - } - - if (StateIsDifferent(bit: 0, out bool action2Bit, states2Bit, prevStates2Bit) && action2Bit != prevAction) - { - yield return new Inputs.Action(time, action2Bit); - prevAction = action2Bit; - } - - if (StateIsDifferent(bit: 1, out bool gunTrigger2Bit, states2Bit, prevStates2Bit) && gunTrigger2Bit != prevGunTrigger) - { - yield return new GunTrigger(time, gunTrigger2Bit); - prevGunTrigger = gunTrigger2Bit; - } - - prevStates2Bit = states2Bit; - - continue; - } - - var states = r.ReadInt32(); - - if (states == prevStatesFull) - { - continue; - } - - if (StateIsDifferent(bit: 1, out bool gunTrigger, states, prevStatesFull) && gunTrigger != prevGunTrigger) - { - yield return new GunTrigger(time, gunTrigger); - prevGunTrigger = gunTrigger; - } - - if (StateIsDifferent(bit: 2, out bool freeLook, states, prevStatesFull)) - { - yield return new FreeLook(time, freeLook); - } - - if (StateIsDifferent(bit: 3, out bool fly, states, prevStatesFull)) - { - yield return new Fly(time, fly); - } - - if (StateIsDifferent(bit: 5, out bool camera2, states, prevStatesFull)) - { - yield return new Camera2(time, camera2); - } - - if (StateIsDifferent(bit: 7, out bool jump, states, prevStatesFull)) - { - yield return new Jump(time, jump); - } - - if (StateIsDifferent(bit: 8, out bool action, states, prevStatesFull) && action != prevAction) - { - yield return new Inputs.Action(time, action); - prevAction = action; - } - - for (var j = 0; j < 4; j++) // 4 action slots - { - if (StateIsDifferent(bit: 10 + j, out bool actionSlot, states, prevStatesFull)) - { - yield return new ActionSlot(time, (byte)(1 + j), actionSlot); - } - } - - if (StateIsDifferentWithMask(16896, out bool use1, states, prevStatesFull)) - { - yield return new Use(time, 1, use1); - } - - if (StateIsDifferentWithMask(32832, out bool use2, states, prevStatesFull)) - { - yield return new Use(time, 2, use2); - } - - if (StateIsDifferent(bit: 16, out bool menu, states, prevStatesFull)) - { - yield return new Menu(time, menu); - } - - if (StateIsDifferent(bit: 20, out bool horn, states, prevStatesFull)) - { - yield return new Horn(time, horn); - } - - if (StateIsDifferent(bit: 21, out bool respawn, states, prevStatesFull)) - { - yield return new Respawn(time, respawn); - } - - if (StateIsDifferent(bit: 26, out bool giveUp, states, prevStatesFull)) - { - yield return new GiveUp(time, giveUp); - } - - prevStatesFull = states; - } - } - - internal ImmutableList ProcessTrackmaniaInputs() + return masked != (prevStates & mask); + } + + private static bool StateIsDifferent(int bit, out bool result, ulong states, ulong? prevStates) + { + var mask = (ulong)1 << bit; + return StateIsDifferentWithMask(mask, out result, states, prevStates); + } + + private static bool StateIsDifferentWithMask(ulong mask, out bool result, ulong states, ulong? prevStates) + { + var masked = states & mask; + result = masked != 0; + + if (prevStates is null) + { + return result; + } + + return masked != (prevStates & mask); + } + + internal IEnumerable ProcessShootmaniaInputs() { if (data is null) { - return ImmutableList.Empty; + yield break; } - var inputs = ImmutableList.CreateBuilder(); + var r = new BitReader(data); - var r = new BitReader(data); - - var started = EStart.NotStarted; - - var prevStatesFull = default(ulong?); - var prevStates2Bit = default(byte?); - var prevHorn = default(bool); - var prevGunTrigger = default(bool); - var prevAction = default(bool); - var prevSteer = default(sbyte); - var prevAccel = default(bool); - var prevBrake = default(bool); - var prevStrafe = NET.Inputs.EStrafe.None; - var prevWalk = NET.Inputs.EWalk.None; - var prevVertical = default(byte); - var prevHorizontal = default(byte); - - for (var i = 0; i < ticks; i++) - { - var time = new TimeInt32(i * 10) + StartOffset.GetValueOrDefault(); - - try - { - var sameState = r.ReadBit(); - - if (!sameState) - { - var only2Bit = r.ReadBit(); - - if (only2Bit) - { - var states = r.Read2Bit(); - - if (states != prevStates2Bit) - { - if (started is EStart.Vehicle) - { - if (StateIsDifferent(bit: 1, out bool horn2Bit, states, prevStates2Bit) && horn2Bit != prevHorn) - { - inputs.Add(new Horn(time, horn2Bit)); - prevHorn = horn2Bit; - } - } - else if (started is EStart.Character) - { - if (StateIsDifferent(bit: 0, out bool gunTrigger, states, prevStates2Bit) && gunTrigger != prevGunTrigger) - { - inputs.Add(new GunTrigger(time, gunTrigger)); - prevGunTrigger = gunTrigger; - } - - if (StateIsDifferent(bit: 1, out bool action, states, prevStates2Bit) && action != prevAction) - { - inputs.Add(new Inputs.Action(time, action)); - prevAction = action; - } - } - - prevStates2Bit = states; - } - } - else - { - var states = r.ReadNumber(bits: version is EVersion._2020_04_08 ? 33 : 34); - - if (started is EStart.NotStarted) - { - started = (EStart)(states & 3); - - if (started is EStart.VehicleMix) - { - started = EStart.Vehicle; - } - } - - if (started is EStart.Character) - { - if (StateIsDifferent(bit: 5, out bool gunTrigger, states, prevStatesFull) && gunTrigger != prevGunTrigger) - { - inputs.Add(new GunTrigger(time, gunTrigger)); - prevGunTrigger = gunTrigger; - } - } - - if (StateIsDifferent(bit: 6, out bool hornOrAction, states, prevStatesFull)) - { - if (started is EStart.Vehicle && hornOrAction != prevHorn) - { - inputs.Add(new Horn(time, hornOrAction)); - prevHorn = hornOrAction; - } - else if (started is EStart.Character && hornOrAction != prevAction) - { - inputs.Add(new Inputs.Action(time, hornOrAction)); - prevAction = hornOrAction; - } - } - - if (started is EStart.Character && StateIsDifferent(bit: 10, out bool camera2, states, prevStatesFull)) - { - inputs.Add(new Camera2(time, camera2)); - } - - if (StateIsDifferent(bit: 12, out bool jump, states, prevStatesFull)) - { - inputs.Add(new Jump(time, jump)); - } - - if (StateIsDifferent(bit: 13, out bool freeLook, states, prevStatesFull)) - { - inputs.Add(new FreeLook(time, freeLook)); - } - - for (var j = 0; j < 9; j++) // 9 action slots - { - // Action slots 2 and 4 have an additional bit 7 usage, which is ignored here - - if (StateIsDifferent(bit: 14 + j, out bool actionSlot, states, prevStatesFull)) - { - inputs.Add(new ActionSlot(time, (byte)(1 + j), actionSlot)); - } - } - - // + 1 action slot 0 - - if (StateIsDifferent(bit: 23, out bool actionSlot0, states, prevStatesFull)) - { - inputs.Add(new ActionSlot(time, 0, actionSlot0)); - } - - if (((states >> 31) & 1) != 0) - { - inputs.Add(new RespawnTM2020(time)); - } - - if (((states >> 33) & 1) != 0) - { - inputs.Add(new SecondaryRespawn(time)); - } - - prevStatesFull = states; - } - } - - var sameMouse = r.ReadBit(); - - if (!sameMouse) - { - var mouseAccuX = r.ReadUInt16(); - var mouseAccuY = r.ReadUInt16(); - - inputs.Add(new MouseAccu(time, mouseAccuX, mouseAccuY)); - } - - // In code, this check is presented as '(X - 2 & 0xfffffffd) == 0' - - switch (started) - { - case EStart.Vehicle: - var sameVehicleValue = r.ReadBit(); - - if (sameVehicleValue) - { - break; - } - - var steer = r.ReadSByte(); - - if (steer != prevSteer) - { - inputs.Add(new SteerTM2020(time, steer)); - prevSteer = steer; - } - - var accel = r.ReadBit(); - - if (accel != prevAccel) - { - inputs.Add(new Accelerate(time, accel)); - prevAccel = accel; - } - - var brake = r.ReadBit(); - - if (brake != prevBrake) - { - inputs.Add(new Brake(time, brake)); - prevBrake = brake; - } - - break; - - case EStart.Character: - var sameCharacterValue = r.ReadBit(); - - if (sameCharacterValue) - { - break; - } - - var strafe = (Inputs.EStrafe)r.Read2Bit(); - if (strafe == NET.Inputs.EStrafe.Corrupted) throw new Exception("Corrupted inputs. (strafe == 2)"); - - if (strafe != prevStrafe) - { - inputs.Add(new Strafe(time, strafe)); - prevStrafe = strafe; - } - - var walk = (Inputs.EWalk)r.Read2Bit(); - if (walk == NET.Inputs.EWalk.Corrupted) throw new Exception("Corrupted inputs. (walk == 2)"); + var prevStrafe = NET.Inputs.EStrafe.None; + var prevWalk = NET.Inputs.EWalk.None; + var prevVertical = default(byte); + var prevStatesFull = default(int?); + var prevStates2Bit = default(byte?); + var prevAction = default(bool); + var prevGunTrigger = default(bool); - if (walk != prevWalk) - { - inputs.Add(new Walk(time, walk)); - prevWalk = walk; - } - - var vertical = r.Read2Bit(); + for (var i = 0; i < ticks; i++) + { + var time = new TimeInt32(i * 10); + + var sameMouse = r.ReadBit(); + + if (!sameMouse) + { + var mouseAccuX = r.ReadUInt16(); + var mouseAccuY = r.ReadUInt16(); + + yield return new MouseAccu(time, mouseAccuX, mouseAccuY); + } + + var sameValuesAfter = r.ReadBit(); + var sameValue = sameValuesAfter; + + if (!sameValuesAfter) + { + sameValue = r.ReadBit(); + } + + if (!sameValue) + { + var strafe = (Inputs.EStrafe)r.Read2Bit(); + if (strafe == NET.Inputs.EStrafe.Corrupted) throw new Exception("Corrupted inputs. (strafe == 2)"); + + if (strafe != prevStrafe) + { + yield return new Strafe(time, strafe); + prevStrafe = strafe; + } + + var walk = (Inputs.EWalk)r.Read2Bit(); + if (walk == NET.Inputs.EWalk.Corrupted) throw new Exception("Corrupted inputs. (walk == 2)"); + + if (walk != prevWalk) + { + yield return new Walk(time, walk); + prevWalk = walk; + } + + if (version == EVersion._2017_09_12) + { + var vertical = r.Read2Bit(); + + if (vertical != prevVertical) + { + yield return new Vertical(time, vertical); + prevVertical = vertical; + } + } + } + + if (sameValuesAfter) + { + continue; + } + + sameValue = r.ReadBit(); + + if (sameValue) + { + continue; + } + + var onlyGunTriggerAndAction = r.ReadBit(); + + if (onlyGunTriggerAndAction) + { + var states2Bit = r.Read2Bit(); + + if (states2Bit == prevStates2Bit) + { + continue; + } + + if (StateIsDifferent(bit: 0, out bool action2Bit, states2Bit, prevStates2Bit) && action2Bit != prevAction) + { + yield return new Inputs.Action(time, action2Bit); + prevAction = action2Bit; + } + + if (StateIsDifferent(bit: 1, out bool gunTrigger2Bit, states2Bit, prevStates2Bit) && gunTrigger2Bit != prevGunTrigger) + { + yield return new GunTrigger(time, gunTrigger2Bit); + prevGunTrigger = gunTrigger2Bit; + } + + prevStates2Bit = states2Bit; + + continue; + } + + var states = r.ReadInt32(); + + if (states == prevStatesFull) + { + continue; + } + + if (StateIsDifferent(bit: 1, out bool gunTrigger, states, prevStatesFull) && gunTrigger != prevGunTrigger) + { + yield return new GunTrigger(time, gunTrigger); + prevGunTrigger = gunTrigger; + } + + if (StateIsDifferent(bit: 2, out bool freeLook, states, prevStatesFull)) + { + yield return new FreeLook(time, freeLook); + } + + if (StateIsDifferent(bit: 3, out bool fly, states, prevStatesFull)) + { + yield return new Fly(time, fly); + } + + if (StateIsDifferent(bit: 5, out bool camera2, states, prevStatesFull)) + { + yield return new Camera2(time, camera2); + } + + if (StateIsDifferent(bit: 7, out bool jump, states, prevStatesFull)) + { + yield return new Jump(time, jump); + } + + if (StateIsDifferent(bit: 8, out bool action, states, prevStatesFull) && action != prevAction) + { + yield return new Inputs.Action(time, action); + prevAction = action; + } + + for (var j = 0; j < 4; j++) // 4 action slots + { + if (StateIsDifferent(bit: 10 + j, out bool actionSlot, states, prevStatesFull)) + { + yield return new ActionSlot(time, (byte)(1 + j), actionSlot); + } + } + + if (StateIsDifferentWithMask(16896, out bool use1, states, prevStatesFull)) + { + yield return new Use(time, 1, use1); + } + + if (StateIsDifferentWithMask(32832, out bool use2, states, prevStatesFull)) + { + yield return new Use(time, 2, use2); + } + + if (StateIsDifferent(bit: 16, out bool menu, states, prevStatesFull)) + { + yield return new Menu(time, menu); + } + + if (StateIsDifferent(bit: 20, out bool horn, states, prevStatesFull)) + { + yield return new Horn(time, horn); + } + + if (StateIsDifferent(bit: 21, out bool respawn, states, prevStatesFull)) + { + yield return new Respawn(time, respawn); + } + + if (StateIsDifferent(bit: 26, out bool giveUp, states, prevStatesFull)) + { + yield return new GiveUp(time, giveUp); + } + + prevStatesFull = states; + } + } - if (vertical != prevVertical) - { - inputs.Add(new Vertical(time, vertical)); - prevVertical = vertical; - } - - var horizontal = r.Read2Bit(); + internal ImmutableList ProcessTrackmaniaInputs() + { + if (data is null) + { + return ImmutableList.Empty; + } - if (horizontal != prevHorizontal) - { - inputs.Add(new Horizontal(time, horizontal)); - prevHorizontal = horizontal; - } + var inputs = ImmutableList.CreateBuilder(); - break; - } - } - catch (IndexOutOfRangeException) - { - // TM2020 moment - } - } + var r = new BitReader(data); - var theRest = r.ReadToEnd(); + var started = EStart.NotStarted; + + var prevStatesFull = default(ulong?); + var prevStates2Bit = default(byte?); + var prevHorn = default(bool); + var prevGunTrigger = default(bool); + var prevAction = default(bool); + var prevSteer = default(sbyte); + var prevAccel = default(bool); + var prevBrake = default(bool); + var prevStrafe = NET.Inputs.EStrafe.None; + var prevWalk = NET.Inputs.EWalk.None; + var prevVertical = default(byte); + var prevHorizontal = default(byte); + + for (var i = 0; i < ticks; i++) + { + var time = new TimeInt32(i * 10) + StartOffset.GetValueOrDefault(); + + try + { + var sameState = r.ReadBit(); + + if (!sameState) + { + var only2Bit = r.ReadBit(); + + if (only2Bit) + { + var states = r.Read2Bit(); + + if (states != prevStates2Bit) + { + if (started is EStart.Vehicle) + { + if (StateIsDifferent(bit: 1, out bool horn2Bit, states, prevStates2Bit) && horn2Bit != prevHorn) + { + inputs.Add(new Horn(time, horn2Bit)); + prevHorn = horn2Bit; + } + } + else if (started is EStart.Character) + { + if (StateIsDifferent(bit: 0, out bool gunTrigger, states, prevStates2Bit) && gunTrigger != prevGunTrigger) + { + inputs.Add(new GunTrigger(time, gunTrigger)); + prevGunTrigger = gunTrigger; + } + + if (StateIsDifferent(bit: 1, out bool action, states, prevStates2Bit) && action != prevAction) + { + inputs.Add(new Inputs.Action(time, action)); + prevAction = action; + } + } + + prevStates2Bit = states; + } + } + else + { + var states = r.ReadNumber(bits: version is EVersion._2020_04_08 ? 33 : 34); + + if (started is EStart.NotStarted) + { + started = (EStart)(states & 3); + + if (started is EStart.VehicleMix) + { + started = EStart.Vehicle; + } + } + + if (started is EStart.Character) + { + if (StateIsDifferent(bit: 5, out bool gunTrigger, states, prevStatesFull) && gunTrigger != prevGunTrigger) + { + inputs.Add(new GunTrigger(time, gunTrigger)); + prevGunTrigger = gunTrigger; + } + } + + if (StateIsDifferent(bit: 6, out bool hornOrAction, states, prevStatesFull)) + { + if (started is EStart.Vehicle && hornOrAction != prevHorn) + { + inputs.Add(new Horn(time, hornOrAction)); + prevHorn = hornOrAction; + } + else if (started is EStart.Character && hornOrAction != prevAction) + { + inputs.Add(new Inputs.Action(time, hornOrAction)); + prevAction = hornOrAction; + } + } + + if (started is EStart.Character && StateIsDifferent(bit: 10, out bool camera2, states, prevStatesFull)) + { + inputs.Add(new Camera2(time, camera2)); + } + + if (StateIsDifferent(bit: 12, out bool jump, states, prevStatesFull)) + { + inputs.Add(new Jump(time, jump)); + } + + if (StateIsDifferent(bit: 13, out bool freeLook, states, prevStatesFull)) + { + inputs.Add(new FreeLook(time, freeLook)); + } + + for (var j = 0; j < 9; j++) // 9 action slots + { + // Action slots 2 and 4 have an additional bit 7 usage, which is ignored here + + if (StateIsDifferent(bit: 14 + j, out bool actionSlot, states, prevStatesFull)) + { + inputs.Add(new ActionSlot(time, (byte)(1 + j), actionSlot)); + } + } + + // + 1 action slot 0 + + if (StateIsDifferent(bit: 23, out bool actionSlot0, states, prevStatesFull)) + { + inputs.Add(new ActionSlot(time, 0, actionSlot0)); + } + + if (((states >> 31) & 1) != 0) + { + inputs.Add(new RespawnTM2020(time)); + } + + if (((states >> 33) & 1) != 0) + { + inputs.Add(new SecondaryRespawn(time)); + } + + prevStatesFull = states; + } + } + + var sameMouse = r.ReadBit(); + + if (!sameMouse) + { + var mouseAccuX = r.ReadUInt16(); + var mouseAccuY = r.ReadUInt16(); + + inputs.Add(new MouseAccu(time, mouseAccuX, mouseAccuY)); + } + + // In code, this check is presented as '(X - 2 & 0xfffffffd) == 0' + + switch (started) + { + case EStart.Vehicle: + var sameVehicleValue = r.ReadBit(); + + if (sameVehicleValue) + { + break; + } + + var steer = r.ReadSByte(); + + if (steer != prevSteer) + { + inputs.Add(new SteerTM2020(time, steer)); + prevSteer = steer; + } + + var accel = r.ReadBit(); + + if (accel != prevAccel) + { + inputs.Add(new Accelerate(time, accel)); + prevAccel = accel; + } + + var brake = r.ReadBit(); + + if (brake != prevBrake) + { + inputs.Add(new Brake(time, brake)); + prevBrake = brake; + } + + break; + + case EStart.Character: + var sameCharacterValue = r.ReadBit(); + + if (sameCharacterValue) + { + break; + } + + var strafe = (Inputs.EStrafe)r.Read2Bit(); + if (strafe == NET.Inputs.EStrafe.Corrupted) throw new Exception("Corrupted inputs. (strafe == 2)"); + + if (strafe != prevStrafe) + { + inputs.Add(new Strafe(time, strafe)); + prevStrafe = strafe; + } + + var walk = (Inputs.EWalk)r.Read2Bit(); + if (walk == NET.Inputs.EWalk.Corrupted) throw new Exception("Corrupted inputs. (walk == 2)"); + + if (walk != prevWalk) + { + inputs.Add(new Walk(time, walk)); + prevWalk = walk; + } + + var vertical = r.Read2Bit(); + + if (vertical != prevVertical) + { + inputs.Add(new Vertical(time, vertical)); + prevVertical = vertical; + } + + var horizontal = r.Read2Bit(); + + if (horizontal != prevHorizontal) + { + inputs.Add(new Horizontal(time, horizontal)); + prevHorizontal = horizontal; + } + + break; + } + } + catch (IndexOutOfRangeException) + { + // TM2020 moment + } + } - if (theRest.Any(x => x != 0)) - { - throw new Exception("Input buffer not cleared out completely"); - } + var theRest = r.ReadToEnd(); - return inputs.ToImmutable(); - } + if (theRest.Any(x => x != 0)) + { + throw new Exception("Input buffer not cleared out completely"); + } - internal IEnumerable ProcessShootmaniaInputChanges() + return inputs.ToImmutable(); + } + + internal IEnumerable ProcessShootmaniaInputChanges() { if (data is null) { @@ -557,82 +557,82 @@ internal IEnumerable ProcessShootmaniaInputChanges() var r = new BitReader(data); - for (var i = 0; i < ticks; i++) - { - var different = false; + for (var i = 0; i < ticks; i++) + { + var different = false; - var mouseAccuX = default(ushort?); - var mouseAccuY = default(ushort?); - var strafe = default(EStrafe?); - var walk = default(EWalk?); - var vertical = default(byte?); - var states = default(int?); + var mouseAccuX = default(ushort?); + var mouseAccuY = default(ushort?); + var strafe = default(EStrafe?); + var walk = default(EWalk?); + var vertical = default(byte?); + var states = default(int?); - var sameMouse = r.ReadBit(); + var sameMouse = r.ReadBit(); - if (!sameMouse) - { - mouseAccuX = r.ReadUInt16(); - mouseAccuY = r.ReadUInt16(); + if (!sameMouse) + { + mouseAccuX = r.ReadUInt16(); + mouseAccuY = r.ReadUInt16(); - different = true; - } + different = true; + } - var sameValuesAfter = r.ReadBit(); - var sameValue = sameValuesAfter; + var sameValuesAfter = r.ReadBit(); + var sameValue = sameValuesAfter; - if (!sameValuesAfter) - { - sameValue = r.ReadBit(); - } + if (!sameValuesAfter) + { + sameValue = r.ReadBit(); + } - if (!sameValue) - { - strafe = (EStrafe)r.Read2Bit(); - if (strafe == EStrafe.Corrupted) throw new Exception("Corrupted inputs. (strafe == 2)"); + if (!sameValue) + { + strafe = (EStrafe)r.Read2Bit(); + if (strafe == EStrafe.Corrupted) throw new Exception("Corrupted inputs. (strafe == 2)"); - walk = (EWalk)r.Read2Bit(); - if (walk == EWalk.Corrupted) throw new Exception("Corrupted inputs. (walk == 2)"); + walk = (EWalk)r.Read2Bit(); + if (walk == EWalk.Corrupted) throw new Exception("Corrupted inputs. (walk == 2)"); - if (version == EVersion._2017_09_12) - { - vertical = r.Read2Bit(); - } + if (version == EVersion._2017_09_12) + { + vertical = r.Read2Bit(); + } - different = true; - } + different = true; + } - if (!sameValuesAfter) - { - sameValue = r.ReadBit(); + if (!sameValuesAfter) + { + sameValue = r.ReadBit(); - if (!sameValue) - { - var onlyTriggerAndAction = r.ReadBit(); + if (!sameValue) + { + var onlyTriggerAndAction = r.ReadBit(); - states = onlyTriggerAndAction - ? r.Read2Bit() - : r.ReadInt32(); + states = onlyTriggerAndAction + ? r.Read2Bit() + : r.ReadInt32(); - different = true; - } - } + different = true; + } + } - if (different) - { - yield return new ShootmaniaInputChange(i, mouseAccuX, mouseAccuY, strafe, walk, vertical, states); - } - } + if (different) + { + yield return new ShootmaniaInputChange(i, mouseAccuX, mouseAccuY, strafe, walk, vertical, states); + } + } - var theRest = r.ReadToEnd(); + var theRest = r.ReadToEnd(); - if (theRest.Any(x => x != 0)) - { - throw new Exception("Input buffer not cleared out completely"); - } - } + if (theRest.Any(x => x != 0)) + { + throw new Exception("Input buffer not cleared out completely"); + } + } - internal IEnumerable ProcessTrackmaniaInputChanges() + internal IEnumerable ProcessTrackmaniaInputChanges() { if (data is null) { @@ -641,219 +641,219 @@ internal IEnumerable ProcessTrackmaniaInputChanges() var r = new BitReader(data); - var started = EStart.NotStarted; - - for (var i = 0; i < ticks; i++) - { - var different = false; - - var states = default(ulong?); - var mouseAccuX = default(ushort?); - var mouseAccuY = default(ushort?); - var steer = default(sbyte?); - var gas = default(bool?); - var brake = default(bool?); - var horn = default(bool?); - var characterStates = default(byte?); - - try - { - var sameState = r.ReadBit(); - - if (!sameState) - { - var onlyHorn = r.ReadBit(); - - states = onlyHorn - ? r.Read2Bit() - : r.ReadNumber(bits: version is EVersion._2020_04_08 ? 33 : 34); - - if (started is EStart.NotStarted) - { - started = (EStart)(states & 3); - - if (started is EStart.VehicleMix) - { - started = EStart.Vehicle; - } - - horn = (states & 64) != 0; // a weird bit that can appear sometimes during the run too - } - else if (started is EStart.Vehicle) - { - horn = onlyHorn - ? (states & 2) != 0 - : (states & 64) != 0; - } - - different = true; - } - - var sameMouse = r.ReadBit(); - - if (!sameMouse) - { - mouseAccuX = r.ReadUInt16(); - mouseAccuY = r.ReadUInt16(); - - different = true; - } - - // This check is a bit weird, may not work for StormMan gameplay - // If starting with horn on, it is included on first tick - // If mouse is not plugged, it is also included - // In code, this check is presented as '(X - 2 & 0xfffffffd) == 0' - - switch (started) - { - case EStart.Vehicle: - var sameVehicleValue = r.ReadBit(); - - if (!sameVehicleValue) - { - steer = r.ReadSByte(); - gas = r.ReadBit(); - brake = r.ReadBit(); - - different = true; - } - - break; - - case EStart.Character: - var sameCharacterValue = r.ReadBit(); - - if (!sameCharacterValue) - { - // Strafe2 - // Walk2 - // Vertical2 - // Horiz2 - characterStates = r.ReadByte(); - - different = true; - } - - break; - } - } - catch (IndexOutOfRangeException) - { - // TM2020 moment - } - - if (different) - { - yield return new TrackmaniaInputChange(i, states, mouseAccuX, mouseAccuY, steer, gas, brake, horn, characterStates); - } - } - - var theRest = r.ReadToEnd(); - - if (theRest.Any(x => x != 0)) - { - throw new Exception("Input buffer not cleared out completely"); - } - } - - public enum EStrafe : byte - { - None, - Left, - Corrupted, - Right - } - - public enum EWalk : byte - { - None, - Forward, - Corrupted, - Backward - } - - public interface IInputChange - { - int Tick { get; } - ushort? MouseAccuX { get; } - ushort? MouseAccuY { get; } - ulong? States { get; } - bool? Respawn { get; } - bool? Horn { get; } - - bool? FreeLook { get; } - bool? ActionSlot1 { get; } - bool? ActionSlot2 { get; } - bool? ActionSlot3 { get; } - bool? ActionSlot4 { get; } - - EStrafe? Strafe { get; } - EWalk? Walk { get; } - byte? Vertical { get; } - - TimeInt32 Timestamp { get; } - } - - public readonly record struct ShootmaniaInputChange(int Tick, - ushort? MouseAccuX, - ushort? MouseAccuY, - EStrafe? Strafe, - EWalk? Walk, - byte? Vertical, - int? States) : IInputChange - { - public TimeInt32 Timestamp => new(Tick * 10); - - public bool? IsGunTrigger => States is null ? null : (States & 2) != 0; - public bool? FreeLook => States is null ? null : (States & 4) != 0; - public bool? Fly => States is null ? null : (States & 8) != 0; - public bool? Camera2 => States is null ? null : (States & 32) != 0; - public bool? Jump => States is null ? null : (States & 128) != 0; - public bool? IsAction => States is null ? null : (States & 257) != 0; - public bool? ActionSlot1 => States is null ? null : (States & 1024) != 0; - public bool? ActionSlot2 => States is null ? null : (States & 2048) != 0; - public bool? ActionSlot3 => States is null ? null : (States & 4096) != 0; - public bool? ActionSlot4 => States is null ? null : (States & 8192) != 0; - public bool? Use1 => States is null ? null : (States & 16896) != 0; - public bool? Use2 => States is null ? null : (States & 32832) != 0; - public bool? Menu => States is null ? null : (States & 65536) != 0; - public bool? Horn => States is null ? null : (States & 1048576) != 0; - public bool? Respawn => States is null ? null : (States & 2097152) != 0; - public bool? GiveUp => States is null ? null : (States & (1 << 26)) != 0; - - ulong? IInputChange.States => States is null ? null : (ulong)States; - } - - public readonly record struct TrackmaniaInputChange(int Tick, - ulong? States, - ushort? MouseAccuX, - ushort? MouseAccuY, - sbyte? Steer, - bool? Gas, - bool? Brake, - bool? Horn = null, - byte? CharacterStates = null) : IInputChange - { - public TimeInt32 Timestamp { get; } = new(Tick * 10); - - public bool? FreeLook => States is null ? null : (States & 8192) != 0; // bit 13 - public bool? ActionSlot1 => States is null ? null : (States & (1 << 14)) != 0; - public bool? ActionSlot2 => States is null ? null : (States & 32896) != 0; // bit 15 (and bit 7?) - public bool? ActionSlot3 => States is null ? null : (States & (1 << 16)) != 0; - public bool? ActionSlot4 => States is null ? null : (States & 132096) != 0; // bit 17 (and bit 7?) - public bool? ActionSlot5 => States is null ? null : (States & (1 << 18)) != 0; - public bool? ActionSlot6 => States is null ? null : (States & 524288) != 0; // bit 19 - public bool? ActionSlot7 => States is null ? null : (States & (1 << 20)) != 0; - public bool? ActionSlot8 => States is null ? null : (States & 2097152) != 0; // bit 21 - public bool? ActionSlot9 => States is null ? null : (States & (1 << 22)) != 0; - public bool? ActionSlot0 => States is null ? null : (States & 8388608) != 0; // bit 23 - public bool? Respawn => States is null ? null : (States & 2147483648) != 0; - public bool? SecondaryRespawn => States is null ? null : (States & 8589934592) != 0; - - public EStrafe? Strafe => CharacterStates is null ? null : (EStrafe)(CharacterStates & 3); - public EWalk? Walk => CharacterStates is null ? null : (EWalk)((CharacterStates >> 2) & 3); - public byte? Vertical => CharacterStates is null ? null : (byte)((CharacterStates >> 4) & 3); - public byte? Horizontal => CharacterStates is null ? null : (byte)((CharacterStates >> 6) & 3); - } - } + var started = EStart.NotStarted; + + for (var i = 0; i < ticks; i++) + { + var different = false; + + var states = default(ulong?); + var mouseAccuX = default(ushort?); + var mouseAccuY = default(ushort?); + var steer = default(sbyte?); + var gas = default(bool?); + var brake = default(bool?); + var horn = default(bool?); + var characterStates = default(byte?); + + try + { + var sameState = r.ReadBit(); + + if (!sameState) + { + var onlyHorn = r.ReadBit(); + + states = onlyHorn + ? r.Read2Bit() + : r.ReadNumber(bits: version is EVersion._2020_04_08 ? 33 : 34); + + if (started is EStart.NotStarted) + { + started = (EStart)(states & 3); + + if (started is EStart.VehicleMix) + { + started = EStart.Vehicle; + } + + horn = (states & 64) != 0; // a weird bit that can appear sometimes during the run too + } + else if (started is EStart.Vehicle) + { + horn = onlyHorn + ? (states & 2) != 0 + : (states & 64) != 0; + } + + different = true; + } + + var sameMouse = r.ReadBit(); + + if (!sameMouse) + { + mouseAccuX = r.ReadUInt16(); + mouseAccuY = r.ReadUInt16(); + + different = true; + } + + // This check is a bit weird, may not work for StormMan gameplay + // If starting with horn on, it is included on first tick + // If mouse is not plugged, it is also included + // In code, this check is presented as '(X - 2 & 0xfffffffd) == 0' + + switch (started) + { + case EStart.Vehicle: + var sameVehicleValue = r.ReadBit(); + + if (!sameVehicleValue) + { + steer = r.ReadSByte(); + gas = r.ReadBit(); + brake = r.ReadBit(); + + different = true; + } + + break; + + case EStart.Character: + var sameCharacterValue = r.ReadBit(); + + if (!sameCharacterValue) + { + // Strafe2 + // Walk2 + // Vertical2 + // Horiz2 + characterStates = r.ReadByte(); + + different = true; + } + + break; + } + } + catch (IndexOutOfRangeException) + { + // TM2020 moment + } + + if (different) + { + yield return new TrackmaniaInputChange(i, states, mouseAccuX, mouseAccuY, steer, gas, brake, horn, characterStates); + } + } + + var theRest = r.ReadToEnd(); + + if (theRest.Any(x => x != 0)) + { + throw new Exception("Input buffer not cleared out completely"); + } + } + + public enum EStrafe : byte + { + None, + Left, + Corrupted, + Right + } + + public enum EWalk : byte + { + None, + Forward, + Corrupted, + Backward + } + + public interface IInputChange + { + int Tick { get; } + ushort? MouseAccuX { get; } + ushort? MouseAccuY { get; } + ulong? States { get; } + bool? Respawn { get; } + bool? Horn { get; } + + bool? FreeLook { get; } + bool? ActionSlot1 { get; } + bool? ActionSlot2 { get; } + bool? ActionSlot3 { get; } + bool? ActionSlot4 { get; } + + EStrafe? Strafe { get; } + EWalk? Walk { get; } + byte? Vertical { get; } + + TimeInt32 Timestamp { get; } + } + + public readonly record struct ShootmaniaInputChange(int Tick, + ushort? MouseAccuX, + ushort? MouseAccuY, + EStrafe? Strafe, + EWalk? Walk, + byte? Vertical, + int? States) : IInputChange + { + public TimeInt32 Timestamp => new(Tick * 10); + + public bool? IsGunTrigger => States is null ? null : (States & 2) != 0; + public bool? FreeLook => States is null ? null : (States & 4) != 0; + public bool? Fly => States is null ? null : (States & 8) != 0; + public bool? Camera2 => States is null ? null : (States & 32) != 0; + public bool? Jump => States is null ? null : (States & 128) != 0; + public bool? IsAction => States is null ? null : (States & 257) != 0; + public bool? ActionSlot1 => States is null ? null : (States & 1024) != 0; + public bool? ActionSlot2 => States is null ? null : (States & 2048) != 0; + public bool? ActionSlot3 => States is null ? null : (States & 4096) != 0; + public bool? ActionSlot4 => States is null ? null : (States & 8192) != 0; + public bool? Use1 => States is null ? null : (States & 16896) != 0; + public bool? Use2 => States is null ? null : (States & 32832) != 0; + public bool? Menu => States is null ? null : (States & 65536) != 0; + public bool? Horn => States is null ? null : (States & 1048576) != 0; + public bool? Respawn => States is null ? null : (States & 2097152) != 0; + public bool? GiveUp => States is null ? null : (States & (1 << 26)) != 0; + + ulong? IInputChange.States => States is null ? null : (ulong)States; + } + + public readonly record struct TrackmaniaInputChange(int Tick, + ulong? States, + ushort? MouseAccuX, + ushort? MouseAccuY, + sbyte? Steer, + bool? Gas, + bool? Brake, + bool? Horn = null, + byte? CharacterStates = null) : IInputChange + { + public TimeInt32 Timestamp { get; } = new(Tick * 10); + + public bool? FreeLook => States is null ? null : (States & 8192) != 0; // bit 13 + public bool? ActionSlot1 => States is null ? null : (States & (1 << 14)) != 0; + public bool? ActionSlot2 => States is null ? null : (States & 32896) != 0; // bit 15 (and bit 7?) + public bool? ActionSlot3 => States is null ? null : (States & (1 << 16)) != 0; + public bool? ActionSlot4 => States is null ? null : (States & 132096) != 0; // bit 17 (and bit 7?) + public bool? ActionSlot5 => States is null ? null : (States & (1 << 18)) != 0; + public bool? ActionSlot6 => States is null ? null : (States & 524288) != 0; // bit 19 + public bool? ActionSlot7 => States is null ? null : (States & (1 << 20)) != 0; + public bool? ActionSlot8 => States is null ? null : (States & 2097152) != 0; // bit 21 + public bool? ActionSlot9 => States is null ? null : (States & (1 << 22)) != 0; + public bool? ActionSlot0 => States is null ? null : (States & 8388608) != 0; // bit 23 + public bool? Respawn => States is null ? null : (States & 2147483648) != 0; + public bool? SecondaryRespawn => States is null ? null : (States & 8589934592) != 0; + + public EStrafe? Strafe => CharacterStates is null ? null : (EStrafe)(CharacterStates & 3); + public EWalk? Walk => CharacterStates is null ? null : (EWalk)((CharacterStates >> 2) & 3); + public byte? Vertical => CharacterStates is null ? null : (byte)((CharacterStates >> 4) & 3); + public byte? Horizontal => CharacterStates is null ? null : (byte)((CharacterStates >> 6) & 3); + } + } } \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Game/CGameCtnMediaClip.cs b/Src/GBX.NET/Engines/Game/CGameCtnMediaClip.cs index d41cbeb3e..44022597f 100644 --- a/Src/GBX.NET/Engines/Game/CGameCtnMediaClip.cs +++ b/Src/GBX.NET/Engines/Game/CGameCtnMediaClip.cs @@ -2,9 +2,17 @@ public partial class CGameCtnMediaClip { + private string? name; + [AppliedWithChunk] + [AppliedWithChunk] + [AppliedWithChunk] + [AppliedWithChunk] + public string? Name { get => name; set => name = value; } + private IList? tracks; [AppliedWithChunk] [AppliedWithChunk] + [AppliedWithChunk] [AppliedWithChunk] public IList Tracks { diff --git a/Src/GBX.NET/Engines/Game/CGameCtnReplayRecord.cs b/Src/GBX.NET/Engines/Game/CGameCtnReplayRecord.cs index 672f29ef5..6f42e86bb 100644 --- a/Src/GBX.NET/Engines/Game/CGameCtnReplayRecord.cs +++ b/Src/GBX.NET/Engines/Game/CGameCtnReplayRecord.cs @@ -22,6 +22,7 @@ public partial class CGameCtnReplayRecord /// /// Nickname of the record owner. /// + [SupportsFormatting] public string? PlayerNickname { get; private set; } /// @@ -49,6 +50,7 @@ public partial class CGameCtnReplayRecord /// /// Nickname of the replay creator. /// + [SupportsFormatting] public string? AuthorNickname { get; private set; } /// @@ -140,21 +142,42 @@ public IEnumerable GetGhosts(bool alsoInClips = true) } } - public Gbx? GetChallengeHeader() + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public async ValueTask?> GetChallengeAsync(GbxReadSettings settings = default, CancellationToken cancellationToken = default) { if (challengeData is null) { return null; } +#if NETSTANDARD2_0 using var ms = new MemoryStream(challengeData); +#else + await using var ms = new MemoryStream(challengeData); +#endif + return await Gbx.ParseAsync(ms, settings, cancellationToken); + } + + [Zomp.SyncMethodGenerator.CreateSyncVersion] + public async Task GetChallengeNodeAsync(GbxReadSettings settings = default, CancellationToken cancellationToken = default) + { + return (await GetChallengeAsync(settings, cancellationToken))?.Node; + } - return Gbx.ParseHeader(ms); + public Gbx? GetChallengeHeader(GbxReadSettings settings = default) + { + if (challengeData is null) + { + return null; + } + + using var ms = new MemoryStream(challengeData); + return Gbx.ParseHeader(ms, settings); } - public CGameCtnChallenge? GetChallengeHeaderNode() + public CGameCtnChallenge? GetChallengeHeaderNode(GbxReadSettings settings = default) { - return GetChallengeHeader()?.Node; + return GetChallengeHeader(settings)?.Node; } public partial class HeaderChunk03093000 : IVersionable diff --git a/Src/GBX.NET/Engines/Meta/NPlugDynaObjectModel_SInstanceParams.chunkl b/Src/GBX.NET/Engines/Meta/NPlugDynaObjectModel_SInstanceParams.chunkl new file mode 100644 index 000000000..1c41ddc98 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugDynaObjectModel_SInstanceParams.chunkl @@ -0,0 +1,14 @@ +NPlugDynaObjectModel_SInstanceParams 0x2F0B6000 +- inherits: SMetaPtr + +archive + version + float PeriodSc + int TextureId + bool IsKinematic + if Version >= 1 + float PeriodScMax + float Phase01 + float Phase01Max + if Version >= 2 + bool CastStaticShadow \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Meta/NPlugDynaObjectModel_SInstanceParams.cs b/Src/GBX.NET/Engines/Meta/NPlugDynaObjectModel_SInstanceParams.cs new file mode 100644 index 000000000..f88069ba6 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugDynaObjectModel_SInstanceParams.cs @@ -0,0 +1,18 @@ +namespace GBX.NET.Engines.Meta; + +public partial class NPlugDynaObjectModel_SInstanceParams : IVersionable +{ + public int Version { get; set; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + ReadWrite(rw, v: 0); + } +} diff --git a/Src/GBX.NET/Engines/Meta/NPlugDyna_SKinematicConstraint.chunkl b/Src/GBX.NET/Engines/Meta/NPlugDyna_SKinematicConstraint.chunkl new file mode 100644 index 000000000..ac9ee3ef4 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugDyna_SKinematicConstraint.chunkl @@ -0,0 +1,83 @@ +NPlugDyna_SKinematicConstraint 0x2F0CA000 + +archive + version + int SubVersion + AnimFunc TransAnimFunc + AnimFunc RotAnimFunc + int ShaderTcType + int ShaderTcVersion + AnimFuncNat[] ShaderTcAnimFunc + if (int)ShaderTcType == 1 + TransSubTextureIn ShaderTcDataTransSub + byte TransAxis + float TransMin + float TransMax + byte RotAxis + float AngleMinDeg + float AngleMaxDeg + +archive AnimFunc + bool IsDuration + SubAnimFunc[] SubFuncs + +archive SubAnimFunc + byte Ease + boolbyte Reverse + timeint Duration + +archive AnimFuncNat + timeint Duration + int TextureId + +archive TransSubTextureIn + int NbSubTexture + int NbSubTexturePerLine + int NbSubTexturePerColumn + bool TopToBottom + +enum AnimEase + Constant + Linear + QuadIn + QuadOut + QuadInOut + CubicIn + CubicOut + CubicInOut + QuartIn + QuartOut + QuartInOut + QuintIn + QuintOut + QuintInOut + SineIn + SineOut + SineInOut + ExpIn + ExpOut + ExpInOut + CircIn + CircOut + CircInOut + BackIn + BackOut + BackInOut + ElasticIn + ElasticOut + ElasticInOut + ElasticIn2 + ElasticOut2 + ElasticInOut2 + BounceIn + BounceOut + BounceInOut + +enum EShaderTcType + None + TransSubTexture + +enum EAxis + X + Y + Z \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Meta/NPlugDyna_SKinematicConstraint.cs b/Src/GBX.NET/Engines/Meta/NPlugDyna_SKinematicConstraint.cs new file mode 100644 index 000000000..cb5d4d5a6 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugDyna_SKinematicConstraint.cs @@ -0,0 +1,18 @@ +namespace GBX.NET.Engines.Meta; + +public partial class NPlugDyna_SKinematicConstraint : IVersionable +{ + public int Version { get; set; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + ReadWrite(rw, v: 0); + } +} diff --git a/Src/GBX.NET/Engines/Meta/NPlugDyna_SPrefabConstraintParams.chunkl b/Src/GBX.NET/Engines/Meta/NPlugDyna_SPrefabConstraintParams.chunkl new file mode 100644 index 000000000..bc331eb09 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugDyna_SPrefabConstraintParams.chunkl @@ -0,0 +1,9 @@ +NPlugDyna_SPrefabConstraintParams 0x2F0C8000 +- inherits: SMetaPtr + +archive + version + int Ent1 + int Ent2 + vec3 Pos1 + vec3 Pos2 \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Meta/NPlugDyna_SPrefabConstraintParams.cs b/Src/GBX.NET/Engines/Meta/NPlugDyna_SPrefabConstraintParams.cs new file mode 100644 index 000000000..93b7c1f5a --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugDyna_SPrefabConstraintParams.cs @@ -0,0 +1,18 @@ +namespace GBX.NET.Engines.Meta; + +public partial class NPlugDyna_SPrefabConstraintParams : IVersionable +{ + public int Version { get; set; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + ReadWrite(rw, v: 0); + } +} diff --git a/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacement.chunkl b/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacement.chunkl new file mode 100644 index 000000000..7b76db9ea --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacement.chunkl @@ -0,0 +1,7 @@ +NPlugItemPlacement_SPlacement 0x2F0A9000 +- inherits: SMetaPtr + +archive + version + int ILayout + NPlugItemPlacement_SPlacementOption[] Options \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacement.cs b/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacement.cs new file mode 100644 index 000000000..f9d5630ca --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacement.cs @@ -0,0 +1,18 @@ +namespace GBX.NET.Engines.Meta; + +public partial class NPlugItemPlacement_SPlacement : IVersionable +{ + public int Version { get; set; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + ReadWrite(rw, v: 0); + } +} diff --git a/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacementGroup.chunkl b/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacementGroup.chunkl new file mode 100644 index 000000000..54f0d7201 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacementGroup.chunkl @@ -0,0 +1,8 @@ +NPlugItemPlacement_SPlacementGroup 0x2F0D8000 +- inherits: SMetaPtr + +archive + version + NPlugItemPlacement_SPlacement[] Placements + short[] + transquat[] \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacementGroup.cs b/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacementGroup.cs new file mode 100644 index 000000000..93b64ea62 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugItemPlacement_SPlacementGroup.cs @@ -0,0 +1,18 @@ +namespace GBX.NET.Engines.Meta; + +public partial class NPlugItemPlacement_SPlacementGroup : IVersionable +{ + public int Version { get; set; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + ReadWrite(rw, v: 0); + } +} diff --git a/Src/GBX.NET/Engines/Meta/NPlugStaticObjectModel_SInstanceParams.chunkl b/Src/GBX.NET/Engines/Meta/NPlugStaticObjectModel_SInstanceParams.chunkl new file mode 100644 index 000000000..632bd54f1 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugStaticObjectModel_SInstanceParams.chunkl @@ -0,0 +1,6 @@ +NPlugStaticObjectModel_SInstanceParams 0x2F0D9000 +- inherits: SMetaPtr + +archive + version + float Phase01 \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Meta/NPlugStaticObjectModel_SInstanceParams.cs b/Src/GBX.NET/Engines/Meta/NPlugStaticObjectModel_SInstanceParams.cs new file mode 100644 index 000000000..d7ac37da7 --- /dev/null +++ b/Src/GBX.NET/Engines/Meta/NPlugStaticObjectModel_SInstanceParams.cs @@ -0,0 +1,18 @@ +namespace GBX.NET.Engines.Meta; + +public partial class NPlugStaticObjectModel_SInstanceParams : IVersionable +{ + public int Version { get; set; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + ReadWrite(rw, v: 0); + } +} diff --git a/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItemPlacement_SPlacementOption.chunkl b/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItemPlacement_SPlacementOption.chunkl new file mode 100644 index 000000000..92e9d7e73 --- /dev/null +++ b/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItemPlacement_SPlacementOption.chunkl @@ -0,0 +1,3 @@ +NPlugItemPlacement_SPlacementOption 0x301B5000 + +archive \ No newline at end of file diff --git a/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItemPlacement_SPlacementOption.cs b/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItemPlacement_SPlacementOption.cs new file mode 100644 index 000000000..d3e4fccba --- /dev/null +++ b/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItemPlacement_SPlacementOption.cs @@ -0,0 +1,34 @@ + +namespace GBX.NET.Engines.MetaNotPersistent; + +public partial class NPlugItemPlacement_SPlacementOption +{ + public Dictionary RequiredTags { get; set; } = []; + + public void ReadWrite(GbxReaderWriter rw, int v = 0) + { + if (rw.Reader is not null) + { + var count = rw.Reader.ReadInt32(); + RequiredTags = new Dictionary(count); + + for (var i = 0; i < count; i++) + { + var key = rw.Reader.ReadString(); + var value = rw.Reader.ReadString(); + RequiredTags[key] = value; + } + } + + if (rw.Writer is not null) + { + rw.Writer.Write(RequiredTags.Count); + + foreach (var pair in RequiredTags) + { + rw.Writer.Write(pair.Key); + rw.Writer.Write(pair.Value); + } + } + } +} diff --git a/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItem_SVariant.cs b/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItem_SVariant.cs index 48bba2c52..ab7590261 100644 --- a/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItem_SVariant.cs +++ b/Src/GBX.NET/Engines/MetaNotPersistent/NPlugItem_SVariant.cs @@ -9,7 +9,7 @@ public partial class NPlugItem_SVariant public CMwNod? EntityModel { get => entityModelFile?.GetNode(ref entityModel) ?? entityModel; set => entityModel = value; } private Components.GbxRefTableFile? entityModelFile; public Components.GbxRefTableFile? EntityModelFile { get => entityModelFile; set => entityModelFile = value; } - public CMwNod? GetEntityModel(GbxReadSettings settings = default) => entityModelFile?.GetNode(ref entityModel, settings); + public CMwNod? GetEntityModel(GbxReadSettings settings = default, bool exceptions = false) => entityModelFile?.GetNode(ref entityModel, settings, exceptions); private bool hiddenInManualCycle; public bool HiddenInManualCycle { get => hiddenInManualCycle; set => hiddenInManualCycle = value; } diff --git a/Src/GBX.NET/Engines/MwFoundations/CMwNod.cs b/Src/GBX.NET/Engines/MwFoundations/CMwNod.cs index e5ba920ee..9dd50f7ed 100644 --- a/Src/GBX.NET/Engines/MwFoundations/CMwNod.cs +++ b/Src/GBX.NET/Engines/MwFoundations/CMwNod.cs @@ -87,6 +87,29 @@ static void IClass.Read(T node, GbxReaderWriter rw) break; } + if (r.Settings.SafeSkippableChunks) + { + var data = r.ReadBytes(chunkSize); + using var ms = new MemoryStream(data); + using var rSafe = new GbxReader(ms, r.Settings); + rSafe.LoadFrom(r); + using var rwSafe = new GbxReaderWriter(rSafe); + + try + { + readableWritableT.ReadWrite(node, rwSafe); + } + catch (Exception ex) + { + r.Logger?.LogError(ex, "Skippable chunk data failed to read. Some properties may have been read. Buffer will be stored and used instead."); + ((ISkippableChunk)readableWritableT).Data = data; + } + + r.LoadFrom(rSafe); + + break; + } + readableWritableT.ReadWrite(node, rw); // TODO: validate chunk size @@ -100,6 +123,28 @@ static void IClass.Read(T node, GbxReaderWriter rw) break; } + if (r.Settings.SafeSkippableChunks) + { + var data = r.ReadBytes(chunkSize); + using var ms = new MemoryStream(data); + using var rSafe = new GbxReader(ms, r.Settings); + rSafe.LoadFrom(r); + + try + { + readableT.Read(node, rSafe); + } + catch (Exception ex) + { + r.Logger?.LogError(ex, "Skippable chunk data failed to read. Some properties may have been read. Buffer will be stored and used instead."); + ((ISkippableChunk)readableT).Data = data; + } + + r.LoadFrom(rSafe); + + break; + } + readableT.Read(node, r); // TODO: validate chunk size @@ -113,6 +158,29 @@ static void IClass.Read(T node, GbxReaderWriter rw) break; } + if (r.Settings.SafeSkippableChunks) + { + var data = r.ReadBytes(chunkSize); + using var ms = new MemoryStream(data); + using var rSafe = new GbxReader(ms, r.Settings); + rSafe.LoadFrom(r); + using var rwSafe = new GbxReaderWriter(rSafe); + + try + { + readableWritable.ReadWrite(node, rwSafe); + } + catch (Exception ex) + { + r.Logger?.LogError(ex, "Skippable chunk data failed to read. Some properties may have been read. Buffer will be stored and used instead."); + ((ISkippableChunk)readableWritable).Data = data; + } + + r.LoadFrom(rSafe); + + break; + } + readableWritable.ReadWrite(node, rw); // TODO: validate chunk size @@ -126,6 +194,28 @@ static void IClass.Read(T node, GbxReaderWriter rw) break; } + if (r.Settings.SafeSkippableChunks) + { + var data = r.ReadBytes(chunkSize); + using var ms = new MemoryStream(data); + using var rSafe = new GbxReader(ms, r.Settings); + rSafe.LoadFrom(r); + + try + { + readable.Read(node, rSafe); + } + catch (Exception ex) + { + r.Logger?.LogError(ex, "Skippable chunk data failed to read. Some properties may have been read. Buffer will be stored and used instead."); + ((ISkippableChunk)readable).Data = data; + } + + r.LoadFrom(rSafe); + + break; + } + readable.Read(node, r); // TODO: validate chunk size @@ -282,6 +372,29 @@ internal virtual void Read(GbxReaderWriter rw) break; } + if (r.Settings.SafeSkippableChunks) + { + var data = r.ReadBytes(chunkSize); + using var ms = new MemoryStream(data); + using var rSafe = new GbxReader(ms, r.Settings); + rSafe.LoadFrom(r); + using var rwSafe = new GbxReaderWriter(rSafe); + + try + { + readableWritable.ReadWrite(this, rwSafe); + } + catch (Exception ex) + { + r.Logger?.LogError(ex, "Skippable chunk data failed to read. Some properties may have been read. Buffer will be stored and used instead."); + ((ISkippableChunk)readableWritable).Data = data; + } + + r.LoadFrom(rSafe); + + break; + } + readableWritable.ReadWrite(this, rw); // TODO: validate chunk size @@ -296,6 +409,28 @@ internal virtual void Read(GbxReaderWriter rw) break; } + if (r.Settings.SafeSkippableChunks) + { + var data = r.ReadBytes(chunkSize); + using var ms = new MemoryStream(data); + using var rSafe = new GbxReader(ms, r.Settings); + rSafe.LoadFrom(r); + + try + { + readable.Read(this, rSafe); + } + catch (Exception ex) + { + r.Logger?.LogError(ex, "Skippable chunk data failed to read. Some properties may have been read. Buffer will be stored and used instead."); + ((ISkippableChunk)readable).Data = data; + } + + r.LoadFrom(rSafe); + + break; + } + readable.Read(this, r); // TODO: validate chunk size diff --git a/Src/GBX.NET/Engines/Plug/CPlugDynaObjectModel.chunkl b/Src/GBX.NET/Engines/Plug/CPlugDynaObjectModel.chunkl new file mode 100644 index 000000000..487814a17 --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/CPlugDynaObjectModel.chunkl @@ -0,0 +1 @@ +CPlugDynaObjectModel 0x09144000 \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Plug/CPlugDynaObjectModel.cs b/Src/GBX.NET/Engines/Plug/CPlugDynaObjectModel.cs new file mode 100644 index 000000000..9371ccce0 --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/CPlugDynaObjectModel.cs @@ -0,0 +1,86 @@ +namespace GBX.NET.Engines.Plug; + +public partial class CPlugDynaObjectModel : IVersionable +{ + private bool isStatic; + private bool dynamizeOnSpawn; + private CPlugSolid2Model? mesh; + private CPlugSurface? dynaShape; + private CPlugSurface? staticShape; + private float breakSpeedKmh; + private float mass; + private float lightAliveDurationScMin; + private float lightAliveDurationScMax; + private int u01; + private int u02; + private byte u03; + private byte u04; + private int u05; + private int u06; + private byte u07; + private int u08; + private int u09; + private CPlugAnimLocSimple? locAnim; + private int u10; + private bool locAnimIsPhysical; + private CPlugDynaWaterModel? waterModel; + + public int Version { get; set; } + + public bool IsStatic { get => isStatic; set => isStatic = value; } + public bool DynamizeOnSpawn { get => dynamizeOnSpawn; set => dynamizeOnSpawn = value; } + public CPlugSolid2Model? Mesh { get => mesh; set => mesh = value; } + public CPlugSurface? DynaShape { get => dynaShape; set => dynaShape = value; } + public CPlugSurface? StaticShape { get => staticShape; set => staticShape = value; } + public float BreakSpeedKmh { get => breakSpeedKmh; set => breakSpeedKmh = value; } + public float Mass { get => mass; set => mass = value; } + public float LightAliveDurationScMin { get => lightAliveDurationScMin; set => lightAliveDurationScMin = value; } + public float LightAliveDurationScMax { get => lightAliveDurationScMax; set => lightAliveDurationScMax = value; } + public int U01 { get => u01; set => u01 = value; } + public int U02 { get => u02; set => u02 = value; } + public byte U03 { get => u03; set => u03 = value; } + public byte U04 { get => u04; set => u04 = value; } + public int U05 { get => u05; set => u05 = value; } + public int U06 { get => u06; set => u06 = value; } + public byte U07 { get => u07; set => u07 = value; } + public int U08 { get => u08; set => u08 = value; } + public int U09 { get => u09; set => u09 = value; } + public CPlugAnimLocSimple? LocAnim { get => locAnim; set => locAnim = value; } + public int U10 { get => u10; set => u10 = value; } + public bool LocAnimIsPhysical { get => locAnimIsPhysical; set => locAnimIsPhysical = value; } + public CPlugDynaWaterModel? WaterModel { get => waterModel; set => waterModel = value; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + rw.VersionInt32(this); + rw.Boolean(ref isStatic); + rw.Boolean(ref dynamizeOnSpawn); + rw.NodeRef(ref mesh); + rw.NodeRef(ref dynaShape); + rw.NodeRef(ref staticShape); + rw.Single(ref breakSpeedKmh); + rw.Single(ref mass); + rw.Single(ref lightAliveDurationScMin); + rw.Single(ref lightAliveDurationScMax); + rw.Int32(ref u01); + rw.Int32(ref u02); + rw.Byte(ref u03); + rw.Byte(ref u04); + rw.Int32(ref u05); + rw.Int32(ref u06); + rw.Byte(ref u07); + rw.Int32(ref u08); + rw.Int32(ref u09); + rw.NodeRef(ref locAnim); + rw.Int32(ref u10); + rw.Boolean(ref locAnimIsPhysical); + rw.NodeRef(ref waterModel); + } +} diff --git a/Src/GBX.NET/Engines/Plug/CPlugDynaWaterModel.chunkl b/Src/GBX.NET/Engines/Plug/CPlugDynaWaterModel.chunkl new file mode 100644 index 000000000..f81a22056 --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/CPlugDynaWaterModel.chunkl @@ -0,0 +1 @@ +CPlugDynaWaterModel 0x0915F000 \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Plug/CPlugEditorHelper.chunkl b/Src/GBX.NET/Engines/Plug/CPlugEditorHelper.chunkl new file mode 100644 index 000000000..949ec47ed --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/CPlugEditorHelper.chunkl @@ -0,0 +1,5 @@ +CPlugEditorHelper 0x0917B000 + +archive + version + CPlugPrefab Prefab (external) \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Plug/CPlugEditorHelper.cs b/Src/GBX.NET/Engines/Plug/CPlugEditorHelper.cs new file mode 100644 index 000000000..e7b889e75 --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/CPlugEditorHelper.cs @@ -0,0 +1,18 @@ +namespace GBX.NET.Engines.Plug; + +public partial class CPlugEditorHelper : IVersionable +{ + public int Version { get; set; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + ReadWrite(rw, v: 0); + } +} diff --git a/Src/GBX.NET/Engines/Plug/CPlugGameSkin.cs b/Src/GBX.NET/Engines/Plug/CPlugGameSkin.cs index f304e0eb8..f42ede79c 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugGameSkin.cs +++ b/Src/GBX.NET/Engines/Plug/CPlugGameSkin.cs @@ -16,7 +16,7 @@ public partial class Fid : IReadableWritable public CMwNod? Node { get => nodeFile?.GetNode(ref node) ?? node; set => node = value; } private Components.GbxRefTableFile? nodeFile; public Components.GbxRefTableFile? NodeFile { get => nodeFile; set => nodeFile = value; } - public CMwNod? GetNode(GbxReadSettings settings = default) => nodeFile?.GetNode(ref node, settings) ?? node; + public CMwNod? GetNode(GbxReadSettings settings = default, bool exceptions = false) => nodeFile?.GetNode(ref node, settings, exceptions) ?? node; public string Directory { get => directory; set => directory = value; } public bool U01 { get => u01; set => u01 = value; } diff --git a/Src/GBX.NET/Engines/Plug/CPlugMaterial.chunkl b/Src/GBX.NET/Engines/Plug/CPlugMaterial.chunkl index 6200c6b46..175122a49 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugMaterial.chunkl +++ b/Src/GBX.NET/Engines/Plug/CPlugMaterial.chunkl @@ -1,6 +1,9 @@ CPlugMaterial 0x09079000 - inherits: CPlug +0x001 + CMwNod + 0x002 int @@ -10,6 +13,8 @@ CPlugMaterial 0x09079000 0x00A int +0x00D + 0x00E int @@ -27,3 +32,13 @@ CPlugMaterial 0x09079000 0x013 (skippable, ignore) 0x014 (skippable, ignore) + +archive DeviceMat + short + short + v4+ + bool + CPlugShader Shader1 (external) + v9+ + CPlugShader Shader2 (external) + CPlugShader Shader3 (external) \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Plug/CPlugMaterial.cs b/Src/GBX.NET/Engines/Plug/CPlugMaterial.cs new file mode 100644 index 000000000..696963a45 --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/CPlugMaterial.cs @@ -0,0 +1,34 @@ +namespace GBX.NET.Engines.Plug; + +public partial class CPlugMaterial +{ + private CPlug? shader; + [AppliedWithChunk] + public CPlug? Shader { get => shaderFile?.GetNode(ref shader) ?? shader; set => shader = value; } + private Components.GbxRefTableFile? shaderFile; + public Components.GbxRefTableFile? ShaderFile { get => shaderFile; set => shaderFile = value; } + public CPlug? GetShader(GbxReadSettings settings = default, bool exceptions = false) => shaderFile?.GetNode(ref shader, settings, exceptions) ?? shader; + + private DeviceMat[]? deviceMaterials; + [AppliedWithChunk] + public DeviceMat[]? DeviceMaterials { get => deviceMaterials; set => deviceMaterials = value; } + + public partial class Chunk0907900D + { + public int[]? U01; + + public override void ReadWrite(CPlugMaterial n, GbxReaderWriter rw) + { + rw.NodeRef(ref n.shader, ref n.shaderFile); + + if (n.shader is not null && n.shaderFile is not null) + { + return; + } + + rw.ArrayReadableWritable(ref n.deviceMaterials, version: 0xD); + + rw.Array(ref U01); + } + } +} diff --git a/Src/GBX.NET/Engines/Plug/CPlugPrefab.cs b/Src/GBX.NET/Engines/Plug/CPlugPrefab.cs index d72eff842..2d4b75820 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugPrefab.cs +++ b/Src/GBX.NET/Engines/Plug/CPlugPrefab.cs @@ -1,4 +1,5 @@ - +using GBX.NET.Managers; + namespace GBX.NET.Engines.Plug; public partial class CPlugPrefab : IVersionable @@ -41,7 +42,7 @@ public sealed partial class EntRef public CMwNod? Model { get => modelFile?.GetNode(ref model) ?? model; set => model = value; } private Components.GbxRefTableFile? modelFile; public Components.GbxRefTableFile? ModelFile { get => modelFile; set => modelFile = value; } - public CMwNod? GetModel(GbxReadSettings settings = default) => modelFile?.GetNode(ref model, settings); + public CMwNod? GetModel(GbxReadSettings settings = default, bool exceptions = false) => modelFile?.GetNode(ref model, settings, exceptions); private Quat rotation; public Quat Rotation { get => rotation; set => rotation = value; } @@ -61,10 +62,22 @@ public void ReadWrite(GbxReaderWriter rw, int v = 0) rw.Quat(ref rotation); rw.Vec3(ref position); - if (model is not null || modelFile is not null) + // should be replaced with rw.MetaRef in the future or something + var classId = rw.UInt32(@params is null + ? uint.MaxValue + : ClassManager.GetId(@params.GetType()) + .GetValueOrDefault(uint.MaxValue)); + + @params = classId switch { - rw.MetaRef(ref @params); - } + 0x2F0A9000 => rw.Node((NPlugItemPlacement_SPlacement?)@params), + 0x2F0B6000 => rw.Node((NPlugDynaObjectModel_SInstanceParams?)@params), + 0x2F0C8000 => rw.Node((NPlugDyna_SPrefabConstraintParams?)@params), + 0x2F0D8000 => rw.Node((NPlugItemPlacement_SPlacementGroup?)@params), + 0x2F0D9000 => rw.Node((NPlugStaticObjectModel_SInstanceParams?)@params), + uint.MaxValue => null, + _ => throw new NotImplementedException($"Unknown classId: 0x{classId:X8} ({ClassManager.GetName(classId)})"), + }; rw.String(ref u01); } diff --git a/Src/GBX.NET/Engines/Plug/CPlugShader.chunkl b/Src/GBX.NET/Engines/Plug/CPlugShader.chunkl index ad04449f2..1f2c2c117 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugShader.chunkl +++ b/Src/GBX.NET/Engines/Plug/CPlugShader.chunkl @@ -2,6 +2,9 @@ CPlugShader 0x09002000 - inherits: CPlug 0x007 + CMwNod + CMwNod[] // CPlugShaderPass array + CMwNod 0x00E (base: 0x007) base diff --git a/Src/GBX.NET/Engines/Plug/CPlugShaderGeneric.chunkl b/Src/GBX.NET/Engines/Plug/CPlugShaderGeneric.chunkl index 9b45817d0..de438a911 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugShaderGeneric.chunkl +++ b/Src/GBX.NET/Engines/Plug/CPlugShaderGeneric.chunkl @@ -1,6 +1,8 @@ CPlugShaderGeneric 0x09004000 - inherits: CPlugShader -0x001 (ignore) +0x001 + data[88] -0x003 (ignore) \ No newline at end of file +0x003 + data[88] \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Plug/CPlugSolid2Model.cs b/Src/GBX.NET/Engines/Plug/CPlugSolid2Model.cs index 780e6d598..31828295e 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugSolid2Model.cs +++ b/Src/GBX.NET/Engines/Plug/CPlugSolid2Model.cs @@ -155,7 +155,7 @@ public override void ReadWrite(CPlugSolid2Model n, GbxReaderWriter rw) { if (Version < 29) { - rw.Int32(ref materialCount); + materialCount = rw.Int32(n.customMaterials?.Length ?? 0); } if (Version >= 30) diff --git a/Src/GBX.NET/Engines/Plug/CPlugSpawnModel.chunkl b/Src/GBX.NET/Engines/Plug/CPlugSpawnModel.chunkl new file mode 100644 index 000000000..8f386f4ae --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/CPlugSpawnModel.chunkl @@ -0,0 +1,9 @@ +CPlugSpawnModel 0x0917A000 + +0x000 + version + iso4 Loc + float TorqueX + timeint TorqueDuration + vec3 DefaultGravitySpawn + int \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Plug/CPlugSurface.cs b/Src/GBX.NET/Engines/Plug/CPlugSurface.cs index f3f6cf322..424480f86 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugSurface.cs +++ b/Src/GBX.NET/Engines/Plug/CPlugSurface.cs @@ -10,6 +10,11 @@ public partial class CPlugSurface private CPlugSkel? skel; public CPlugSkel? Skel { get => skel; set => skel = value; } + private SurfMaterial[] materials = []; + [AppliedWithChunk] + [AppliedWithChunk] + public SurfMaterial[] Materials { get => materials; set => materials = value; } + public partial class Chunk0900C003 : IVersionable { public int Version { get; set; } @@ -18,6 +23,7 @@ public partial class Chunk0900C003 : IVersionable public ushort[]? U02; public float? U03; public ushort[]? U04; + public int? U05; public override void ReadWrite(CPlugSurface n, GbxReaderWriter rw) { @@ -40,6 +46,11 @@ public override void ReadWrite(CPlugSurface n, GbxReaderWriter rw) rw.ArrayReadableWritable(ref n.materials); // ArchiveMaterials + if (Version >= 4 && n.materials?.Length > 0) + { + rw.Int32(ref U05); + } + if ((Version == 3 && (n.materials is null || n.materials.Length == 0)) || Version >= 4) { rw.Array(ref U02); @@ -49,10 +60,6 @@ public override void ReadWrite(CPlugSurface n, GbxReaderWriter rw) { rw.Data(ref U01); // length matches materials count } - else - { - rw.Array(ref U04); // length matches materials count - } if (Version >= 1) { @@ -234,16 +241,47 @@ public void Write(GbxWriter w, int version = 0) public sealed partial class Compound : ISurf, IVersionable { public int Version { get; set; } + public ISurf[] Surfs { get; set; } = []; + public Iso4[] SurfLocs { get; set; } = []; + public short[] SurfJoints { get; set; } = []; public Vec3? U01 { get; set; } public void Read(GbxReader r, int version = 0) { - throw new NotImplementedException(); + var surfCount = r.ReadInt32(); + Surfs = new ISurf[surfCount]; + + for (var i = 0; i < surfCount; i++) + { + Surfs[i] = ReadSurf(r, version); + } + + SurfLocs = r.ReadArray(surfCount); + + if (version >= 1) + { + SurfJoints = r.ReadArray(); + } } public void Write(GbxWriter w, int version = 0) { - throw new NotImplementedException(); + w.Write(Surfs.Length); + + foreach (var surf in Surfs) + { + WriteSurf(surf, w, version); + } + + foreach (var surfLoc in SurfLocs) + { + w.Write(surfLoc); + } + + if (version >= 1) + { + w.WriteArray(SurfJoints); + } } } } diff --git a/Src/GBX.NET/Engines/Plug/CPlugTree.cs b/Src/GBX.NET/Engines/Plug/CPlugTree.cs index 2cf82e9a2..0001786a5 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugTree.cs +++ b/Src/GBX.NET/Engines/Plug/CPlugTree.cs @@ -34,7 +34,7 @@ static IEnumerable GetAllChildren(CPlugTree tree, bool includeVisualM { foreach (var level in mip.Levels) { - foreach (var descendant in GetAllChildren(level.Value, includeVisualMipLevels)) + foreach (var descendant in GetAllChildren(level.Tree, includeVisualMipLevels)) { yield return descendant; } @@ -122,12 +122,12 @@ static Iso4 MultiplyAddIso4(Iso4 a, Iso4 b) static CPlugTree GetLodTree(CPlugTreeVisualMip mip, int lod) { return mip.Levels - .OrderBy(x => x.Key) - .Select(x => x.Value) + .OrderBy(x => x.FarZ) + .Select(x => x.Tree) .ElementAtOrDefault(lod) ?? mip.Levels - .OrderBy(x => x.Key) + .OrderBy(x => x.FarZ) .First() - .Value; + .Tree; } } diff --git a/Src/GBX.NET/Engines/Plug/CPlugTreeVisualMip.cs b/Src/GBX.NET/Engines/Plug/CPlugTreeVisualMip.cs index 413cc793c..efdc57e27 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugTreeVisualMip.cs +++ b/Src/GBX.NET/Engines/Plug/CPlugTreeVisualMip.cs @@ -3,7 +3,9 @@ namespace GBX.NET.Engines.Plug; public partial class CPlugTreeVisualMip { - public IDictionary Levels { get; set; } = new Dictionary(); + private IList levels = new List(); + [AppliedWithChunk] + public IList Levels { get => levels; set => levels = value; } public partial class Chunk09015002 { @@ -15,9 +17,9 @@ public override void Read(CPlugTreeVisualMip n, GbxReader r) for (var i = 0; i < length; i++) { - var key = r.ReadSingle(); - var value = r.ReadNodeRef()!; - n.Levels.Add(key, value); + var farZ = r.ReadSingle(); + var tree = r.ReadNodeRef()!; + n.Levels.Add(new(farZ, tree)); } } @@ -27,9 +29,11 @@ public override void Write(CPlugTreeVisualMip n, GbxWriter w) foreach (var pair in n.Levels) { - w.Write(pair.Key); - w.WriteNodeRef(pair.Value); + w.Write(pair.FarZ); + w.WriteNodeRef(pair.Tree); } } } + + public sealed record Level(float FarZ, CPlugTree Tree); } diff --git a/Src/GBX.NET/Engines/Plug/CPlugVehicleCameraInternalModel.chunkl b/Src/GBX.NET/Engines/Plug/CPlugVehicleCameraInternalModel.chunkl index a56bc0d96..b1bb1cf2f 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugVehicleCameraInternalModel.chunkl +++ b/Src/GBX.NET/Engines/Plug/CPlugVehicleCameraInternalModel.chunkl @@ -7,8 +7,8 @@ CPlugVehicleCameraInternalModel 0x090F7000 v2+ vec3 RelativePos float? Fov - v2- - vec3 U01 // U01 = RelativePos in v3+ + v3+ + vec3 U01 // U01 = RelativePos in v2- v4+ bool IsFirstPerson vec3 PitchYawRoll diff --git a/Src/GBX.NET/Engines/Plug/CPlugVehicleCarPhyTuning.chunkl b/Src/GBX.NET/Engines/Plug/CPlugVehicleCarPhyTuning.chunkl index be1ac2878..6a84fe879 100644 --- a/Src/GBX.NET/Engines/Plug/CPlugVehicleCarPhyTuning.chunkl +++ b/Src/GBX.NET/Engines/Plug/CPlugVehicleCarPhyTuning.chunkl @@ -528,11 +528,6 @@ CPlugVehicleCarPhyTuning 0x090ED000 v8- float float - v1+ - bool - v8- - float - float v4+ Keys (version: Version - 37) v5+ @@ -653,14 +648,14 @@ CPlugVehicleCarPhyTuning 0x090ED000 v4+ throw int - CPlugCamControlModel[] + CPlugCamControlModel[] (external) v1+ int - CPlugCamControlModel[] + CPlugCamControlModel[] (external) v2+ - CPlugCamControlModel + CPlugCamControlModel (external) v3+ - CPlugCamControlModel + CPlugCamControlModel (external) 0x094 version @@ -755,7 +750,7 @@ CPlugVehicleCarPhyTuning 0x090ED000 0x09A version - CPlugVehicleGearBox + CPlugVehicleGearBox (external) 0x09B version diff --git a/Src/GBX.NET/Engines/Plug/NPlugTrigger_SWaypoint.chunkl b/Src/GBX.NET/Engines/Plug/NPlugTrigger_SWaypoint.chunkl new file mode 100644 index 000000000..276238223 --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/NPlugTrigger_SWaypoint.chunkl @@ -0,0 +1,15 @@ +NPlugTrigger_SWaypoint 0x09178000 + +archive + version + int Type + CPlugSurface TriggerShape (external) + bool NoRespawn + +enum EGameItemWaypointType + Start + Finish + Checkpoint + None + StartFinish + Dispenser \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Plug/NPlugTrigger_SWaypoint.cs b/Src/GBX.NET/Engines/Plug/NPlugTrigger_SWaypoint.cs new file mode 100644 index 000000000..dd9d377ee --- /dev/null +++ b/Src/GBX.NET/Engines/Plug/NPlugTrigger_SWaypoint.cs @@ -0,0 +1,18 @@ +namespace GBX.NET.Engines.Plug; + +public partial class NPlugTrigger_SWaypoint : IVersionable +{ + public int Version { get; set; } + +#if NET8_0_OR_GREATER + static void IClass.Read(T node, GbxReaderWriter rw) + { + node.ReadWrite(rw); + } +#endif + + public override void ReadWrite(GbxReaderWriter rw) + { + ReadWrite(rw, v: 0); + } +} diff --git a/Src/GBX.NET/Engines/Scene/CScenePhyCharSpecialProperty.chunkl b/Src/GBX.NET/Engines/Scene/CScenePhyCharSpecialProperty.chunkl new file mode 100644 index 000000000..549cdc0ea --- /dev/null +++ b/Src/GBX.NET/Engines/Scene/CScenePhyCharSpecialProperty.chunkl @@ -0,0 +1,23 @@ +CScenePhyCharSpecialProperty 0x0A071000 + +0x000 + version = 2 + v3+ + throw + int + v1- + float + float + float + bool + int + float + int + float + v1+ + int + v2+ + float + float + float + float \ No newline at end of file diff --git a/Src/GBX.NET/Engines/Script/CScriptTraitsMetadata.chunkl b/Src/GBX.NET/Engines/Script/CScriptTraitsMetadata.chunkl index 1f279330e..a8ce730c1 100644 --- a/Src/GBX.NET/Engines/Script/CScriptTraitsMetadata.chunkl +++ b/Src/GBX.NET/Engines/Script/CScriptTraitsMetadata.chunkl @@ -1,3 +1,5 @@ CScriptTraitsMetadata 0x11002000 0x000 + +0x11001000 (base: 0x000) \ No newline at end of file diff --git a/Src/GBX.NET/Engines/System/CSystemConfig.chunkl b/Src/GBX.NET/Engines/System/CSystemConfig.chunkl index 19bb9e9bf..92a5137e5 100644 --- a/Src/GBX.NET/Engines/System/CSystemConfig.chunkl +++ b/Src/GBX.NET/Engines/System/CSystemConfig.chunkl @@ -18,7 +18,7 @@ CSystemConfig 0x0B005000 0x00B (skippable, base: 0x005) [TMF, MP3, MP4] base - int + int U04 0x020 (skippable) [TMF, MP3, MP4] bool IsSafeMode diff --git a/Src/GBX.NET/Exceptions/LzoNotDefinedException.cs b/Src/GBX.NET/Exceptions/LzoNotDefinedException.cs index 1917e4d81..10c0bbbce 100644 --- a/Src/GBX.NET/Exceptions/LzoNotDefinedException.cs +++ b/Src/GBX.NET/Exceptions/LzoNotDefinedException.cs @@ -3,7 +3,7 @@ [Serializable] public class LzoNotDefinedException : Exception { - public LzoNotDefinedException() : base("LZO compression is not defined. Include GBX.NET.LZO and set 'Gbx.LZO = new MiniLZO()' to fix this problem.") { } + public LzoNotDefinedException() : base("LZO compression is not defined. Include GBX.NET.LZO and set 'Gbx.LZO = new Lzo()' to fix this problem.") { } public LzoNotDefinedException(string message) : base(message) { } public LzoNotDefinedException(string message, Exception? innerException) : base(message, innerException) { } } \ No newline at end of file diff --git a/Src/GBX.NET/GBX.NET.csproj b/Src/GBX.NET/GBX.NET.csproj index d20fc7a72..f05d4c523 100644 --- a/Src/GBX.NET/GBX.NET.csproj +++ b/Src/GBX.NET/GBX.NET.csproj @@ -2,7 +2,7 @@ GBX.NET - 2.0.5 + 2.0.6 BigBang1112 General purpose library for Gbx files - data from Nadeo games like Trackmania or Shootmania. It supports high performance serialization and deserialization of 200+ Gbx classes. Copyright (c) 2024 Petr Pivoňka @@ -49,8 +49,8 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Src/GBX.NET/GameBox.cs b/Src/GBX.NET/GameBox.cs index 8b61c8af7..ba848415b 100644 --- a/Src/GBX.NET/GameBox.cs +++ b/Src/GBX.NET/GameBox.cs @@ -1,5 +1,9 @@ using GBX.NET.Components; +#if NET6_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; +#endif + namespace GBX.NET; /// @@ -10,4 +14,8 @@ public class GameBox(GbxHeader header, GbxBody body) : Gbx(header, body); /// /// Old name for . /// -public class GameBox(GbxHeader header, GbxBody body, T node) : Gbx(header, body, node) where T : notnull, CMwNod; \ No newline at end of file +public class GameBox< +#if NET6_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] +#endif + T>(GbxHeader header, GbxBody body, T node) : Gbx(header, body, node) where T : notnull, CMwNod; \ No newline at end of file diff --git a/Src/GBX.NET/Gbx.cs b/Src/GBX.NET/Gbx.cs index 985153d62..45e2b9e3e 100644 --- a/Src/GBX.NET/Gbx.cs +++ b/Src/GBX.NET/Gbx.cs @@ -3,6 +3,10 @@ using GBX.NET.Managers; using Microsoft.Extensions.Logging; +#if NET6_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; +#endif + namespace GBX.NET; public interface IGbx @@ -69,22 +73,58 @@ public interface IGbx : IGbx where T : CMwNod new T Node { get; } } +/// +/// Represents a Gbx, which can be either known ( is not null) or unknown ( is null). +/// public partial class Gbx : IGbx { + /// + /// Magic (intial binary letters) for Gbx files. + /// public const string Magic = "GBX"; + /// + /// File path where the Gbx was read from. This can be set externally. It is not used when saving the Gbx. + /// public string? FilePath { get; set; } - public GbxHeader Header { get; } + + /// + /// Header of the Gbx. + /// + public GbxHeader Header { get; init; } + + /// + /// Reference table of the Gbx. This is the Gbx has no external Gbx references (Gbx files or -related files, does not count here). + /// public GbxRefTable? RefTable { get; protected set; } - public GbxBody Body { get; } + + /// + /// Body of the Gbx. This only handles body metadata and raw data (in case this reading method was picked). + /// + public GbxBody Body { get; init; } + + /// + /// Settings used to read the Gbx. They are stored just for convenience, they don't affect writing when using or . + /// public GbxReadSettings ReadSettings { get; protected set; } - public CMwNod? Node { get; protected set; } + + /// + /// Main node of the Gbx. + /// + public CMwNod? Node { get; protected set; } public int? IdVersion { get; set; } public byte? PackDescVersion { get; set; } public int? DeprecVersion { get; set; } + + /// + /// Class ID remap mode used during serialization. + /// public ClassIdRemapMode ClassIdRemapMode { get; set; } + /// + /// Compression of the body part of the Gbx. This wraps of . + /// public GbxCompression BodyCompression { get => Header.Basic.CompressionOfBody; @@ -111,7 +151,6 @@ public override string ToString() public string? GetFileNameWithoutExtension() { - if (FilePath is null) return null; return GbxPath.GetFileNameWithoutExtension(FilePath); } @@ -204,6 +243,9 @@ public static async Task ParseAsync(Stream stream, GbxReadSettings settings public static async Task ParseAsync(string filePath, GbxReadSettings settings = default, CancellationToken cancellationToken = default) { +#if !NETSTANDARD2_0 + await +#endif using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); return await ParseAsync(fs, settings, cancellationToken); } @@ -259,6 +301,9 @@ public static Gbx Parse(string filePath, GbxReadSettings settings = default) public static async Task> ParseAsync(string filePath, GbxReadSettings settings = default, CancellationToken cancellationToken = default) where T : CMwNod, new() { +#if !NETSTANDARD2_0 + await +#endif using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); return await ParseAsync(fs, settings, cancellationToken); } @@ -513,12 +558,11 @@ public virtual void Save(string filePath, GbxWriteSettings settings = default) } /// - /// Compresses the body part of the Gbx file, also setting the header parameter so that the outputted Gbx file is compatible with the game. If the file is already detected compressed, the input is just copied over to the output. + /// Compresses the body part of the Gbx file, also setting the header parameter so that the outputted Gbx file is compatible with the game. Compression algorithm is determined from . If the file is already detected compressed, it is recompressed. /// /// Gbx stream to compress. /// Output Gbx stream in the compressed form. /// Cancellation token. - /// False if was already compressed, otherwise true. /// /// /// @@ -526,9 +570,9 @@ public virtual void Save(string filePath, GbxWriteSettings settings = default) /// /// [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async Task CompressAsync(Stream input, Stream output, CancellationToken cancellationToken = default) + public static async Task CompressAsync(Stream input, Stream output, CancellationToken cancellationToken = default) { - return await GbxCompressionUtils.CompressAsync(input, output, cancellationToken); + await GbxCompressionUtils.CompressAsync(input, output, cancellationToken); } /// @@ -537,10 +581,10 @@ public static async Task CompressAsync(Stream input, Stream output, Cancel /// /// /// - public static async Task CompressAsync(string inputFilePath, Stream output, CancellationToken cancellationToken = default) + public static async Task CompressAsync(string inputFilePath, Stream output, CancellationToken cancellationToken = default) { using var input = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); - return await CompressAsync(input, output, cancellationToken); + await CompressAsync(input, output, cancellationToken); } /// @@ -549,10 +593,10 @@ public static async Task CompressAsync(string inputFilePath, Stream output /// /// /// - public static async Task CompressAsync(Stream input, string outputFilePath, CancellationToken cancellationToken = default) + public static async Task CompressAsync(Stream input, string outputFilePath, CancellationToken cancellationToken = default) { using var output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - return await CompressAsync(input, output, cancellationToken); + await CompressAsync(input, output, cancellationToken); } /// @@ -561,11 +605,11 @@ public static async Task CompressAsync(Stream input, string outputFilePath /// /// /// - public static async Task CompressAsync(string inputFilePath, string outputFilePath, CancellationToken cancellationToken = default) + public static async Task CompressAsync(string inputFilePath, string outputFilePath, CancellationToken cancellationToken = default) { using var input = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - return await CompressAsync(input, output, cancellationToken: cancellationToken); + await CompressAsync(input, output, cancellationToken: cancellationToken); } /// @@ -574,10 +618,10 @@ public static async Task CompressAsync(string inputFilePath, string output /// /// /// - public static bool Compress(string inputFilePath, Stream output) + public static void Compress(string inputFilePath, Stream output) { using var input = File.OpenRead(inputFilePath); - return Compress(input, output); + Compress(input, output); } /// @@ -586,10 +630,10 @@ public static bool Compress(string inputFilePath, Stream output) /// /// /// - public static bool Compress(Stream input, string outputFilePath) + public static void Compress(Stream input, string outputFilePath) { using var output = File.Create(outputFilePath); - return Compress(input, output); + Compress(input, output); } /// @@ -598,107 +642,20 @@ public static bool Compress(Stream input, string outputFilePath) /// /// /// - public static bool Compress(string inputFilePath, string outputFilePath) + public static void Compress(string inputFilePath, string outputFilePath) { using var input = File.OpenRead(inputFilePath); using var output = File.Create(outputFilePath); - return Compress(input, output); + Compress(input, output); } /// - /// Decompresses the body part of the Gbx file, also setting the header parameter so that the outputted Gbx file is compatible with the game. If the file is already detected decompressed, the input is just copied over to the output. + /// Decompresses the body part of the Gbx file, also setting the header parameter so that the outputted Gbx file is compatible with the game. Decompression algorithm is determined from . If the file is already detected decompressed, the input is just copied over to the output. /// /// Gbx stream to decompress. /// Output Gbx stream in the decompressed form. /// The token to monitor for cancellation requests. - /// False if was already decompressed, otherwise true. - /// - /// - /// - /// - /// - /// - [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async Task DecompressAsync(Stream input, Stream output, CancellationToken cancellationToken = default) - { - return await GbxCompressionUtils.DecompressAsync(input, output, cancellationToken); - } - - /// - /// - /// - /// - /// - /// - public static async Task DecompressAsync(string inputFilePath, Stream output, CancellationToken cancellationToken = default) - { - using var input = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); - return await DecompressAsync(input, output, cancellationToken); - } - - /// - /// - /// - /// - /// - /// - public static async Task DecompressAsync(Stream input, string outputFilePath, CancellationToken cancellationToken = default) - { - using var output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - return await DecompressAsync(input, output, cancellationToken); - } - - /// - /// - /// - /// - /// - /// - public static async Task DecompressAsync(string inputFilePath, string outputFilePath, CancellationToken cancellationToken = default) - { - using var input = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); - using var output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - return await DecompressAsync(input, output, cancellationToken: cancellationToken); - } - - /// - /// - /// - /// - /// - /// - public static bool Decompress(string inputFilePath, Stream output) - { - using var input = File.OpenRead(inputFilePath); - return Decompress(input, output); - } - - /// - /// - /// - /// - /// - /// - public static bool Decompress(Stream input, string outputFilePath) - { - using var output = File.Create(outputFilePath); - return Decompress(input, output); - } - - /// - /// - /// - /// - /// - /// - public static bool Decompress(string inputFilePath, string outputFilePath) - { - using var input = File.OpenRead(inputFilePath); - using var output = File.Create(outputFilePath); - return Decompress(input, output); - } - /// /// /// @@ -706,9 +663,9 @@ public static bool Decompress(string inputFilePath, string outputFilePath) /// /// [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async Task RecompressAsync(Stream input, Stream output, CancellationToken cancellationToken = default) + public static async Task DecompressAsync(Stream input, Stream output, CancellationToken cancellationToken = default) { - return await GbxCompressionUtils.RecompressAsync(input, output, cancellationToken); + await GbxCompressionUtils.DecompressAsync(input, output, cancellationToken); } /// @@ -717,10 +674,10 @@ public static async Task RecompressAsync(Stream input, Stream ou /// /// /// - public static async Task RecompressAsync(string inputFilePath, Stream output, CancellationToken cancellationToken = default) + public static async Task DecompressAsync(string inputFilePath, Stream output, CancellationToken cancellationToken = default) { using var input = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); - return await RecompressAsync(input, output, cancellationToken); + await DecompressAsync(input, output, cancellationToken); } /// @@ -729,10 +686,10 @@ public static async Task RecompressAsync(string inputFilePath, S /// /// /// - public static async Task RecompressAsync(Stream input, string outputFilePath, CancellationToken cancellationToken = default) + public static async Task DecompressAsync(Stream input, string outputFilePath, CancellationToken cancellationToken = default) { using var output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - return await RecompressAsync(input, output, cancellationToken); + await DecompressAsync(input, output, cancellationToken); } /// @@ -741,11 +698,11 @@ public static async Task RecompressAsync(Stream input, string ou /// /// /// - public static async Task RecompressAsync(string inputFilePath, string outputFilePath, CancellationToken cancellationToken = default) + public static async Task DecompressAsync(string inputFilePath, string outputFilePath, CancellationToken cancellationToken = default) { using var input = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); using var output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); - return await RecompressAsync(input, output, cancellationToken: cancellationToken); + await DecompressAsync(input, output, cancellationToken); } /// @@ -754,10 +711,10 @@ public static async Task RecompressAsync(string inputFilePath, s /// /// /// - public static GbxCompression Recompress(string inputFilePath, Stream output) + public static void Decompress(string inputFilePath, Stream output) { using var input = File.OpenRead(inputFilePath); - return Recompress(input, output); + Decompress(input, output); } /// @@ -766,10 +723,10 @@ public static GbxCompression Recompress(string inputFilePath, Stream output) /// /// /// - public static GbxCompression Recompress(Stream input, string outputFilePath) + public static void Decompress(Stream input, string outputFilePath) { using var output = File.Create(outputFilePath); - return Recompress(input, output); + Decompress(input, output); } /// @@ -778,11 +735,11 @@ public static GbxCompression Recompress(Stream input, string outputFilePath) /// /// /// - public static GbxCompression Recompress(string inputFilePath, string outputFilePath) + public static void Decompress(string inputFilePath, string outputFilePath) { using var input = File.OpenRead(inputFilePath); using var output = File.Create(outputFilePath); - return Recompress(input, output); + Decompress(input, output); } /// @@ -866,26 +823,58 @@ public static uint ParseClassId(string filePath, bool remap = true) public static implicit operator CMwNod?(Gbx gbx) => gbx.Node; } -public class Gbx : Gbx, IGbx where T : CMwNod +/// +/// Represents a Gbx with a main node of type . +/// +/// Type of the main node. +public class Gbx< +#if NET6_0_OR_GREATER + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] +#endif + T> : Gbx, IGbx where T : CMwNod { + /// + /// Main typed node of the Gbx. + /// public new T Node => (T)(base.Node ?? throw new Exception("Null node is not expected here.")); - public new GbxHeader Header => (GbxHeader)base.Header; + + /// + /// Typed header of the Gbx. + /// + public new GbxHeader Header => (GbxHeader)base.Header; internal Gbx(GbxHeader header, GbxBody body, T node) : base(header, body) { base.Node = node ?? throw new ArgumentNullException(nameof(node)); } - public Gbx(T node, GbxHeaderBasic headerBasic) : this(new GbxHeader(headerBasic), new GbxBody(), node) + /// + /// Creates a new Gbx wrap of with and basic header parameters. + /// + /// Node. + /// Basic header parameters. + public Gbx(T node, GbxHeaderBasic headerBasic) : this(new GbxHeader(headerBasic), new GbxBody(), node) { } + /// + /// Creates a new Gbx wrap of with . + /// + /// Node. public Gbx(T node) : this(node, GbxHeaderBasic.Default) { } + /// + /// Creates a new Gbx with all defaults. This should be ONLY used for deserialization purposes. + /// + internal Gbx() : this(new GbxHeader(GbxHeaderBasic.Default), new(), Activator.CreateInstance()) + { + + } + public override string ToString() { return $"Gbx<{typeof(T).Name}> ({ClassManager.GetName(Header.ClassId)}, 0x{Header.ClassId:X8})"; diff --git a/Src/GBX.NET/GbxCompressionUtils.cs b/Src/GBX.NET/GbxCompressionUtils.cs index ac6f9ffe8..3d5619770 100644 --- a/Src/GBX.NET/GbxCompressionUtils.cs +++ b/Src/GBX.NET/GbxCompressionUtils.cs @@ -9,7 +9,7 @@ internal static partial class GbxCompressionUtils /// /// [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async Task CompressAsync(Stream input, Stream output, CancellationToken cancellationToken) + public static async Task CompressAsync(Stream input, Stream output, CancellationToken cancellationToken) { _ = input ?? throw new ArgumentNullException(nameof(input)); _ = output ?? throw new ArgumentNullException(nameof(output)); @@ -27,25 +27,30 @@ public static async Task CompressAsync(Stream input, Stream output, Cancel // Body compression type var compressedBody = r.ReadByte(); - if (compressedBody != 'U') - { - await input.CopyToAsync(output, bufferSize: 81920, cancellationToken); - - return false; - } + var isAlreadyCompressed = compressedBody != 'U'; w.Write('C'); await CopyRestOfTheHeaderAsync(version, r, w, cancellationToken); - var uncompressedData = await r.ReadToEndAsync(cancellationToken); + byte[] uncompressedData; + + if (isAlreadyCompressed) + { + var uncompressedSize = r.ReadInt32(); + uncompressedData = new byte[uncompressedSize]; + Gbx.LZO.Decompress(await r.ReadDataAsync(cancellationToken), uncompressedData); + } + else + { + uncompressedData = await r.ReadToEndAsync(cancellationToken); + } + var compressedData = Gbx.LZO.Compress(uncompressedData); w.Write(uncompressedData.Length); w.Write(compressedData.Length); await w.WriteAsync(compressedData, cancellationToken); - - return true; } /// @@ -55,7 +60,7 @@ public static async Task CompressAsync(Stream input, Stream output, Cancel /// /// [Zomp.SyncMethodGenerator.CreateSyncVersion] - public static async Task DecompressAsync(Stream input, Stream output, CancellationToken cancellationToken) + public static async Task DecompressAsync(Stream input, Stream output, CancellationToken cancellationToken) { _ = input ?? throw new ArgumentNullException(nameof(input)); _ = output ?? throw new ArgumentNullException(nameof(output)); @@ -77,8 +82,7 @@ public static async Task DecompressAsync(Stream input, Stream output, Canc { w.Write(compressedBody); await input.CopyToAsync(output, bufferSize: 81920, cancellationToken); - - return false; + return; } w.Write('U'); @@ -92,8 +96,6 @@ public static async Task DecompressAsync(Stream input, Stream output, Canc var buffer = new byte[uncompressedSize]; Gbx.LZO.Decompress(compressedData, buffer); await w.WriteAsync(buffer, cancellationToken); - - return true; } /// diff --git a/Src/GBX.NET/GbxPath.cs b/Src/GBX.NET/GbxPath.cs index e2fca9c86..0e2be7a66 100644 --- a/Src/GBX.NET/GbxPath.cs +++ b/Src/GBX.NET/GbxPath.cs @@ -1,8 +1,11 @@ -namespace GBX.NET; +using System.Diagnostics.CodeAnalysis; + +namespace GBX.NET; public static class GbxPath { - public static string GetFileNameWithoutExtension(string path) + [return: NotNullIfNotNull(nameof(path))] + public static string? GetFileNameWithoutExtension(string? path) { return Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(path)); } diff --git a/Src/GBX.NET/GbxReadSettings.cs b/Src/GBX.NET/GbxReadSettings.cs index b130579a1..aac95021e 100644 --- a/Src/GBX.NET/GbxReadSettings.cs +++ b/Src/GBX.NET/GbxReadSettings.cs @@ -31,4 +31,9 @@ public readonly record struct GbxReadSettings public bool OpenPlanetHookExtractMode { get; init; } public HashSet? SkipChunkIds { get; init; } + + /// + /// Skippable chunks will be read less efficiently, but they will be ignored if the read will fail, with (usually) no corruption once saved. + /// + public bool SafeSkippableChunks { get; init; } } \ No newline at end of file diff --git a/Src/GBX.NET/Interfaces/Game/IGameCtnChallengeMP4.cs b/Src/GBX.NET/Interfaces/Game/IGameCtnChallengeMP4.cs index 467379618..05ff103ed 100644 --- a/Src/GBX.NET/Interfaces/Game/IGameCtnChallengeMP4.cs +++ b/Src/GBX.NET/Interfaces/Game/IGameCtnChallengeMP4.cs @@ -4,7 +4,7 @@ namespace GBX.NET.Interfaces.Game; public interface IGameCtnChallengeMP4 : IGameCtnChallenge { - IEnumerable GetBlocks(bool includeUnassigned1 = true); + IEnumerable GetBlocks(); IEnumerable GetBakedBlocks(); ZipArchive OpenReadEmbeddedZipData(); void UpdateEmbeddedZipData(Action update); diff --git a/Src/GBX.NET/README.md b/Src/GBX.NET/README.md index 9504e29c3..80135d596 100644 --- a/Src/GBX.NET/README.md +++ b/Src/GBX.NET/README.md @@ -30,7 +30,7 @@ using GBX.NET; using GBX.NET.Engines.Game; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var map = Gbx.ParseNode("Path/To/My.Map.Gbx"); @@ -62,7 +62,7 @@ using GBX.NET; using GBX.NET.Engines.Game; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var gbx = Gbx.Parse("Path/To/My.Map.Gbx"); var map = gbx.Node; // See Clarity section for more info @@ -106,7 +106,7 @@ using GBX.NET; using GBX.NET.Engines.Game; using GBX.NET.LZO; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var node = Gbx.ParseNode("Path/To/My.Gbx"); diff --git a/Src/GBX.NET/Serialization/GbxBodyReader.cs b/Src/GBX.NET/Serialization/GbxBodyReader.cs index 32ed617f0..d260cba71 100644 --- a/Src/GBX.NET/Serialization/GbxBodyReader.cs +++ b/Src/GBX.NET/Serialization/GbxBodyReader.cs @@ -144,7 +144,11 @@ public async Task ParseAsync(T node, CancellationToken cancellationT var decompressedData = await DecompressDataAsync(body.CompressedSize.Value, body.UncompressedSize, cancellationToken); +#if NETSTANDARD2_0 using var ms = new MemoryStream(decompressedData); +#else + await using var ms = new MemoryStream(decompressedData); +#endif using var decompressedReader = new GbxReader(ms, Settings); decompressedReader.LoadFrom(reader); using var decompressedReaderWriter = new GbxReaderWriter(decompressedReader); diff --git a/Src/GBX.NET/Serialization/GbxWriter.cs b/Src/GBX.NET/Serialization/GbxWriter.cs index ef273b692..51fa45203 100644 --- a/Src/GBX.NET/Serialization/GbxWriter.cs +++ b/Src/GBX.NET/Serialization/GbxWriter.cs @@ -861,7 +861,7 @@ public void WriteSmallString(string? value) return; } - WriteSmallLen(value.Length); + WriteSmallLen(encoding.GetByteCount(value)); Write(value, StringLengthPrefix.None); } diff --git a/Tests/GBX.NET.Tests/Files/Gbx/CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx b/Tests/GBX.NET.Tests/Files/Gbx/CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx new file mode 100644 index 000000000..b2124842f Binary files /dev/null and b/Tests/GBX.NET.Tests/Files/Gbx/CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx differ diff --git a/Tests/GBX.NET.Tests/GBX.NET.Tests.csproj b/Tests/GBX.NET.Tests/GBX.NET.Tests.csproj index dc287959c..8efa941ce 100644 --- a/Tests/GBX.NET.Tests/GBX.NET.Tests.csproj +++ b/Tests/GBX.NET.Tests/GBX.NET.Tests.csproj @@ -18,11 +18,11 @@ - + - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/Tests/GBX.NET.Tests/Integration/GbxEqualTests.cs b/Tests/GBX.NET.Tests/Integration/GbxEqualTests.cs index c2b76726f..1addfa123 100644 --- a/Tests/GBX.NET.Tests/Integration/GbxEqualTests.cs +++ b/Tests/GBX.NET.Tests/Integration/GbxEqualTests.cs @@ -17,7 +17,7 @@ public GbxEqualTests(ITestOutputHelper output) { this.output = output; - Gbx.LZO = new MiniLZO(); + Gbx.LZO = new Lzo(); Gbx.StrictBooleans = true; } @@ -34,6 +34,7 @@ public GbxEqualTests(ITestOutputHelper output) [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMNESWC 001.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 001.Challenge.Gbx")] + [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge MP3 001.Map.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMT 001.Map.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge MP4 001.Map.Gbx")] @@ -96,6 +97,7 @@ public void TestGbxEqualDataImplicit(string filePath) [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMNESWC 001.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 001.Challenge.Gbx")] + [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge MP3 001.Map.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMT 001.Map.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge MP4 001.Map.Gbx")] @@ -162,6 +164,7 @@ public void TestGbxEqualObjectsImplicit(string filePath) [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMNESWC 001.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 001.Challenge.Gbx")] + [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge MP3 001.Map.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMT 001.Map.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge MP4 001.Map.Gbx")] @@ -223,6 +226,7 @@ public async Task TestGbxEqualDataImplicitAsync(string filePath) [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMNESWC 001.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 001.Challenge.Gbx")] + [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge MP3 001.Map.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge TMT 001.Map.Gbx")] [InlineData("CGameCtnChallenge/GBX-NET 2 CGameCtnChallenge MP4 001.Map.Gbx")] @@ -289,6 +293,7 @@ public async Task TestGbxEqualObjectsImplicitAsync(string filePath) [InlineData("GBX-NET 2 CGameCtnChallenge TMNESWC 001.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMF 001.Challenge.Gbx")] + [InlineData("GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge MP3 001.Map.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMT 001.Map.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge MP4 001.Map.Gbx")] @@ -402,6 +407,7 @@ public void TestGbxEqualDataExplicitCGameCtnGhost(string filePath) [InlineData("GBX-NET 2 CGameCtnChallenge TMNESWC 001.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMF 001.Challenge.Gbx")] + [InlineData("GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge MP3 001.Map.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMT 001.Map.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge MP4 001.Map.Gbx")] @@ -515,6 +521,7 @@ public void TestGbxEqualObjectsExplicitCGameCtnGhost(string filePath) [InlineData("GBX-NET 2 CGameCtnChallenge TMNESWC 001.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMF 001.Challenge.Gbx")] + [InlineData("GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge MP3 001.Map.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMT 001.Map.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge MP4 001.Map.Gbx")] @@ -628,6 +635,7 @@ public async Task TestGbxEqualDataExplicitCGameCtnGhostAsync(string filePath) [InlineData("GBX-NET 2 CGameCtnChallenge TMNESWC 001.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMU 001.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMF 001.Challenge.Gbx")] + [InlineData("GBX-NET 2 CGameCtnChallenge TMF 002.Challenge.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge MP3 001.Map.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge TMT 001.Map.Gbx")] [InlineData("GBX-NET 2 CGameCtnChallenge MP4 001.Map.Gbx")] diff --git a/Tools/BulkParseTest/Program.cs b/Tools/BulkParseTest/Program.cs index f7ac126bb..ed2498e8f 100644 --- a/Tools/BulkParseTest/Program.cs +++ b/Tools/BulkParseTest/Program.cs @@ -11,7 +11,7 @@ var dirPath = args[0]; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var existingExceptions = new HashSet(); var counter = 0; diff --git a/Tools/ClassIdTxtFromGbxClassInfo/GbxClassInfo/Trackmania2020.txt b/Tools/ClassIdTxtFromGbxClassInfo/GbxClassInfo/Trackmania2020.txt index 92e378f87..af778f15d 100644 --- a/Tools/ClassIdTxtFromGbxClassInfo/GbxClassInfo/Trackmania2020.txt +++ b/Tools/ClassIdTxtFromGbxClassInfo/GbxClassInfo/Trackmania2020.txt @@ -496,7 +496,6 @@ 0321A000 CGamePlaygroundModuleServerInventory 0321B000 CGamePlaygroundModuleServerScoresTable 0321C000 CWebServicesTaskResult_RealLeaderBoardInfoList -0321D000 CGameRealLeaderBoardInfoScript 0321E000 CGameScoreTask_GetRealLeaderBoardPlayerList 0321F000 CWebServicesTaskResult_Ghost 03220000 CGameScoreTask_GetPlayerMapRecordGhost @@ -611,9 +610,6 @@ 032B5000 CGameMasterServerTask_SetTitlePaid 032B6000 CGameScoreTask_GetNaturalLeaderBoardPlayerList 032B7000 CGameCtnMasterServerTask_GetNaturalLeaderBoard -032B8000 CGameNaturalLeaderBoardInfoScript -032B9000 CWebServicesTaskResult_NaturalLeaderBoardInfoListScript -032BA000 CWebServicesTaskResult_RealLeaderBoardInfoListScript 032BB000 CGameMatchSettingsManagerScript 032BC000 CGameMatchSettingsScript 032BD000 CGameDataFileTask_PackDownloadOrUpdate @@ -704,7 +700,6 @@ 0331C000 CWebServicesTaskResult_UserZoneListScript 0331E000 CGameScoreTask_GetCampaignRanking 0331F000 CGameScoreTask_GetMapRanking -03320000 CWebServicesTaskResult_PlayerRanking 03321000 CWebServicesTaskResult_AccountTrophyGainHistory 03322000 CGameMasterServerTask_GetPlayerCreditedPackagesGroups 03323000 CWebServicesTask_GetPlayerCreditedPackagesGroups @@ -735,7 +730,6 @@ 0333C000 CGameSeasonScoreManager_MultiAsyncLevel 0333D000 CGameScoreTask_AddMapListToSeason 0333E000 CGameScoreTask_RemoveMapListToSeason -0333F000 CGameScoreTask_GetPlayerListMapRecordList 03340000 CGameCtnBlockInfoClipVertical 03341000 CGameGhostMgrScript 03346000 CGameBlockInfoGroups @@ -1762,9 +1756,11 @@ 12215000 CWebServicesTask_Party_SetLocked 12216000 CNetUbiServicesTask_Profile_RetrieveProfileInfoListFromPlatform 12217000 CWebServicesTask_GetWebServicesUserIdFromWebIdentity -12220000 CNetNadeoServicesTask_AddSubscriptionDeprecated +12220000 CNetNadeoServicesTask_GetMapRecordList 12221000 CNetNadeoServicesTask_AddClientDebugInfo 12223000 CWebServicesTask_Preference_RetrieveUserPreference +12224000 CWebServicesTask_Event_AddMapSession +12225000 CNetNadeoServicesTask_AddTelemetryMapSession 12228000 CNetNadeoServicesTask_Activity_CreateMatch 12229000 CNetNadeoServicesTask_Activity_ReportMatchResult 1222A000 CWebServicesTaskResult_WSMapRecordList @@ -2063,330 +2059,330 @@ 30004000 ISceneVis 30005000 IScenePhy 30006000 NSceneWeather_SMgr -30007000 NGameLoadProgress_SMgr -30008000 NGameScriptChat_SManager -30009000 NGameHud3d_SMgr -3000A000 NGameMenuSkinChooser_SMgr -3000B000 CWebServicesTaskResult_GhostDriver_UploadLimits -3000C000 CWebServicesTaskResult_GhostDriver_Download -3000D000 NPlugMaterial_SWater -3000E000 NGameCollection_SCustomizableDeco -3000F000 CNotification -30010000 CNotification_Prestige -30011000 CNotification_Squad -30012000 CNotification_PrestigeEarned -30013000 CNotification_SquadDeleted -30014000 CNotification_SquadInvitationAccepted -30015000 CNotification_SquadInvitationAdded -30016000 CNotification_SquadInvitationCanceled -30017000 CNotification_SquadInvitationCanceledForExitingPlayer -30018000 CNotification_SquadInvitationCanceledForFullSquad -30019000 CNotification_SquadInvitationDeclined -3001A000 CNotification_SquadInvitationReceived -3001B000 CNotification_SquadLockStateUpdated -3001C000 CNotification_SquadMemberAdded -3001D000 CNotification_SquadMemberKicked -3001E000 CNotification_SquadMemberRemoved -3001F000 CNotification_SquadUpdated -30020000 CSeasonMapInfo -30021000 CSeason -30022000 CAccountTrophyGain -30023000 CAccountTrophyGainForHistory -30024000 CAccountTrophyGainForHistory_CompetitionMatch -30025000 CAccountTrophyGainForHistory_CompetitionRanking -30026000 CAccountTrophyGainForHistory_LiveMatch -30027000 CAccountTrophyGainForHistory_SoloMedal -30028000 CAccountTrophyGainForHistory_SoloRanking -30029000 CAccountTrophyLastYearSummary -3002A000 CTrophyAchievement -3002B000 CTrophyAchievement_CompetitionMatch -3002C000 CTrophyAchievement_CompetitionRanking -3002D000 CTrophyAchievement_LiveMatch -3002E000 CTrophyAchievement_SoloMedal -3002F000 CTrophyAchievement_SoloRanking -30030000 CTrophySoloMedalAchievementLevelSettings -30031000 CTrophySoloMedalAchievementSettings -30032000 CMapRecord -30033000 NGameScriptChat_SContext -30034000 NGameScriptChat_SHistory -30035000 NGameScriptChat_SEntry -30036000 NGameScriptChat_SEvent -30037000 NGameScriptChat_SEvent_HistoryChange -30038000 NGameScriptChat_SEvent_NewEntry -30039000 CGameDirectLinkScript -3003A000 CGameDirectLinkScript_Home -3003B000 CGameDirectLinkScript_NewMap -3003C000 CGameDirectLinkScript_OfficialCampaign -3003D000 CGameDirectLinkScript_JoinServer -3003E000 CGameDirectLinkScript_TrackOfTheDay -3003F000 CGameDirectLinkScript_Ranked -30040000 CGameDirectLinkScript_Royal -30041000 CGameDirectLinkScript_ArcadeServer -30042000 CGameDirectLinkScript_Hotseat -30043000 CGameDirectLinkScript_Splitscreen -30044000 CGameDirectLinkScript_Garage -30045000 CGameDirectLinkScript_WaitingPage -30046000 CGameDirectLinkScript_JoinSession -30047000 CGameUserManagerScript_VoiceChatEvent -30048000 CGameUserManagerScript_VoiceChatEvent_UserChange_IsSpeaking -30049000 CGameUserManagerScript_VoiceChatEvent_UserChange_IsConnected -3004A000 CGameUserManagerScript_VoiceChatEvent_UserChange_IsMuted -3004B000 CGameUserManagerScript_VoiceChatEvent_SpeakingHasChanged -3004C000 CGameUserManagerScript_VoiceChatEvent_Message -3004D000 CGameUserManagerScript_VoiceChatEvent_DisplayUI -3004E000 NGameEditorMap_SExperimentalFeatures -3004F000 NPlugItemPlacement_STag -30050000 CAdvertisingManager -30051000 NGameMiniMap_SMgr -30052000 CGameVoiceChatConfigScript -30053000 CGameDataFileTask_GhostDriver -30054000 CGameDataFileTask_GhostDriver_UploadLimits -30055000 CGameDataFileTask_GhostDriver_Upload -30056000 CGameDataFileTask_GhostDriver_Download -30057000 CFriend -30058000 CSkinInfo -30059000 CSquadInvitation -3005A000 CSquadMember -3005B000 CSquad -3005C000 CNewsLink -3005D000 CNews -3005E000 CPrestige -3005F000 CUserPrestige -30060000 CGameCtnMenuProfileScene -30061000 CNadeoServicesMap -30062000 CNadeoServicesItemCollection -30063000 CNadeoServicesSkin -30064000 CZone -30065000 CNadeoServicesItemCollectionVersion -30066000 NSmArenaInterface_SMgr -30067000 NPlugCurve_SSimpleCurveInPlace7 -30068000 NSceneTransitoryBlockingSurfs_SMgr -30069000 NSceneLightMapCloud_SServer -3006A000 NSceneLightMapCloud_SClient -3006B000 NScenePicking_SMgr -3006C000 NSceneGateSpecial_SMgr -3006D000 NSceneTimeshift_SMgr -3006E000 NSceneRecorder_SMgr -3006F000 NSmArenaPhysics_SMgr -30070000 NSmPlayerVis_SMgr -30071000 NSmPlayerPhy_SMgr -30072000 NSmArenaVis_SMgr -30073000 NGameConstraintPhy_SMgr -30074000 NGameObjectPhy_SMgr -30075000 NGameArenaState_SMgr -30076000 NGameArenaVis_SMgr -30077000 NGamePrefab_SMgr -30078000 NGamePrefab_SInst -30079000 NGamePrefab_SGridEntSpawner -3007A000 NGamePrefabPhy_SMgr -3007B000 NGamePrefabPhy_SInst -3007C000 NSceneKinematicVis_SMgr -3007D000 NSceneKinematicVis_SConstraint -3007E000 NGameActionFxVis_SMgr -3007F000 NGameShieldVis_SMgr -30080000 NGameShieldPhy_SMgr -30081000 NGameGateVis_SMgr -30082000 NGameGatePhy_SMgr -30083000 NGameWaypoint_SMgr -30084000 NGameWaypoint_SSpawn -30085000 NGameItem_SMgr -30086000 NGameMediaClip_SMgr -30087000 NGameSlotVis_SMgr -30088000 NGameSlotPhy_SMgr -30089000 NGameVehiclePhy_SMgr -3008A000 NGameTurretVis_SMgr -3008B000 NGameTurretPhy_SMgr -3008C000 NGameObjectVis_SMgr -3008D000 NGamePodiumVis_SMgr -3008E000 NGamePodium_SMgr -3008F000 NGamePodium_SPodium -30090000 NGameCamera_SMgr -30091000 NGameMapPhy_SMgr -30092000 NGameMgrMap_SMgr -30093000 NGameGhostClips_SMgr -30094000 NGameGhost_SMgr -30095000 NSceneItemPlacement_SMgr -30096000 NSceneItemPlacement_SZone -30097000 NSceneBulletPhy_SMgr -30098000 NSceneDestructiblePhy_SMgr -30099000 SSceneDestructibleDynaPhy -3009A000 SSceneDestructiblePhy -3009B000 -3009C000 NSceneDyna_SMgr -3009D000 NSceneDyna_SKinematicConstraint -3009F000 NSceneAdvert_SMgr -300A0000 NSceneMapColoring_SMgr -300A1000 NSceneModelKit_SMgr -300A2000 NSceneProp_SMgrPhy -300A3000 NSceneProp_SProp -300A4000 NSceneProp_SMgrVis -300A5000 NSceneConstruction_SMgrPhy -300A6000 NSceneConstruction_SConstruction -300A7000 NSceneConstruction_SMgrVis -300A8000 NSceneRopeVis_SMgr -300A9000 NSceneRopePhy_SMgr -300AA000 SSceneRopePhyEnt -300AB000 NSceneEditorHelper_SMgr -300AC000 NSceneEditorHelper_SHelper -300AD000 NSceneFlock_SMgr -300AF000 NSceneAnim_SMgr -300B0000 NSceneSolid2Vis_SMgr -300B1000 NSceneSound_SMgr -300B2000 NSceneSound_SSource -300B3000 NSceneSpectatorVis_SMgr -300B4000 NSceneParticleVis_SMgr -300B5000 NSceneCitizenNetwork_SMgr -300B6000 NSceneCitizenNetwork_SChunk -300B7000 NSceneRoad_SMgr -300B8000 NSceneRoad_SChunk -300B9000 NSceneRail_SMgr -300BA000 NSceneBulletVis_SMgr -300BB000 NSceneFxSystem_SMgr -300BC000 NSceneFxSystem_SFxSystemInstance -300BD000 NSceneWind_SMgrPhy -300BE000 NSceneTrainVis_SMgr -300BF000 NSceneTrainPhy_SMgr -300C0000 NSceneCharVis_SMgr -300C1000 NSceneVehicleVis_SMgr -300C2000 NSceneLight_SMgr -300C3000 NScenePathFinding_SMgr -300C4000 NSceneTrafficVis_SMgr -300C6000 NSceneTrafficPhy_SMgr -300C7000 NSceneVFX_SMgr -300C8000 NSceneVFX_SVFXInstance -300C9000 NSceneEdEntWrapper_SMgr -300CA000 NSceneEdEntWrapper_SWrapper -300CB000 NHmsForestVis_SMgr -300CC000 NHmsForestVis_STree -300CD000 NHmsMgrInstDyna2_SMgr -300CE000 SHmsLodGroup -300CF000 SHmsInstDyna -300D0000 SHmsMeshStatic -300D1000 NHmsZone_SMgrLightDynamic -300D2000 NHmsZone_SLightDyna -300D4000 NHmsCollision_SMgr -300D5000 NHmsCollision_SItem -300D6000 NScenePicking_SPickable -300D7000 GmTransQuat -300D8000 NPlugPainterLayer_SElem -300D9000 NPlugPainterLayer_SLayerVFX -300DA000 NPlugPainterLayer_SLayerDraw -300DB000 NPlugPainterLayer_SBitmapGroup -300DC000 NPlugAnim_SSkelPose -300DD000 NPlugAnim_SIKSkelPoseN -300DE000 NPlugAnim_SIKChainPoseN -300DF000 NPlugAnim_SIKChainPose -300E0000 NPlugAnim_SIKSkelMappingCache -300E1000 NPlugAnim_SIKChainMappingCache -300E2000 NPlugAnim_SIKSkelMapping -300E3000 NPlugAnim_SIKChainMapping -300E4000 NPlugAnim_SIKSkel -300E5000 SMetaPtr -300E6000 NHmsMgrVolume_SFogSimuParameters -300E7000 NFuncShaderLayerUV_STransSubTextureIn -300E8000 TSceneUId -300E9000 NGameAdvert_Simu_SMgr -300EA000 NGameAdvert_Anzu_SMgr -300EB000 Nat256 -300EC000 NGameAdvert_Test_SMgr -300ED000 EditorMeshPickingIdentifier -300EE000 NGamePrefab_SInstanceCreateParams -300EF000 NGamePrefab_SSceneEntListElem -300F0000 NGamePrefab_SGridParams -300F1000 NFastBlockAlloc_SAllocator -300F2000 NGamePrefabPhy_SSceneEntListElem -300F3000 NGamePrefabPhy_SInstanceCreateParams -300F4000 NSceneKinematicVis_SSharedSignal -300F5000 SWebServicesTaskResult_GhostDriver_UploadLimit -300F6000 SWebServicesTaskResult_GhostDriver_Download_Team -300F7000 SWebServicesTaskResult_GhostDriver_Download_Member -300F8000 SWebServicesTaskResult_GhostDriver_Download_Ghost -300F9000 NGamePodiumVis_SConfig -300FA000 NGamePodiumVis_SSequence -300FB000 SGameHud3dParams -300FC000 NGameMenuSkinChooser_SDispParams -300FD000 NGameCamera_SCamSys -300FE000 NGameScriptDebugger_SDebuggerMgr -300FF000 NGameScriptDebugger_SWatchedVariable -30100000 NGameScriptDebugger_SWatchedVariableV2 -30101000 NGameVideoSource_SMgr -30102000 CAdvertisingSlot -30103000 NGameAdvert_Live_SMgr -30104000 NGameAdvert_Live_SAdsManager -30105000 NGameAdvert_Live_SAdSlotInternal -30106000 NGameAdvert_Live_SImpressionParams -30107000 NChatLog_SChatHistory -30108000 NChatLog_SChatMsg -30109000 NFastBucketAlloc_SAllocator -3010A000 NGameMgrMap_SMapInst -3010B000 NGameIconShooter_SSceneSetting -3010C000 NGameIconShooter_SCameraSetting -3010D000 CGameCtnMediaBlockGhostTM_SuperSKeyVal -3010E000 NGameMediaBlockEntity_SuperSKeyVal -3010F000 CGameCtnMediaBlockOpponentVisibility_SuperSKeyVal -30110000 CGameCtnMediaBlockDirtyLens_SKeyVal -30111000 CGameCtnMediaBlockCameraEffectScript_SKeyVal -30112000 CGameCtnMediaBlockVehicleLight_SuperSKeyVal -30113000 CGameCtnMediaBlockFog_SKeyVal -30114000 CGameCtnMediaBlockTimeSpeed_SKeyVal -30115000 CGameCtnMediaBlockBloomHdr_SKeyVal -30116000 CGameCtnMediaBlockToneMapping_SKeyVal -30117000 CGameCtnMediaBlockDOF_SKeyVal -30118000 CGameCtnMediaBlock3dStereo_SKeyVal -30119000 CGameCtnMediaBlockTransitionFade_SuperSKeyVal -3011A000 CGameCtnMediaBlockColorGrading_SuperSKeyVal -3011B000 CGameCtnMediaBlockText_SuperSKeyVal -3011C000 CGameCtnMediaBlockSpectators_SKeyVal -3011D000 CGameCtnMediaBlockSound_SuperSKeyVal -3011E000 CGameCtnMediaBlockMusicEffect_SKeyVal -3011F000 CGameCtnMediaBlockImage_SuperSKeyVal -30120000 CGameCtnMediaBlockCameraEffectShake_SKeyVal -30121000 CGameCtnMediaBlockCameraCustom_SKeyVal -30122000 CGameCtnMediaBlockCameraPath_SKeyVal -30123000 CGameCtnMediaBlockCameraOrbital_SKeyVal -30124000 CGameCtnMediaBlockTime_SKeyVal -30125000 CGameCtnMediaBlockFxCameraBlend_SKeyVal -30126000 CGameCtnMediaBlockFxColors_SKeyVal -30127000 SGameItemModelTree -30128000 SGameBlockInfoTree -30129000 SGameBlockInfoGroup -3012A000 NPlugSkin_SCustomizableBitmap -3012B000 NGameGhostClips_SClipPlayerGhost -3012C000 NGameMapItemPlacement_SMapData -3012D000 NGameMapItemPlacement_SZone -3012E000 NGameMapItemPlacement_SZoneId -3012F000 SGameCtnIdentifier -30130000 GmTransYawPitchRollDeg -30131000 NHmsLightMap_SCptBackgnd -30132000 CVisionVideoDecode -30133000 NSysCfgVision_SSubsurfaceScattering -30134000 CVisionHmsZone -30135000 NVisionHmsZone_SWaterPlaneVisibility -30136000 NVis_SBenchShader -30137000 NFilmicTone_PowerSegments_SCurveParamsUser -30138000 NSysCfgVision_SVisionImpostor -30139000 NSysCfgVision_SVisionForest -3013A000 NSysCfgVision_SLightmap -3013B000 NSysCfgVision_SCptInGameplay -3013C000 NSysCfgVision_SCptInGame_Local -3013D000 NSysCfgVision_SCptInGame_Global -3013E000 NSysCfgVision_SNvHBAO -3013F000 NSysCfgVision_SSSAmbOcc -30140000 NSysCfgVision_SDeferred -30141000 CSysFidNodRefBase -30142000 NSysPlatform_SDirectLink -30143000 SScenePhy_DelayedScene -30144000 NSceneVisEntFx_STactical -30145000 NSceneVisEntFx_SVisibilityState -30146000 NSceneDyna_SMgrParams -30147000 NSceneDyna_SSleepingParams -30148000 NSceneDyna_SSolverParams -30149000 NSceneLayout_SLight -3014A000 NSceneLayout_SItem -3014B000 SSceneDestructibleRuntimePhy -3014C000 SSceneDestructibleFrozenPhy -3014D000 -3014E000 +30007000 NSceneVehiclePhy_SStuntStatus +30008000 NSceneVehiclePhy_SStuntFigure +30009000 NGameLoadProgress_SMgr +3000A000 NGameScriptChat_SManager +3000B000 NGameHud3d_SMgr +3000C000 NGameMenuSkinChooser_SMgr +3000D000 CWebServicesTaskResult_GhostDriver_UploadLimits +3000E000 CWebServicesTaskResult_GhostDriver_Download +3000F000 NPlugMaterial_SWater +30010000 NGameCollection_SCustomizableDeco +30011000 CNotification +30012000 CNotification_Prestige +30013000 CNotification_Squad +30014000 CNotification_PrestigeEarned +30015000 CNotification_SquadDeleted +30016000 CNotification_SquadInvitationAccepted +30017000 CNotification_SquadInvitationAdded +30018000 CNotification_SquadInvitationCanceled +30019000 CNotification_SquadInvitationCanceledForExitingPlayer +3001A000 CNotification_SquadInvitationCanceledForFullSquad +3001B000 CNotification_SquadInvitationDeclined +3001C000 CNotification_SquadInvitationReceived +3001D000 CNotification_SquadLockStateUpdated +3001E000 CNotification_SquadMemberAdded +3001F000 CNotification_SquadMemberKicked +30020000 CNotification_SquadMemberRemoved +30021000 CNotification_SquadUpdated +30022000 CSeasonMapInfo +30023000 CSeason +30024000 CAccountTrophyGain +30025000 CAccountTrophyGainForHistory +30026000 CAccountTrophyGainForHistory_CompetitionMatch +30027000 CAccountTrophyGainForHistory_CompetitionRanking +30028000 CAccountTrophyGainForHistory_LiveMatch +30029000 CAccountTrophyGainForHistory_SoloMedal +3002A000 CAccountTrophyGainForHistory_SoloRanking +3002B000 CAccountTrophyLastYearSummary +3002C000 CTrophyAchievement +3002D000 CTrophyAchievement_CompetitionMatch +3002E000 CTrophyAchievement_CompetitionRanking +3002F000 CTrophyAchievement_LiveMatch +30030000 CTrophyAchievement_SoloMedal +30031000 CTrophyAchievement_SoloRanking +30032000 CTrophySoloMedalAchievementLevelSettings +30033000 CTrophySoloMedalAchievementSettings +30034000 CMapRecord +30035000 NGameScriptChat_SContext +30036000 NGameScriptChat_SHistory +30037000 NGameScriptChat_SEntry +30038000 NGameScriptChat_SEvent +30039000 NGameScriptChat_SEvent_HistoryChange +3003A000 NGameScriptChat_SEvent_NewEntry +3003B000 CGameDirectLinkScript +3003C000 CGameDirectLinkScript_Home +3003D000 CGameDirectLinkScript_NewMap +3003E000 CGameDirectLinkScript_OfficialCampaign +3003F000 CGameDirectLinkScript_JoinServer +30040000 CGameDirectLinkScript_TrackOfTheDay +30041000 CGameDirectLinkScript_Ranked +30042000 CGameDirectLinkScript_Royal +30043000 CGameDirectLinkScript_ArcadeServer +30044000 CGameDirectLinkScript_Hotseat +30045000 CGameDirectLinkScript_Splitscreen +30046000 CGameDirectLinkScript_Garage +30047000 CGameDirectLinkScript_WaitingPage +30048000 CGameDirectLinkScript_JoinSession +30049000 CGameUserManagerScript_VoiceChatEvent +3004A000 CGameUserManagerScript_VoiceChatEvent_UserChange_IsSpeaking +3004B000 CGameUserManagerScript_VoiceChatEvent_UserChange_IsConnected +3004C000 CGameUserManagerScript_VoiceChatEvent_UserChange_IsMuted +3004D000 CGameUserManagerScript_VoiceChatEvent_SpeakingHasChanged +3004E000 CGameUserManagerScript_VoiceChatEvent_Message +3004F000 CGameUserManagerScript_VoiceChatEvent_DisplayUI +30050000 NGameEditorMap_SExperimentalFeatures +30051000 NPlugItemPlacement_STag +30052000 CAdvertisingManager +30053000 NGameMiniMap_SMgr +30054000 CGameVoiceChatConfigScript +30055000 SWebServicesTaskResult_GhostDriver_Download_Ghost +30056000 SWebServicesTaskResult_GhostDriver_Download_Member +30057000 SWebServicesTaskResult_GhostDriver_Download_Team +30058000 SWebServicesTaskResult_GhostDriver_UploadLimit +30059000 CGameDataFileTask_GhostDriver +3005A000 CGameDataFileTask_GhostDriver_UploadLimits +3005B000 CGameDataFileTask_GhostDriver_Upload +3005C000 CGameDataFileTask_GhostDriver_Download +3005D000 CFriend +3005E000 CSkinInfo +3005F000 CSquadInvitation +30060000 CSquadMember +30061000 CSquad +30062000 CNewsLink +30063000 CNews +30064000 CPrestige +30065000 CUserPrestige +30066000 CGameCtnMenuProfileScene +30067000 CNadeoServicesMap +30068000 CNadeoServicesItemCollection +30069000 CNadeoServicesSkin +3006A000 CZone +3006B000 CNadeoServicesItemCollectionVersion +3006C000 NSmArenaInterface_SMgr +3006D000 NPlugCurve_SSimpleCurveInPlace7 +3006E000 NSceneTransitoryBlockingSurfs_SMgr +3006F000 NSceneLightMapCloud_SServer +30070000 NSceneLightMapCloud_SClient +30071000 NScenePicking_SMgr +30072000 NSceneGateSpecial_SMgr +30073000 NSceneTimeshift_SMgr +30074000 NSceneRecorder_SMgr +30075000 NSmArenaPhysics_SMgr +30076000 NSmPlayerVis_SMgr +30077000 NSmPlayerPhy_SMgr +30078000 NSmArenaVis_SMgr +30079000 NGameConstraintPhy_SMgr +3007A000 NGameObjectPhy_SMgr +3007B000 NGameArenaState_SMgr +3007C000 NGameArenaVis_SMgr +3007D000 NGamePrefab_SMgr +3007E000 NGamePrefab_SInst +3007F000 NGamePrefab_SGridEntSpawner +30080000 NGamePrefabPhy_SMgr +30081000 NGamePrefabPhy_SInst +30082000 NSceneKinematicVis_SMgr +30083000 NSceneKinematicVis_SConstraint +30084000 NGameActionFxVis_SMgr +30085000 NGameShieldVis_SMgr +30086000 NGameShieldPhy_SMgr +30087000 NGameGateVis_SMgr +30088000 NGameGatePhy_SMgr +30089000 NGameWaypoint_SMgr +3008A000 NGameWaypoint_SSpawn +3008B000 NGameItem_SMgr +3008C000 NGameMediaClip_SMgr +3008D000 NGameSlotVis_SMgr +3008E000 NGameSlotPhy_SMgr +3008F000 NGameVehiclePhy_SMgr +30090000 NGameTurretVis_SMgr +30091000 NGameTurretPhy_SMgr +30092000 NGameObjectVis_SMgr +30093000 NGamePodiumVis_SMgr +30094000 NGamePodium_SMgr +30095000 NGamePodium_SPodium +30096000 NGameCamera_SMgr +30097000 NGameMapPhy_SMgr +30098000 NGameMgrMap_SMgr +30099000 NGameGhostClips_SMgr +3009A000 NGameGhost_SMgr +3009B000 NSceneItemPlacement_SMgr +3009C000 NSceneItemPlacement_SZone +3009D000 NSceneBulletPhy_SMgr +3009E000 NSceneDestructiblePhy_SMgr +3009F000 SSceneDestructibleDynaPhy +300A0000 SSceneDestructiblePhy +300A1000 +300A2000 NSceneDyna_SMgr +300A3000 NSceneDyna_SKinematicConstraint +300A5000 NSceneAdvert_SMgr +300A6000 NSceneMapColoring_SMgr +300A7000 NSceneModelKit_SMgr +300A8000 NSceneProp_SMgrPhy +300A9000 NSceneProp_SProp +300AA000 NSceneProp_SMgrVis +300AB000 NSceneConstruction_SMgrPhy +300AC000 NSceneConstruction_SConstruction +300AD000 NSceneConstruction_SMgrVis +300AE000 NSceneRopeVis_SMgr +300AF000 NSceneRopePhy_SMgr +300B0000 SSceneRopePhyEnt +300B1000 NSceneEditorHelper_SMgr +300B2000 NSceneEditorHelper_SHelper +300B3000 NSceneFlock_SMgr +300B5000 NSceneAnim_SMgr +300B6000 NSceneSolid2Vis_SMgr +300B7000 NSceneSound_SMgr +300B8000 NSceneSound_SSource +300B9000 NSceneSpectatorVis_SMgr +300BA000 NSceneParticleVis_SMgr +300BB000 NSceneCitizenNetwork_SMgr +300BC000 NSceneCitizenNetwork_SChunk +300BD000 NSceneRoad_SMgr +300BE000 NSceneRoad_SChunk +300BF000 NSceneRail_SMgr +300C0000 NSceneBulletVis_SMgr +300C1000 NSceneFxSystem_SMgr +300C2000 NSceneFxSystem_SFxSystemInstance +300C3000 NSceneWind_SMgrPhy +300C4000 NSceneTrainVis_SMgr +300C5000 NSceneTrainPhy_SMgr +300C6000 NSceneCharVis_SMgr +300C7000 NSceneVehicleVis_SMgr +300C8000 NSceneLight_SMgr +300C9000 NScenePathFinding_SMgr +300CA000 NSceneTrafficVis_SMgr +300CC000 NSceneTrafficPhy_SMgr +300CD000 NSceneVFX_SMgr +300CE000 NSceneVFX_SVFXInstance +300CF000 NSceneEdEntWrapper_SMgr +300D0000 NSceneEdEntWrapper_SWrapper +300D1000 NHmsForestVis_SMgr +300D2000 NHmsForestVis_STree +300D3000 NHmsMgrInstDyna2_SMgr +300D4000 SHmsLodGroup +300D5000 SHmsInstDyna +300D6000 SHmsMeshStatic +300D7000 NHmsZone_SMgrLightDynamic +300D8000 NHmsZone_SLightDyna +300DA000 NHmsCollision_SMgr +300DB000 NHmsCollision_SItem +300DC000 NScenePicking_SPickable +300DD000 GmTransQuat +300DE000 NPlugPainterLayer_SElem +300DF000 NPlugPainterLayer_SLayerVFX +300E0000 NPlugPainterLayer_SLayerDraw +300E1000 NPlugPainterLayer_SBitmapGroup +300E2000 NPlugAnim_SSkelPose +300E3000 NPlugAnim_SIKSkelPoseN +300E4000 NPlugAnim_SIKChainPoseN +300E5000 NPlugAnim_SIKChainPose +300E6000 NPlugAnim_SIKSkelMappingCache +300E7000 NPlugAnim_SIKChainMappingCache +300E8000 NPlugAnim_SIKSkelMapping +300E9000 NPlugAnim_SIKChainMapping +300EA000 NPlugAnim_SIKSkel +300EB000 SMetaPtr +300EC000 NHmsMgrVolume_SFogSimuParameters +300ED000 NFuncShaderLayerUV_STransSubTextureIn +300EE000 TSceneUId +300EF000 NGameAdvert_Simu_SMgr +300F0000 NGameAdvert_Anzu_SMgr +300F1000 Nat256 +300F2000 NGameAdvert_Test_SMgr +300F3000 EditorMeshPickingIdentifier +300F4000 NGamePrefab_SInstanceCreateParams +300F5000 NGamePrefab_SSceneEntListElem +300F6000 NGamePrefab_SGridParams +300F7000 NFastBlockAlloc_SAllocator +300F8000 NGamePrefabPhy_SSceneEntListElem +300F9000 NGamePrefabPhy_SInstanceCreateParams +300FA000 NSceneKinematicVis_SSharedSignal +300FB000 NGamePodiumVis_SConfig +300FC000 NGamePodiumVis_SSequence +300FD000 SGameHud3dParams +300FE000 NGameMenuSkinChooser_SDispParams +300FF000 NGameCamera_SCamSys +30100000 NGameScriptDebugger_SDebuggerMgr +30101000 NGameScriptDebugger_SWatchedVariable +30102000 NGameScriptDebugger_SWatchedVariableV2 +30103000 NGameVideoSource_SMgr +30104000 CAdvertisingSlot +30105000 NGameAdvert_Live_SMgr +30106000 NGameAdvert_Live_SAdsManager +30107000 NGameAdvert_Live_SAdSlotInternal +30108000 NGameAdvert_Live_SImpressionParams +30109000 NChatLog_SChatHistory +3010A000 NChatLog_SChatMsg +3010B000 NFastBucketAlloc_SAllocator +3010C000 NGameMgrMap_SMapInst +3010D000 NGameIconShooter_SSceneSetting +3010E000 NGameIconShooter_SCameraSetting +3010F000 CGameCtnMediaBlockGhostTM_SuperSKeyVal +30110000 NGameMediaBlockEntity_SuperSKeyVal +30111000 CGameCtnMediaBlockOpponentVisibility_SuperSKeyVal +30112000 CGameCtnMediaBlockDirtyLens_SKeyVal +30113000 CGameCtnMediaBlockCameraEffectScript_SKeyVal +30114000 CGameCtnMediaBlockVehicleLight_SuperSKeyVal +30115000 CGameCtnMediaBlockFog_SKeyVal +30116000 CGameCtnMediaBlockTimeSpeed_SKeyVal +30117000 CGameCtnMediaBlockBloomHdr_SKeyVal +30118000 CGameCtnMediaBlockToneMapping_SKeyVal +30119000 CGameCtnMediaBlockDOF_SKeyVal +3011A000 CGameCtnMediaBlock3dStereo_SKeyVal +3011B000 CGameCtnMediaBlockTransitionFade_SuperSKeyVal +3011C000 CGameCtnMediaBlockColorGrading_SuperSKeyVal +3011D000 CGameCtnMediaBlockText_SuperSKeyVal +3011E000 CGameCtnMediaBlockSpectators_SKeyVal +3011F000 CGameCtnMediaBlockSound_SuperSKeyVal +30120000 CGameCtnMediaBlockMusicEffect_SKeyVal +30121000 CGameCtnMediaBlockImage_SuperSKeyVal +30122000 CGameCtnMediaBlockCameraEffectShake_SKeyVal +30123000 CGameCtnMediaBlockCameraCustom_SKeyVal +30124000 CGameCtnMediaBlockCameraPath_SKeyVal +30125000 CGameCtnMediaBlockCameraOrbital_SKeyVal +30126000 CGameCtnMediaBlockTime_SKeyVal +30127000 CGameCtnMediaBlockFxCameraBlend_SKeyVal +30128000 CGameCtnMediaBlockFxColors_SKeyVal +30129000 SGameItemModelTree +3012A000 SGameBlockInfoTree +3012B000 SGameBlockInfoGroup +3012C000 NPlugSkin_SCustomizableBitmap +3012D000 NGameGhostClips_SClipPlayerGhost +3012E000 NGameMapItemPlacement_SMapData +3012F000 NGameMapItemPlacement_SZone +30130000 NGameMapItemPlacement_SZoneId +30131000 SGameCtnIdentifier +30132000 GmTransYawPitchRollDeg +30133000 NHmsLightMap_SCptBackgnd +30134000 CVisionVideoDecode +30135000 NSysCfgVision_SSubsurfaceScattering +30136000 CVisionHmsZone +30137000 NVisionHmsZone_SWaterPlaneVisibility +30138000 NVis_SBenchShader +30139000 NFilmicTone_PowerSegments_SCurveParamsUser +3013A000 NSysCfgVision_SVisionImpostor +3013B000 NSysCfgVision_SVisionForest +3013C000 NSysCfgVision_SLightmap +3013D000 NSysCfgVision_SCptInGameplay +3013E000 NSysCfgVision_SCptInGame_Local +3013F000 NSysCfgVision_SCptInGame_Global +30140000 NSysCfgVision_SNvHBAO +30141000 NSysCfgVision_SSSAmbOcc +30142000 NSysCfgVision_SDeferred +30143000 CSysFidNodRefBase +30144000 NSysPlatform_SDirectLink +30145000 SScenePhy_DelayedScene +30146000 NSceneVisEntFx_STactical +30147000 NSceneVisEntFx_SVisibilityState +30148000 NSceneDyna_SMgrParams +30149000 NSceneDyna_SSleepingParams +3014A000 NSceneDyna_SSolverParams +3014B000 NSceneLayout_SLight +3014C000 NSceneLayout_SItem +3014D000 SSceneDestructibleRuntimePhy +3014E000 SSceneDestructibleFrozenPhy 3014F000 30150000 30151000 @@ -2399,107 +2395,107 @@ 30158000 30159000 3015A000 -3015B000 NSceneDyna_SKinematicSharedSignal -3015C000 NSceneDyna_SItemArrayDyn -3015D000 NSceneDyna_SItemState -3015E000 NSceneDyna_SItemCreateParams -3015F000 NSceneDyna_SKinematicConstraintCreateParams -30160000 NSceneAdvert_SVisibilityTracker -30161000 NSceneAdvert_SAdSystemParams -30162000 SSceneMapColorisable01VisState -30163000 SSceneMapBaseVisState -30164000 NSceneAnim_SModel -30165000 NSceneAnim_SModelInst -30166000 NSceneAnim_SEdModelInstContext -30167000 NSceneAnim_SNodeState_StateMachine -30168000 NSceneAnim_SClipPlayer -30169000 NSceneAnim_SClipPlayerInput -3016A000 NSceneAnim_SInstInputBase -3016B000 NSceneAnim_SModelInstInput -3016C000 NSceneAnim_SNodeUpdateContextParams -3016D000 NSceneSpectatorVis_SInput -3016E000 NSceneSpectatorVis_SLocGenOptions -3016F000 NSceneSpectatorVis_SPositionGenOptions -30170000 NSceneSpectatorVis_SOrientationOpts -30171000 NSceneFxSystem_SRuntimeModel -30172000 NSceneFxSystem_SFxSystemInstanceInput -30173000 NSceneFxSystem_SFxSystemInstanceExpressionsUpdateParams -30174000 NMotionPrediction_SParams -30175000 CSceneVehicleVisParams -30176000 NSceneAnim_SChar -30177000 NSceneAnim_SCharInput -30178000 NSceneAnim_SGraphInstance -30179000 NSceneAnim_SCharState -3017A000 NSceneAnim_SGraphUpdateParams -3017B000 NSceneAnim_SGraphState -3017C000 NSceneAnim_SNode -3017D000 NSceneAnim_SNodeAim -3017E000 NSceneAnim_SNodeProceduralAttractor -3017F000 NSceneAnim_SNodeBlend2d -30180000 NSceneAnim_SNodeLocoGroup -30181000 NSceneAnim_SNodeClip -30182000 NSceneAnim_SNodeSequence -30183000 NSceneAnim_SNodeJump -30184000 NSceneAnim_SRootYaw -30185000 NScenePathFinding_SNavMeshBuildParams -30186000 NScenePathFinding_STileCacheHandler -30187000 NScenePathFinding_SPathRequestState -30188000 NScenePathFinding_SDynamicPathState -30189000 NScenePathFinding_SAgentModel -3018A000 NScenePathFinding_SAgentSize -3018B000 NScenePathFinding_SPathRequestInput -3018C000 NScenePathFinding_SPathRequestOutput -3018D000 NScenePathFinding_SPathRequestData -3018E000 NSceneVFX_SVFXInstanceInput -3018F000 NSceneVFX_SVFXInstanceNodeUpdateContext -30190000 SPlugExpr -30191000 NPlugGunLock_SParams -30192000 SPlugGraphNodeConnection -30193000 SPlugGraphVar -30194000 SPlugStateMachine_State -30195000 SPlugStateMachine_TransitionData -30196000 SPlugStateMachine_Transition -30197000 NPlugGpuHlsl_D3D12_SRootSign -30198000 NPlugGpuHlsl_D3D12_NRootSign_SParam -30199000 SPlugAnimUIRigNodeTypeConfig -3019A000 NPlugAnim_SPoseEditor_Model -3019B000 NPlugAnim_SAvatarAnimV0_Model -3019C000 NPlugAnim_SAvatarAnimV3_Model_Global -3019D000 NPlugAnim_SAvatarAnimV3_Model_Locomotion -3019E000 NPlugAnim_SAvatarAnimV3_Model_Jump -3019F000 NPlugAnim_SAvatarAnimV3_Model_Swim -301A0000 NPlugAnim_SAvatarAnimV3_Model_Idle -301A1000 NPlugAnim_SAvatarAnimV3_Model_Fire -301A2000 NPlugAnim_SAvatarAnim_Model_Rest -301A3000 NPlugAnim_SAvatarAnim_Model_Climb -301A4000 NPlugAnim_SAvatarAnimV3_Model_Gait -301A5000 NPlugAnim_SGaitSelector -301A6000 NPlugAnim_SLocomotionRotationModel -301A7000 NPlugAnim_SAvatarAnimV0_Model_Locomotion -301A8000 NPlugAnim_SAvatarAnimV0_Model_Tiredness -301A9000 NPlugAnim_SAvatarAnimV0_Model_Firing -301AA000 NPlugAnim_SAvatarAnimV0_Model_WeightInfluence -301AB000 NPlugCurve_SRichCurveInPlace4 -301AC000 SPlugAnimClipGroup -301AD000 NPlugItem_SVariant -301AE000 NPlugItemPlacement_SPatchLayoutDeprec -301AF000 NPlugItemPlacement_SPatchLayout -301B0000 NPlugItemPlacement_SIdGroup -301B1000 NPlugItemPlacement_SSizeGroup -301B2000 NPlugItemPlacement_SPlacementOption -301B3000 NPlugItemPlacement_STypeDef -301B4000 NPlugItemPlacement_STable -301B5000 NPlugItemPlacement_STypeInternal -301B6000 NPlugBulletModel_SElectroPulse -301B7000 NPlugBulletModel_SDamage -301B8000 NPlugBulletModel_SBlow -301B9000 NPlugAnim_SRigPose -301BA000 SPlugSpawnState -301BB000 GmBoxAligned -301BC000 SCamShakeParams -301BD000 -301BE000 -301BF000 +3015B000 +3015C000 +3015D000 +3015E000 NSceneDyna_SKinematicSharedSignal +3015F000 NSceneDyna_SItemArrayDyn +30160000 NSceneDyna_SItemState +30161000 NSceneDyna_SItemCreateParams +30162000 NSceneDyna_SKinematicConstraintCreateParams +30163000 NSceneAdvert_SVisibilityTracker +30164000 NSceneAdvert_SAdSystemParams +30165000 SSceneMapColorisable01VisState +30166000 SSceneMapBaseVisState +30167000 NSceneAnim_SModel +30168000 NSceneAnim_SModelInst +30169000 NSceneAnim_SEdModelInstContext +3016A000 NSceneAnim_SNodeState_StateMachine +3016B000 NSceneAnim_SClipPlayer +3016C000 NSceneAnim_SClipPlayerInput +3016D000 NSceneAnim_SInstInputBase +3016E000 NSceneAnim_SModelInstInput +3016F000 NSceneAnim_SNodeUpdateContextParams +30170000 NSceneSpectatorVis_SInput +30171000 NSceneSpectatorVis_SLocGenOptions +30172000 NSceneSpectatorVis_SPositionGenOptions +30173000 NSceneSpectatorVis_SOrientationOpts +30174000 NSceneFxSystem_SRuntimeModel +30175000 NSceneFxSystem_SFxSystemInstanceInput +30176000 NSceneFxSystem_SFxSystemInstanceExpressionsUpdateParams +30177000 NMotionPrediction_SParams +30178000 CSceneVehicleVisParams +30179000 NSceneAnim_SChar +3017A000 NSceneAnim_SCharInput +3017B000 NSceneAnim_SGraphInstance +3017C000 NSceneAnim_SCharState +3017D000 NSceneAnim_SGraphUpdateParams +3017E000 NSceneAnim_SGraphState +3017F000 NSceneAnim_SNode +30180000 NSceneAnim_SNodeAim +30181000 NSceneAnim_SNodeProceduralAttractor +30182000 NSceneAnim_SNodeBlend2d +30183000 NSceneAnim_SNodeLocoGroup +30184000 NSceneAnim_SNodeClip +30185000 NSceneAnim_SNodeSequence +30186000 NSceneAnim_SNodeJump +30187000 NSceneAnim_SRootYaw +30188000 NScenePathFinding_SNavMeshBuildParams +30189000 NScenePathFinding_STileCacheHandler +3018A000 NScenePathFinding_SPathRequestState +3018B000 NScenePathFinding_SDynamicPathState +3018C000 NScenePathFinding_SAgentModel +3018D000 NScenePathFinding_SAgentSize +3018E000 NScenePathFinding_SPathRequestInput +3018F000 NScenePathFinding_SPathRequestOutput +30190000 NScenePathFinding_SPathRequestData +30191000 NSceneVFX_SVFXInstanceInput +30192000 NSceneVFX_SVFXInstanceNodeUpdateContext +30193000 SPlugExpr +30194000 NPlugGunLock_SParams +30195000 SPlugGraphNodeConnection +30196000 SPlugGraphVar +30197000 SPlugStateMachine_State +30198000 SPlugStateMachine_TransitionData +30199000 SPlugStateMachine_Transition +3019A000 NPlugGpuHlsl_D3D12_SRootSign +3019B000 NPlugGpuHlsl_D3D12_NRootSign_SParam +3019C000 SPlugAnimUIRigNodeTypeConfig +3019D000 NPlugAnim_SPoseEditor_Model +3019E000 NPlugAnim_SAvatarAnimV0_Model +3019F000 NPlugAnim_SAvatarAnimV3_Model_Global +301A0000 NPlugAnim_SAvatarAnimV3_Model_Locomotion +301A1000 NPlugAnim_SAvatarAnimV3_Model_Jump +301A2000 NPlugAnim_SAvatarAnimV3_Model_Swim +301A3000 NPlugAnim_SAvatarAnimV3_Model_Idle +301A4000 NPlugAnim_SAvatarAnimV3_Model_Fire +301A5000 NPlugAnim_SAvatarAnim_Model_Rest +301A6000 NPlugAnim_SAvatarAnim_Model_Climb +301A7000 NPlugAnim_SAvatarAnimV3_Model_Gait +301A8000 NPlugAnim_SGaitSelector +301A9000 NPlugAnim_SLocomotionRotationModel +301AA000 NPlugAnim_SAvatarAnimV0_Model_Locomotion +301AB000 NPlugAnim_SAvatarAnimV0_Model_Tiredness +301AC000 NPlugAnim_SAvatarAnimV0_Model_Firing +301AD000 NPlugAnim_SAvatarAnimV0_Model_WeightInfluence +301AE000 NPlugCurve_SRichCurveInPlace4 +301AF000 SPlugAnimClipGroup +301B0000 NPlugItem_SVariant +301B1000 NPlugItemPlacement_SPatchLayoutDeprec +301B2000 NPlugItemPlacement_SPatchLayout +301B3000 NPlugItemPlacement_SIdGroup +301B4000 NPlugItemPlacement_SSizeGroup +301B5000 NPlugItemPlacement_SPlacementOption +301B6000 NPlugItemPlacement_STypeDef +301B7000 NPlugItemPlacement_STable +301B8000 NPlugItemPlacement_STypeInternal +301B9000 NPlugBulletModel_SElectroPulse +301BA000 NPlugBulletModel_SDamage +301BB000 NPlugBulletModel_SBlow +301BC000 NPlugAnim_SRigPose +301BD000 SPlugSpawnState +301BE000 GmBoxAligned +301BF000 SCamShakeParams 301C0000 301C1000 301C2000 @@ -2533,145 +2529,148 @@ 301DE000 301DF000 301E0000 -301E1000 NPlugAnim_SSkelImportJointLod -301E2000 NPlugAnim_SPoseGridImportPose -301E3000 NPlugAnim_SChannelGroupJointImport -301E4000 SMwIdRefSkel -301E5000 SMwIdRefRig -301E6000 SMwIdRefRigToSkel -301E7000 SMwIdRefChannelGroup -301E8000 SMwIdRefJointExprGroup -301E9000 SMwIdRefClip -301EA000 NPlugAnim_SJointExpr -301EB000 SFastRange -301EC000 GmTransYaw -301ED000 NPlugAnim_SAssetFiles -301EE000 SMwIdFid -301EF000 NPlugAnim_SAssetPaths -301F0000 SMwIdString -301F1000 SMwIdRefBase -301F2000 NPlugAdn_STag -301F3000 SPlugRandomMetaData -301F4000 SPlugAdnRandomGenSet -301F5000 NPlugAdn_STagType -301F6000 NPlugAdn_STagValue -301F7000 NPlugAdn_SContext -301F8000 NPlugAdn_STagTypeDef -301F9000 NPlugAdn_STagTable -301FA000 NPlugAdn_STagTypeInternal -301FB000 NPlugAdn_STagValueInternal -301FC000 NPlugMapAI_SNode -301FD000 NPlugMapAI_SNode_SpawnCitizen -301FE000 NPlugTVScreen_SModelInfo -301FF000 NPlugTVScreen_SSkinModel -30200000 NPlugClassicSkin_SSkinModel_SFxSystem -30201000 NPlugClassicSkin_SSkinModel -30202000 NPlugMatRemap_SSkinModel -30203000 NPlugParallaxScreen_SSkinModel -30204000 NPlugParallaxScreen_SSkinModel_Layer -30205000 NPlugSkinManialink_SSkinModel -30206000 NPlugSkinnedModel_SMgr -30207000 NPlugSkinnedModel_SModel -30208000 NPlugSkinnedModel_SSkin -30209000 NPlugSkinnedModel_SImage_SSampler -3020A000 NPlugSkinnedModel_SImage -3020B000 NPlugModelKit_SModelLib -3020C000 NPlugModelKit_SModelAssets -3020D000 NPlugModelKit_SPartAssets -3020E000 NPlugModelShading_SMaterialFiles -3020F000 NPlugModelKit_SPartFiles -30210000 NPlugModelKit_SPartFilesVersion -30211000 NPlugModelKit_SPartFilesVersions -30212000 NPlugModelKit_SOption -30213000 NPlugModelKit_SOptionVal -30214000 NPlugModelKit_SOptionArray -30215000 NPlugModelKit_SModelFiles -30216000 NPlugModelKit_SPartPaths -30217000 NPlugModelKit_SOptionDesc -30218000 NPlugModelKit_SOptionValDesc -30219000 NPlugModelKit_SOptionArrayDesc -3021A000 NPlugModelKit_SModelDesc -3021B000 NPlugModelKit_SFolder -3021C000 NPlugPrefab_SEnt_Void -3021D000 NPlugRoadChunk_SParams -3021E000 SPlugTrafficLight -3021F000 NPlugAnim_SEntTrack -30220000 NPlugAnim_SEntClip -30221000 NPlugAnim_SEntDesc -30222000 NPlugAnim_SEntBlock -30223000 NPlugAnim_SPropClip -30224000 NPlugAnim_SPropDesc -30225000 NPlugCurve_SRichCurve -30226000 NPlugNoise_SParams -30227000 NPlugModelLodMesh_SRange -30228000 NPlugGrass_SMatterArray -30229000 NPlugGrass_SModel -3022A000 NPlugGrass_SMatter -3022B000 NPlugGrass_SMatterModel -3022C000 GmSurfaceIds -3022D000 NPlugSkel_SJointLodSetup -3022E000 NPlugFilePreloader_SPreloadDesc -3022F000 NPlugFilePreloader_SPreloadDescGroup -30230000 NPlugFilePreloader_SPreloadDescFid -30231000 NPlugModelShading_SText_SShading_STmCarPrestige -30232000 NPlugModelShading_SText_SShading_STmCarPrestige_SMedal -30233000 NPlugModelShading_SText_SShading_SSampler -30234000 NPlugModelShading_SText_SShading_SColor -30235000 NPlugModelShading_SText_SShading_SConstant -30236000 NPlugModelShading_SText_SShading -30237000 NPlugModelShading_SText -30238000 NPlugModelShading_STextureSlotFile -30239000 NPlugModelShading_SDecalRender_StadiumSaisons -3023A000 SPlugParticleLaserEnergyStyle -3023B000 SPlugParticleLaserEnergyModel -3023C000 SPlugParticleEmitStateFromImpactModel -3023D000 SPlugParticleSimulatedSmokeModel -3023E000 SPlugParticlePrecalcModel -3023F000 SPlugParticlePhysicsModel -30240000 SPlugParticleRenderModel -30241000 NPlugCurve_SSimpleCurveInPlace4 -30242000 NPlugCurve_SColorGradient -30243000 SPlugParticleLifeModel -30244000 SPlugParticleSpawnModel -30245000 SPlugVFXNodeConnection -30246000 NPlugVeget_STreeModel -30247000 NPlugVeget_STreeLodModel -30248000 NPlugVeget_SMaterial -30249000 NPlugVeget_STreeLeafPropagationModel -3024A000 NPlugVeget_SShadedGeom -3024B000 NPlugDyna_SAnimFunc01 -3024C000 NPlugDyna_SAnimFuncNat -3024D000 NPlugDyna_SAnimFuncNatBase -3024E000 NPlugDyna_SAnimFunc01Base -3024F000 SPlugDynaWaterModel -30250000 SCBuffer -30251000 NPlugCurve_SRichCurveInPlace7 -30252000 NPlugCurve_SRichCurveKey -30253000 NPlugCurve_SSimpleCurve -30254000 NPlugBitmap_SAtlasCubeInElem -30255000 NProbabilityDistributionSampler_SAliasTable -30256000 GmTransYawPitchRoll -30257000 GmTransYawPitch -30258000 NFastPoolVirtual_SPoolBase -30259000 GmBoxNat3 -3025A000 SGmSmoothReal3Model -3025B000 TPlayerUId -3025C000 NHmsCollision_SItemCreateParams -3025D000 NHmsLightMapBlender_SMgr -3025E000 NHmsLightMapBlender_SFrame -3025F000 NHmsLightMapCache_SFrame -30260000 NHmsZoneOverlay_SClipRect -30261000 SHmsFxBloomHdr -30262000 SHmsFxToneMap -30263000 SHmsPostFxState -30264000 NHmsLightMap_SComputePImp -30265000 NHmsLightMap_SPImp -30266000 CHmsSolidVisCst_TmCar_SPrestige -30267000 CHmsSolid2 -30268000 NHmsZone_SLightDir -30269000 NHmsZone_SLightDynaFrustum -3026A000 NHmsZone_SLightDyna2 -3026B000 NHmsZone_SLightStatic -3026C000 NHmsZone_SMgrMeshStatic -3026D000 NHmsZone_NHmsMeshStatic_SModelRef -3026E000 CControlEffectSimi_SKeyVal \ No newline at end of file +301E1000 +301E2000 +301E3000 +301E4000 NPlugAnim_SSkelImportJointLod +301E5000 NPlugAnim_SPoseGridImportPose +301E6000 NPlugAnim_SChannelGroupJointImport +301E7000 SMwIdRefSkel +301E8000 SMwIdRefRig +301E9000 SMwIdRefRigToSkel +301EA000 SMwIdRefChannelGroup +301EB000 SMwIdRefJointExprGroup +301EC000 SMwIdRefClip +301ED000 NPlugAnim_SJointExpr +301EE000 SFastRange +301EF000 GmTransYaw +301F0000 NPlugAnim_SAssetFiles +301F1000 SMwIdFid +301F2000 NPlugAnim_SAssetPaths +301F3000 SMwIdString +301F4000 SMwIdRefBase +301F5000 NPlugAdn_STag +301F6000 SPlugRandomMetaData +301F7000 SPlugAdnRandomGenSet +301F8000 NPlugAdn_STagType +301F9000 NPlugAdn_STagValue +301FA000 NPlugAdn_SContext +301FB000 NPlugAdn_STagTypeDef +301FC000 NPlugAdn_STagTable +301FD000 NPlugAdn_STagTypeInternal +301FE000 NPlugAdn_STagValueInternal +301FF000 NPlugMapAI_SNode +30200000 NPlugMapAI_SNode_SpawnCitizen +30201000 NPlugTVScreen_SModelInfo +30202000 NPlugTVScreen_SSkinModel +30203000 NPlugClassicSkin_SSkinModel_SFxSystem +30204000 NPlugClassicSkin_SSkinModel +30205000 NPlugMatRemap_SSkinModel +30206000 NPlugParallaxScreen_SSkinModel +30207000 NPlugParallaxScreen_SSkinModel_Layer +30208000 NPlugSkinManialink_SSkinModel +30209000 NPlugSkinnedModel_SMgr +3020A000 NPlugSkinnedModel_SModel +3020B000 NPlugSkinnedModel_SSkin +3020C000 NPlugSkinnedModel_SImage_SSampler +3020D000 NPlugSkinnedModel_SImage +3020E000 NPlugModelKit_SModelLib +3020F000 NPlugModelKit_SModelAssets +30210000 NPlugModelKit_SPartAssets +30211000 NPlugModelShading_SMaterialFiles +30212000 NPlugModelKit_SPartFiles +30213000 NPlugModelKit_SPartFilesVersion +30214000 NPlugModelKit_SPartFilesVersions +30215000 NPlugModelKit_SOption +30216000 NPlugModelKit_SOptionVal +30217000 NPlugModelKit_SOptionArray +30218000 NPlugModelKit_SModelFiles +30219000 NPlugModelKit_SPartPaths +3021A000 NPlugModelKit_SOptionDesc +3021B000 NPlugModelKit_SOptionValDesc +3021C000 NPlugModelKit_SOptionArrayDesc +3021D000 NPlugModelKit_SModelDesc +3021E000 NPlugModelKit_SFolder +3021F000 NPlugPrefab_SEnt_Void +30220000 NPlugRoadChunk_SParams +30221000 SPlugTrafficLight +30222000 NPlugAnim_SEntTrack +30223000 NPlugAnim_SEntClip +30224000 NPlugAnim_SEntDesc +30225000 NPlugAnim_SEntBlock +30226000 NPlugAnim_SPropClip +30227000 NPlugAnim_SPropDesc +30228000 NPlugCurve_SRichCurve +30229000 NPlugNoise_SParams +3022A000 NPlugModelLodMesh_SRange +3022B000 NPlugGrass_SMatterArray +3022C000 NPlugGrass_SModel +3022D000 NPlugGrass_SMatter +3022E000 NPlugGrass_SMatterModel +3022F000 GmSurfaceIds +30230000 NPlugSkel_SJointLodSetup +30231000 NPlugFilePreloader_SPreloadDesc +30232000 NPlugFilePreloader_SPreloadDescGroup +30233000 NPlugFilePreloader_SPreloadDescFid +30234000 NPlugModelShading_SText_SShading_STmCarPrestige +30235000 NPlugModelShading_SText_SShading_STmCarPrestige_SMedal +30236000 NPlugModelShading_SText_SShading_SSampler +30237000 NPlugModelShading_SText_SShading_SColor +30238000 NPlugModelShading_SText_SShading_SConstant +30239000 NPlugModelShading_SText_SShading +3023A000 NPlugModelShading_SText +3023B000 NPlugModelShading_STextureSlotFile +3023C000 NPlugModelShading_SDecalRender_StadiumSaisons +3023D000 SPlugParticleLaserEnergyStyle +3023E000 SPlugParticleLaserEnergyModel +3023F000 SPlugParticleEmitStateFromImpactModel +30240000 SPlugParticleSimulatedSmokeModel +30241000 SPlugParticlePrecalcModel +30242000 SPlugParticlePhysicsModel +30243000 SPlugParticleRenderModel +30244000 NPlugCurve_SSimpleCurveInPlace4 +30245000 NPlugCurve_SColorGradient +30246000 SPlugParticleLifeModel +30247000 SPlugParticleSpawnModel +30248000 SPlugVFXNodeConnection +30249000 NPlugVeget_STreeModel +3024A000 NPlugVeget_STreeLodModel +3024B000 NPlugVeget_SMaterial +3024C000 NPlugVeget_STreeLeafPropagationModel +3024D000 NPlugVeget_SShadedGeom +3024E000 NPlugDyna_SAnimFunc01 +3024F000 NPlugDyna_SAnimFuncNat +30250000 NPlugDyna_SAnimFuncNatBase +30251000 NPlugDyna_SAnimFunc01Base +30252000 SPlugDynaWaterModel +30253000 SCBuffer +30254000 NPlugCurve_SRichCurveInPlace7 +30255000 NPlugCurve_SRichCurveKey +30256000 NPlugCurve_SSimpleCurve +30257000 NPlugBitmap_SAtlasCubeInElem +30258000 NProbabilityDistributionSampler_SAliasTable +30259000 GmTransYawPitchRoll +3025A000 GmTransYawPitch +3025B000 NFastPoolVirtual_SPoolBase +3025C000 GmBoxNat3 +3025D000 SGmSmoothReal3Model +3025E000 TPlayerUId +3025F000 NHmsCollision_SItemCreateParams +30260000 NHmsLightMapBlender_SMgr +30261000 NHmsLightMapBlender_SFrame +30262000 NHmsLightMapCache_SFrame +30263000 NHmsZoneOverlay_SClipRect +30264000 SHmsFxBloomHdr +30265000 SHmsFxToneMap +30266000 SHmsPostFxState +30267000 NHmsLightMap_SComputePImp +30268000 NHmsLightMap_SPImp +30269000 CHmsSolidVisCst_TmCar_SPrestige +3026A000 CHmsSolid2 +3026B000 NHmsZone_SLightDir +3026C000 NHmsZone_SLightDynaFrustum +3026D000 NHmsZone_SLightDyna2 +3026E000 NHmsZone_SLightStatic +3026F000 NHmsZone_SMgrMeshStatic +30270000 NHmsZone_NHmsMeshStatic_SModelRef +30271000 CControlEffectSimi_SKeyVal diff --git a/Tools/GbxDecompress/Program.cs b/Tools/GbxDecompress/Program.cs index ac1ea8d78..5570b6134 100644 --- a/Tools/GbxDecompress/Program.cs +++ b/Tools/GbxDecompress/Program.cs @@ -10,23 +10,15 @@ return; } -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); + +var folderName = "decompressed"; foreach (var fileName in args) { - Directory.CreateDirectory("decompressed"); - var outputFilePath = Path.GetDirectoryName(fileName) is string dir - ? Path.Combine(dir, "decompressed", Path.GetFileName(fileName)) - : Path.Combine("decompressed", Path.GetFileName(fileName)); + Directory.CreateDirectory(folderName); - var decompressed = Gbx.Decompress(fileName, outputFilePath); + Gbx.Decompress(fileName, Path.Combine(folderName, Path.GetFileName(fileName))); - if (decompressed) - { - Console.WriteLine($"{fileName} successfully decompressed."); - } - else - { - Console.WriteLine($"{fileName} is already decompressed."); - } + Console.WriteLine($"{fileName} successfully decompressed."); } \ No newline at end of file diff --git a/Tools/GbxDiff/Program.cs b/Tools/GbxDiff/Program.cs index b632fb9db..c19ba8020 100644 --- a/Tools/GbxDiff/Program.cs +++ b/Tools/GbxDiff/Program.cs @@ -13,7 +13,7 @@ Console.WriteLine("Actual: " + Path.GetFileName(args[1])); Console.WriteLine(); -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var gbx1 = Gbx.Parse(args[0]); var gbx2 = Gbx.Parse(args[1]); diff --git a/Tools/GbxDiscordBot/GbxDiscordBot.csproj b/Tools/GbxDiscordBot/GbxDiscordBot.csproj index 91eb5ea9e..f0a3caff4 100644 --- a/Tools/GbxDiscordBot/GbxDiscordBot.csproj +++ b/Tools/GbxDiscordBot/GbxDiscordBot.csproj @@ -23,12 +23,12 @@ - + - + - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Tools/GbxDiscordBot/Program.cs b/Tools/GbxDiscordBot/Program.cs index 8006151fe..3e10b6ee1 100644 --- a/Tools/GbxDiscordBot/Program.cs +++ b/Tools/GbxDiscordBot/Program.cs @@ -56,7 +56,7 @@ // Add services services.AddHttpClient(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddScoped(); diff --git a/Tools/GbxExplorer/Client/GbxExplorer.Client.csproj b/Tools/GbxExplorer/Client/GbxExplorer.Client.csproj index 006c32aef..b6b2079a6 100644 --- a/Tools/GbxExplorer/Client/GbxExplorer.Client.csproj +++ b/Tools/GbxExplorer/Client/GbxExplorer.Client.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/Tools/GbxExplorer/Component/GbxExplorer.Component.csproj b/Tools/GbxExplorer/Component/GbxExplorer.Component.csproj index dbf4f7ffb..684f0b34b 100644 --- a/Tools/GbxExplorer/Component/GbxExplorer.Component.csproj +++ b/Tools/GbxExplorer/Component/GbxExplorer.Component.csproj @@ -14,7 +14,7 @@ - + diff --git a/Tools/GbxExplorer/Server/GbxExplorer.Server.csproj b/Tools/GbxExplorer/Server/GbxExplorer.Server.csproj index e33fa1975..f94a44f36 100644 --- a/Tools/GbxExplorer/Server/GbxExplorer.Server.csproj +++ b/Tools/GbxExplorer/Server/GbxExplorer.Server.csproj @@ -20,7 +20,7 @@ - + diff --git a/Tools/GbxExplorerOld/Client/GbxExplorerOld.Client.csproj b/Tools/GbxExplorerOld/Client/GbxExplorerOld.Client.csproj index 5487b4448..14eb25a3e 100644 --- a/Tools/GbxExplorerOld/Client/GbxExplorerOld.Client.csproj +++ b/Tools/GbxExplorerOld/Client/GbxExplorerOld.Client.csproj @@ -24,17 +24,18 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/Tools/GbxExplorerOld/Client/Program.cs b/Tools/GbxExplorerOld/Client/Program.cs index a1cf96e6c..b5dbaf752 100644 --- a/Tools/GbxExplorerOld/Client/Program.cs +++ b/Tools/GbxExplorerOld/Client/Program.cs @@ -10,7 +10,7 @@ CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; -GBX.NET.Gbx.LZO = new GBX.NET.LZO.MiniLZO(); +GBX.NET.Gbx.LZO = new GBX.NET.LZO.Lzo(); GBX.NET.Gbx.CRC32 = new GBX.NET.Hashing.CRC32(); GBX.NET.Gbx.ZLib = new GBX.NET.ZLib.ZLib(); diff --git a/Tools/GbxExplorerOld/Client/Services/GbxService.cs b/Tools/GbxExplorerOld/Client/Services/GbxService.cs index 5ae688a64..501b82157 100644 --- a/Tools/GbxExplorerOld/Client/Services/GbxService.cs +++ b/Tools/GbxExplorerOld/Client/Services/GbxService.cs @@ -81,7 +81,8 @@ public GbxService(IJSRuntime js, ISettingsService settings, ILogger logger) { Logger = _logger, OpenPlanetHookExtractMode = _settings.OpenPlanetHookExtractMode, - IgnoreExceptionsInBody = true + IgnoreExceptionsInBody = true, + SafeSkippableChunks = true }, cancellationToken: cancellationToken); } diff --git a/Tools/GbxExplorerOld/Server/Dockerfile b/Tools/GbxExplorerOld/Server/Dockerfile index 6ed7f7794..689878821 100644 --- a/Tools/GbxExplorerOld/Server/Dockerfile +++ b/Tools/GbxExplorerOld/Server/Dockerfile @@ -1,12 +1,12 @@ -FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0 AS build ARG BUILD_CONFIGURATION=Release ARG TARGETARCH=x64 -RUN apk add --no-cache git +RUN apt-get update && apt-get install -y git python3 WORKDIR /src COPY .git/ ./.git/ -# RUN dotnet workload install wasm-tools +RUN dotnet workload install wasm-tools # copy csproj and restore as distinct layers COPY Tools/GbxExplorerOld/Server/*.csproj Tools/GbxExplorerOld/Server/ @@ -31,7 +31,7 @@ RUN dotnet publish Tools/GbxExplorerOld/Server -c $BUILD_CONFIGURATION -a $TARGE # final stage/image -FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine +FROM mcr.microsoft.com/dotnet/aspnet:8.0 EXPOSE 8080 EXPOSE 8081 WORKDIR /app diff --git a/Tools/GbxExplorerOld/Server/GbxExplorerOld.Server.csproj b/Tools/GbxExplorerOld/Server/GbxExplorerOld.Server.csproj index 87deceaad..bc48e6927 100644 --- a/Tools/GbxExplorerOld/Server/GbxExplorerOld.Server.csproj +++ b/Tools/GbxExplorerOld/Server/GbxExplorerOld.Server.csproj @@ -11,7 +11,7 @@ - + @@ -20,7 +20,7 @@ - + diff --git a/Tools/GbxToJson/Program.cs b/Tools/GbxToJson/Program.cs index 754dc29ff..232163f01 100644 --- a/Tools/GbxToJson/Program.cs +++ b/Tools/GbxToJson/Program.cs @@ -9,7 +9,7 @@ Console.ReadKey(true); } -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); var gbx = Gbx.Parse(args[0]); diff --git a/Tools/ParseRepeater/Program.cs b/Tools/ParseRepeater/Program.cs index 123800cdd..0154d3de7 100644 --- a/Tools/ParseRepeater/Program.cs +++ b/Tools/ParseRepeater/Program.cs @@ -13,7 +13,7 @@ } var fileName = args[0]; -Gbx.LZO = new MiniLZO(); +Gbx.LZO = new Lzo(); Gbx.ZLib = new ZLib(); var logger = LoggerFactory.Create(builder =>