Skip to content

Commit

Permalink
Major refactoring
Browse files Browse the repository at this point in the history
Getting ready for more...
  • Loading branch information
xoascf committed Sep 25, 2023
1 parent 42e720b commit 7b0d076
Show file tree
Hide file tree
Showing 60 changed files with 820 additions and 1,224 deletions.
53 changes: 19 additions & 34 deletions OTRMod.CLI/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,7 @@ internal static string ReadPath(string name, string fallback = "", bool checkIfE
} while (string.IsNullOrWhiteSpace(path));

if (path.StartsWith("\"") && path.EndsWith("\""))
#if NETCOREAPP3_0_OR_GREATER
path = path[1..^1];
#else
path = path.Substring(1, path.Length - 2);
#endif

while (checkIfExists && !File.Exists(path)) {
Con.WriteLine("File not found!");
Expand All @@ -51,13 +47,12 @@ internal static string ReadPath(string name, string fallback = "", bool checkIfE
internal static bool AnsweredYesTo(string question) {
Con.Write($"{question} [Y/n] ");
string? res = Con.ReadLine();
return string.IsNullOrEmpty(res)
return res.IsNullOrEmpty()
|| res.StartsWith("y", StringComparison.OrdinalIgnoreCase);
}

internal static string? GetIfExists(this string[] array, int index) {
return array.Length > index ? array[index] : null;
}
internal static string? GetIfExists(this string[] array, int index)
=> array.Length > index ? array[index] : null;

internal static int GetArgIndex(this string[] args, string argMain, char argAlt) {
int argIndex = Array.IndexOf(args, $"--{argMain}");
Expand All @@ -71,36 +66,27 @@ internal static int GetArgIndex(this string[] args, string argMain, char argAlt)
return argIndex != -1 ? args.GetIfExists(argIndex + 1) : null;
}

internal static char[] GetInvalidChars() {
return new char[] { '<', '>', '|', ':', '*', '?' };
}
internal static char[] GetInvalidChars()
=> new[] { '<', '>', '|', ':', '*', '?' };

internal static readonly string InvalidCharsPattern = $"[{Regex.Escape(new string(GetInvalidChars()))}]";
internal static readonly string InvalidCharsPattern
= $"[{Regex.Escape(new string(GetInvalidChars()))}]";

internal static string EncodePath(string path) {
return Regex.Replace(path, InvalidCharsPattern, m => {
return "%" + ((int)m.Value[0]).ToString("X2");
});
}
internal static string EncodePath(string path)
=> Regex.Replace(path, InvalidCharsPattern, m
=> "%" + ((int)m.Value[0]).ToString("X2"));

internal static string DecodePath(string path) {
return Regex.Replace(path, "%[0-9A-F]{2}", m => {
#if NETCOREAPP3_0_OR_GREATER
string hexValue = m.Value[1..];
#else
string hexValue = m.Value.Substring(1);
#endif
char decodedChar = (char)Convert.ToInt32(hexValue, 16);
if (Array.IndexOf(GetInvalidChars(), decodedChar) != -1)
return decodedChar.ToString();

return m.Value;
internal static string DecodePath(string path)
=> Regex.Replace(path, "%[0-9A-F]{2}", hex => {
char decodedChar = (char)Convert.ToInt32(hex.Value[1..], 16);
return Array.IndexOf(GetInvalidChars(), decodedChar) != -1
? decodedChar.ToString()
: hex.Value;
});
}

internal static void Save(this Stream s, string path) {
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir))
if (!dir.IsNullOrEmpty())
Directory.CreateDirectory(dir);

using FileStream fs = new(path, FileMode.OpenOrCreate);
Expand All @@ -110,7 +96,6 @@ internal static void Save(this Stream s, string path) {
fs.Close();
}

internal static void Warn(string issue, int line, string file) {
Con.WriteLine($"::warning file={file},line={line}::{issue}");
}
internal static void Warn(string issue, int line, string file)
=> Con.WriteLine($"::warning file={file},line={line}::{issue}");
}
66 changes: 31 additions & 35 deletions OTRMod.CLI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
using OTRMod.ROM;
using OTRMod.Utility;

using System.Text;

static MemStream Run(string pathImage, bool romMode, bool calc, out string outName) {
bool decompressOnly = romMode && calc;
outName = "Decompressed.z64";
Expand All @@ -16,8 +14,9 @@ static MemStream Run(string pathImage, bool romMode, bool calc, out string outNa
if (romMode)
iData = Decompressor.Data(iData.ToBigEndian(), calc: calc);
MemStream ms;
if (decompressOnly)
if (decompressOnly) {
ms = new MemStream(iData);
}
else {
ms = new MemStream();
ms.SetLength(0);
Expand All @@ -40,7 +39,7 @@ static MemStream Run(string pathImage, bool romMode, bool calc, out string outNa

static void TUIRun(bool romMode, bool calc) {
using MemStream genMs = Run(ReadPath("Image"), romMode, calc, out string outName);
genMs.Save(ReadPath($"Output", outName, false));
genMs.Save(ReadPath("Output", outName, false));
genMs.Flush();
genMs.Close();
#if NETCOREAPP1_0_OR_GREATER
Expand All @@ -49,19 +48,19 @@ static void TUIRun(bool romMode, bool calc) {
}

static void Extract(string? filePath = null, string? outDir = null) {
Dictionary<string, Stream> OTRFiles = new();
Dictionary<string, Stream> otrFiles = new();
filePath ??= ReadPath("OTR");

Con.WriteLine("Loading...");
using FileStream fs = new(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Load.From(fs, ref OTRFiles);
Load.From(fs, ref otrFiles);
outDir ??= ReadPath("Output", "Extracted", false);

Con.WriteLine("Extracting...");
foreach (KeyValuePair<string, Stream> file in OTRFiles)
foreach (KeyValuePair<string, Stream> file in otrFiles)
file.Value.Save(Path.Combine(outDir, EncodePath(file.Key)));

OTRFiles.Clear();
otrFiles.Clear();
Con.WriteLine("Extraction complete.");
}

Expand All @@ -72,7 +71,7 @@ static void GenerateGeneric(string inputDir, string? outPath = null) {

if (outPath is null) {
outPath = $"{Path.GetFileName(inputDir)}.otr";
outPath = ReadPath($"Output", outPath, false);
outPath = ReadPath("Output", outPath, false);
}

ms.Save(outPath);
Expand All @@ -83,25 +82,26 @@ static void GenerateGeneric(string inputDir, string? outPath = null) {
static void AddSequence(string[] meta, string path, byte[] seqData) {
string font = meta[1];
if (font.StartsWith("0x")) {
#if NETCOREAPP3_0_OR_GREATER
font = font[2..];
#else
font = font.Substring(2);
#endif
}
else if (font == "-") {
Warn($"Sequence uses custom Audiobank, skipping...", 2, path); /* FIXME */
Warn("Sequence uses custom Audiobank, skipping...", 2, path); /* FIXME */
return;
}
else
else {
Warn("Audiobank index is expected to start with '0x'", 2, path);
}

string? type = meta.GetIfExists(2);
if (type is null || string.IsNullOrEmpty(type)) {
if (type.IsNullOrEmpty()) {
Warn("No sequence type found, using 'bgm'", 3, path);
type = "bgm";
}
#if NETCOREAPP3_0_OR_GREATER
else if (type.Contains(' ')) {
#else
else if (type.Contains(" ")) {
#endif
Warn("Sequence type contains spaces", 3, path);
type = type.Trim();
}
Expand All @@ -116,7 +116,7 @@ static void AddSequence(string[] meta, string path, byte[] seqData) {
seqFont = 0;
}

seqData = Format.Audio.ExportSeq(0, seqFont, cachePolicy, seqData);
seqData = OTRMod.Z.Audio.ExportSeq(0, seqFont, cachePolicy, seqData);
string name = meta[0].Replace('/', '|');
path = $"custom/music/{name}_{type}";

Expand All @@ -137,35 +137,35 @@ static void AutoGenerate(string? inputDir = null, string? outPath = null) {
using FileStream fs = new(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using ZipFile zip = ZipFile.Read(fs);

MemStream seqMS = new();
MemStream metaMS = new();
MemStream seqMs = new();
MemStream metaMs = new();
string? metaPath = null;

foreach (ZipEntry entry in zip.Entries) {
if (entry.FileName.EndsWith(".zbank", StringComparison.OrdinalIgnoreCase)) {
seqMS.SetLength(0);
metaMS.SetLength(0);
seqMs.SetLength(0);
metaMs.SetLength(0);
metaPath = null;
Con.WriteLine($"Skipping {file}");
break;
}
if (entry.FileName.EndsWith(".seq", StringComparison.OrdinalIgnoreCase)) {
entry.Extract(seqMS);
}
if (entry.FileName.EndsWith(".seq", StringComparison.OrdinalIgnoreCase))
entry.Extract(seqMs);

if (entry.FileName.EndsWith(".meta", StringComparison.OrdinalIgnoreCase)) {
entry.Extract(metaMS);
entry.Extract(metaMs);
metaPath = Path.Combine(file, entry.FileName);
}
}

if (seqMS.Length == 0 || metaMS.Length == 0 || metaPath is null)
if (seqMs.Length == 0 || metaMs.Length == 0 || metaPath is null)
continue;

Con.WriteLine($"Adding {file}");

string[] ootrsMetas = metaMS.ToArray().ToStringArray(Encoding.GetEncoding("iso-8859-1"));
string[] ootrsMetas = metaMs.ToArray().ToStringArray();

AddSequence(ootrsMetas, metaPath, seqMS.ToArray());
AddSequence(ootrsMetas, metaPath, seqMs.ToArray());
}

if (files.Find(a => a.Contains(".zbank")) is not null) {
Expand All @@ -181,7 +181,7 @@ static void AutoGenerate(string? inputDir = null, string? outPath = null) {

Con.WriteLine($"Adding {subFolder}");

string[] metas = File.ReadAllLines(metaFile, Encoding.GetEncoding("iso-8859-1"));
string[] metas = File.ReadAllLines(metaFile, SturmScharf.EncodingProvider.Latin1);
byte[] seq = File.ReadAllBytes(seqFile);

AddSequence(metas, metaFile, seq);
Expand All @@ -196,13 +196,9 @@ static void Build(string? inputDir = null, string? outPath = null) {
string[] filePaths = Directory.GetFiles(inputDir, "*", SearchOption.AllDirectories);

foreach (string filePath in filePaths) {
#if NETCOREAPP3_0_OR_GREATER
string newPath = filePath[inputDir.Length..].Replace(@"\", "/");
if (newPath.StartsWith("/")) newPath = newPath[1..];
#else
string newPath = filePath.Substring(inputDir.Length).Replace(@"\", "/");
if (newPath.StartsWith("/")) newPath = newPath.Substring(1);
#endif
if (newPath.StartsWith("/"))
newPath = newPath[1..];
byte[] fileBytes = File.ReadAllBytes(filePath);
Generate.AddFile(DecodePath(newPath), fileBytes);
}
Expand Down
8 changes: 4 additions & 4 deletions OTRMod.Web/App.razor
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
@inject IJSRuntime JsRuntime
@code {
protected override async Task OnInitializedAsync() {
await JsRuntime.InvokeVoidAsync("setLang", T["lang_tag"].ToString());
protected override async Task OnInitializedAsync()
=> await JsRuntime.InvokeVoidAsync("setLang", T["lang_tag"].ToString());
}
}
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
<FocusOnNavigate RouteData="@routeData" Selector="h1"/>
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>@T["error_404_title"]</PageTitle>
Expand Down
2 changes: 1 addition & 1 deletion OTRMod.Web/OTRMod.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

<ItemGroup>
<PackageReference Include="BlazorDownloadFile" Version="2.4.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="7.0.11" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="7.0.7" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.Localization" Version="7.0.7" />
<PackageReference Include="Toolbelt.Blazor.PWA.Updater" Version="2.1.0.1" />
Expand Down
12 changes: 2 additions & 10 deletions OTRMod.Web/Pages/Index.razor
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
@page "/"
@using System.Text
@using BlazorDownloadFile
@using OTRMod.ROM
@using OTRMod.OTR
Expand Down Expand Up @@ -85,8 +84,8 @@ private async Task GenerateOTR() {
}

private async Task RunProcess() {
_script = _scriptMs.ToArray().ToStringArray(Encoding.ASCII);
byte[] decompressed = Decompressor.Data(ReadFully(_romMs).ToBigEndian(), calc: false);
_script = _scriptMs.ToArray().ToStringArray();
byte[] decompressed = Decompressor.Data(_romMs.ToArray().ToBigEndian(), calc: false);
ScriptParser sParser = new() {
ScriptStrings = _script,
ImageData = decompressed,
Expand All @@ -96,11 +95,4 @@ private async Task RunProcess() {
Generate.FromImage(ref _otrMs);
await DlFileService.DownloadFile(sParser.OTRFileName, _otrMs, "application/octet-stream");
}

private static byte[] ReadFully(Stream stream) {
if (stream is MemoryStream ms) return ms.ToArray();
using MemoryStream memoryStream = new();
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
6 changes: 2 additions & 4 deletions OTRMod.Web/Shared/Resources/Resource.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion OTRMod/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@

global using OTRMod.ID;
global using static OTRMod.Utility.IO;
global using static OTRMod.OTR.Format;
global using ByteOrder = OTRMod.ID.ByteOrder.Type;
#if NET40
global using BitOperations = SturmScharf.Compat.BitOperations;
#endif
1 change: 1 addition & 0 deletions OTRMod/ID/ResourceType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ public enum ResourceType {
AudioSoundFont = 0x4F534654, /* OSFT */
AudioSequence = 0x4F534551, /* OSEQ */
Background = 0x4F424749, /* OBGI */
SceneCommand = 0x4F52434D, /* ORCM */
}
22 changes: 12 additions & 10 deletions OTRMod/ID/Texture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace OTRMod.ID;
* ZAPD - ZTexture.h
*/

internal static class Texture {
public static class Texture {
public enum Codec {
Error = 0,

Expand All @@ -30,13 +30,15 @@ public enum Codec {
JPEG32,
}

private static double GetMultiplier(Codec codec) => codec switch {
Codec.RGBA32 => 4,
Codec.RGBA16 or Codec.IA16 => 2,
Codec.CI8 or Codec.I8 or Codec.IA8 => 1,
Codec.CI4 or Codec.I4 or Codec.IA4 => 0.5,
_ => 0,
};

public static int GetSize(Codec codec, int wxh) => (int)(wxh * GetMultiplier(codec));
private static double GetMultiplier(Codec codec)
=> codec switch {
Codec.RGBA32 => 4,
Codec.RGBA16 or Codec.IA16 => 2,
Codec.CI8 or Codec.I8 or Codec.IA8 => 1,
Codec.CI4 or Codec.I4 or Codec.IA4 => 0.5,
_ => 0,
};

public static int GetSize(Codec codec, int wxh)
=> (int)(wxh * GetMultiplier(codec));
}
Loading

0 comments on commit 7b0d076

Please sign in to comment.